如何为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

我的问题是,是否为scikit-learn中的分类器实现了类似的东西。我搜索了文档,但找不到类似的东西。

如果还没有这样的功能,是否有人知道如何获得这些值的解决方法?

分类器本身不记录特征名称,它们只看到数字数组。但是,如果您使用 Vectorizer/CountVectorizer/TfidfVectorizer/DictVectorizer 提取特征,并且您使用的是线性模型(例如 LinearSVC或朴素贝叶斯),然后您可以应用文档分类示例使用的相同技巧。示例(未经测试,可能包含一两个错误):

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)))

这是针对多类分类的;对于二进制情况,我认为您应该只使用clf.coef_[0]。您可能需要对class_labels进行排序。

在 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%.4ft%-15stt%.4ft%-15s" % (coef_1, fn_1, coef_2, fn_2)

若要添加更新,RandomForestClassifier现在支持 .feature_importances_ 属性。此属性告诉您该特征解释了多少观测方差。显然,所有这些值的总和必须为 <= 1。

我发现此属性在执行特征工程时非常有用。

感谢scikit-learn团队和贡献者实施这一点!

编辑:这适用于RandomForest和GradientBoosting。所以RandomForestClassifierRandomForestRegressorGradientBoostingClassifierGradientBoostingRegressor都支持这一点。

我们最近发布了一个库(https://github.com/TeamHG-Memex/eli5),它允许这样做:它处理来自scikit-learn,二进制/多类案例的各种分类器,允许根据特征值突出显示文本,与IPython集成等。

我实际上必须在我的 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)

请注意,您的分类器(在我的例子中是朴素贝叶斯)必须具有属性feature_count_才能正常工作。

您还可以执行以下操作来按顺序创建重要性特征的图形:

importances = clf.feature_importances_
std = np.std([tree.feature_importances_ for tree in clf.estimators_],
         axis=0)
indices = np.argsort(importances)[::-1]
# Print the feature ranking
#print("Feature ranking:")

# Plot the feature importances of the forest
plt.figure()
plt.title("Feature importances")
plt.bar(range(train[features].shape[1]), importances[indices],
   color="r", yerr=std[indices], align="center")
plt.xticks(range(train[features].shape[1]), indices)
plt.xlim([-1, train[features].shape[1]])
plt.show()

RandomForestClassifier还没有coef_属性,但我认为它会在 0.17 版本中。但是,请参阅使用 scikit-learn 在随机森林上的递归特征消除中的RandomForestClassifierWithCoef类。这可能会为您提供一些解决上述限制的想法。

不完全是您要查找的内容,但是一种获取最大幅度系数的快速方法(假设 pandas 数据帧列是您的特征名称):

你训练了模型,如下所示:

lr = LinearRegression()
X_train, X_test, y_train, y_test = train_test_split(df, Y, test_size=0.25)
lr.fit(X_train, y_train)

获取 10 个最大的负系数值(或更改为 reverse=True 表示最大正值),如下所示:

sorted(list(zip(feature_df.columns, lr.coef_)), key=lambda x: x[1], 
reverse=False)[:10]

首先做一个列表,我给这个列表一个名称标签。 之后提取所有功能名称和列名称,我添加到标签列表中。这里我使用朴素贝叶斯模型。在朴素贝叶斯模型中,feature_log_prob_给出特征的概率。

def top20(model,label):
  feature_prob=(abs(model.feature_log_prob_))
  for i in range(len(feature_prob)):
    print ('top 20 features for {} class'.format(i))
    clas = feature_prob[i,:]
    dictonary={}
    for count,ele in enumerate(clas,0): 
      dictonary[count]=ele
    dictonary=dict(sorted(dictonary.items(), key=lambda x: x[1], reverse=True)[:20])
    keys=list(dictonary.keys())
    for i in keys:
      print(label[i])
    print('*'*1000)

最新更新