python - 使用 SGD 分类器和 GridsearchCV 查找最重要的特征

标签 python machine-learning scikit-learn grid-search

# Implementing Linear_SGD classifier
clf = linear_model.SGDClassifier(max_iter=1000)
Cs = [0.0001,0.001, 0.01, 0.1, 1, 10]
tuned_parameters = [{'alpha': Cs}]
model = GridSearchCV(clf, tuned_parameters, scoring = 'accuracy', cv=2)
model.fit(x_train, Y_train)

如何从下面的代码中找到最重要的功能,因为它显示错误 feature_count_。

这里我的矢量化器是 BOW,分类器是带有铰链损失的 SGDclassifier

def important_features(vectorizer,classifier,n=20):
    class_labels = classifier.classes_
    feature_names =vectorizer.get_feature_names()
    topn_class1 = sorted(zip(classifier.feature_count_[0], 
    feature_names),reverse=True)[:n]
    topn_class2 = sorted(zip(classifier.feature_count_[1], 
    feature_names),reverse=True)[:n]
    print("Important words in negative reviews")

我尝试使用上面的代码,但它显示错误为

AttributeError                            Traceback (most recent call last)
<ipython-input-77-093048fb461e> in <module>()
----> 1 important_features(Timesort_X_vec,model)

<ipython-input-75-10b9d6ee3f81> in important_features(vectorizer, 
classifier, n)
  2     class_labels = classifier.classes_
  3     feature_names =vectorizer.get_feature_names()
   ----> 4     topn_class1 = sorted(zip(classifier.feature_count_[0], 
feature_names),reverse=True)[:n]
  5     topn_class2 = sorted(zip(classifier.feature_count_[1], 
feature_names),reverse=True)[:n]
  6     print("Important words in negative reviews")

 AttributeError: 'GridSearchCV' object has no attribute 'feature_count_'.

由于我是编程新手,请帮我解答。谢谢

最佳答案

错误的原因是您使用的 SGDClassifier 没有 feature_count_ 属性(检查 docs 中的可用属性):

from sklearn.linear_model import SGDClassifier  

X = [[0., 0.], [1., 1.]]
y = [0, 1]
clf = SGDClassifier(loss="hinge", penalty="l2", max_iter=5)
clf.fit(X, y) 

clf.feature_count_
[...]
AttributeError: 'SGDClassifier' object has no attribute 'feature_count_'

最初我认为问题在于您使用的是 GridSearchCV 对象,但事实并非如此,因为函数内的 class_labels = classifier.classes_ 行不会引发任何错误;尽管从文档看来 SGDClassifier 甚至没有 classes_ 属性,但实际上事实证明它确实有:

clf.classes_
# array([0, 1])

据我所知,scikit-learn 中唯一包含 feature_count_ 属性的分类器是 BernoulliNB , MultinomialNB ,和ComplementNB ,所有朴素贝叶斯家族,虽然我不太确定它可以像你打算在这里使用它一样使用......

关于python - 使用 SGD 分类器和 GridsearchCV 查找最重要的特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52644634/

相关文章:

python - Pytube : urllib. error.HTTPError: HTTP Error 410: Gone

python - HTTP 基本身份验证似乎不适用于 python 中的 urllib2

python - 重新拟合决策树以添加层

python - 使用 CountVectorizer 进行词干提取后对文本数据集进行矢量化时得到全零

python - 如何向 Firestore 中的现有数组添加非唯一元素?

python - 生成器内的 for 循环?

machine-learning - Keras ROC 与 Scikit ROC 不同吗?

python - 使用 keras 模型中的 tensorflow 图进行预测

matlab - 使用 MATLAB 查找拉长的簇

python - 试图将四阶回归多项式拟合到散点图,但我得到了一个奇怪的结果