【发布时间】:2020-04-02 08:41:06
【问题描述】:
我在 scikit-learn 的随机森林分类器上使用 eli5 explain_weights 函数。我在 eli5 documentation(第 30-31 页)中看到,此函数能够返回特征重要性(平均权重 + 标准差)每个类进行预测。但是,在我的数据集上使用它时,该函数只返回整个模型的特征重要性(不是每个类)。
这里是使用scikit-learn make_classification 函数生成的可重现示例:
import pandas as pd
import eli5
from eli5.sklearn import PermutationImportance
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
x, y = datasets.make_classification(n_samples=200, n_features=5, n_informative=3, n_redundant=2, n_classes=4)
df = pd.concat([pd.DataFrame(x, columns=['feat_1', 'feat_2', 'feat_3', 'feat_4', 'feat_5']), pd.DataFrame(y, columns=['classe'])], axis=1)
df = df.replace({'classe': {0: '1st', 1: '2nd', 2: '3rd', 3: '4th'}})
labels = pd.unique(df['classe'])
train, test = train_test_split(df, stratify=df['classe'], test_size=0.40)
rf = RandomForestClassifier()
rf.fit(train[['feat_1', 'feat_2', 'feat_3', 'feat_4', 'feat_5']], train['classe'])
perm = PermutationImportance(rf).fit(test[['feat_1', 'feat_2', 'feat_3', 'feat_4', 'feat_5']], test['classe'])
var_imp_classes = eli5.explain_weights(perm, top=5, targets=labels, target_names=labels, feature_names=['feat_1', 'feat_2', 'feat_3', 'feat_4', 'feat_5'])
print(eli5.format_as_text(var_imp_classes))
我已经重命名了特性和类,但这不是强制性的。同样,可以通过将eli5.explain_weights 中的perm 参数替换为rf 来避免PermutationImportance 步骤。
此代码返回以下内容:
Explained as: feature importances
Feature importances, computed as a decrease in score when feature
values are permuted (i.e. become noise). This is also known as
permutation importance.
If feature importances are computed on the same data as used for training,
they don't reflect importance of features for generalization. Use a held-out
dataset if you want generalization feature importances.
0.3475 ± 0.1111 feat_1
0.1900 ± 0.1134 feat_4
0.0700 ± 0.0200 feat_3
0.0550 ± 0.0624 feat_2
0.0300 ± 0.0300 feat_5
我找不到每个类的详细结果,如this question所示。我正在使用explain_weightsshow_weights 函数,因为我想将输出存储在DataFrame 中,但是在使用show_weights 时会出现同样的问题。我在使用其他分类器(例如SGDClassifier)以及删除PermutationImportance 步骤后遇到了同样的问题。
我的代码有什么问题?
谢谢大家!
【问题讨论】:
标签: python random scikit-learn classification random-forest