tob*_*gue 64 python classification machine-learning scikit-learn
liblinear和nltk等机器学习包中的分类器提供了一种方法show_most_informative_features()
,它对调试功能非常有用:
viagra = None ok : spam = 4.5 : 1.0
hello = True ok : spam = 4.5 : 1.0
hello = None spam : ok = 3.3 : 1.0
viagra = True spam : ok = 3.3 : 1.0
casino = True spam : ok = 2.0 : 1.0
casino = None ok : spam = 1.5 : 1.0
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果在scikit-learn中为分类器实现类似的东西.我搜索了文档,但找不到类似的东西.
如果还没有这样的功能,有人知道如何获得这些值吗?
非常感谢!
Fre*_*Foo 59
分类器本身不记录特征名称,它们只是看到数字数组.但是,如果使用Vectorizer
/ CountVectorizer
/ TfidfVectorizer
/ 提取要素DictVectorizer
,并且使用线性模型(例如LinearSVC
Naive Bayes),则可以应用文档分类示例使用的相同技巧.示例(未经测试,可能包含一两个错误):
def print_top10(vectorizer, clf, class_labels):
"""Prints features with the highest coefficient values, per class"""
feature_names = vectorizer.get_feature_names()
for i, class_label in enumerate(class_labels):
top10 = np.argsort(clf.coef_[i])[-10:]
print("%s: %s" % (class_label,
" ".join(feature_names[j] for j in top10)))
Run Code Online (Sandbox Code Playgroud)
这是用于多类分类; 对于二进制的情况,我认为你应该clf.coef_[0]
只使用.你可能要排序class_labels
.
tob*_*gue 51
在larsmans代码的帮助下,我想出了二进制案例的代码:
def show_most_informative_features(vectorizer, clf, n=20):
feature_names = vectorizer.get_feature_names()
coefs_with_fns = sorted(zip(clf.coef_[0], feature_names))
top = zip(coefs_with_fns[:n], coefs_with_fns[:-(n + 1):-1])
for (coef_1, fn_1), (coef_2, fn_2) in top:
print "\t%.4f\t%-15s\t\t%.4f\t%-15s" % (coef_1, fn_1, coef_2, fn_2)
Run Code Online (Sandbox Code Playgroud)
Cli*_*cks 15
要添加更新,RandomForestClassifier
现在支持该.feature_importances_
属性.此属性告诉您该功能解释了多少观察到的方差.显然,所有这些值的总和必须<= 1.
我发现这个属性在执行特征工程时非常有用.
感谢scikit-learn团队和贡献者实现这一目标!
编辑:这适用于RandomForest和GradientBoosting.因此RandomForestClassifier
,RandomForestRegressor
,GradientBoostingClassifier
和GradientBoostingRegressor
所有支持这一点.
我们最近发布了一个库(https://github.com/TeamHG-Memex/eli5),允许这样做:它处理来自scikit-learn,二进制/多类情况的variuos分类器,允许根据特征值突出显示文本,与IPython等集成
小智 6
实际上,我必须在 NaiveBayes 分类器上找出特征重要性,尽管我使用了上述函数,但我无法根据类获得特征重要性。我浏览了 scikit-learn 的文档并对上述函数进行了一些调整,发现它可以解决我的问题。希望对你也有帮助!
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")
for coef, feat in topn_class1:
print(class_labels[0], coef, feat)
print("-----------------------------------------")
print("Important words in positive reviews")
for coef, feat in topn_class2:
print(class_labels[1], coef, feat)
Run Code Online (Sandbox Code Playgroud)
请注意,您的分类器(在我的例子中是 NaiveBayes)必须具有属性 feature_count_ 才能正常工作。
归档时间: |
|
查看次数: |
45365 次 |
最近记录: |