【问题标题】:Eli5 explain_weights does not returns feature_importance for each class with sklearn Random Forest classifierEli5 explain_weights 不会为每个使用 sklearn 随机森林分类器的类返回 feature_importance
【发布时间】: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


    【解决方案1】:

    我认为您的代码没有任何问题
    在您给出的示例中,ELI5 对每个类进行了解释,因为它用于 Logistic 回归模型,该模型对每个类都有单独的回归系数。
    这在随机森林中不会发生 - 特别是如果您使用排列重要性。这些只是在使用给定的置换变量进行预测时模型准确性的降低,因此每个模型只有一个,而不是每个类一个。可以考虑每个类的分类准确度下降——这些可能会给出一个总体思路,但我不确定它们是否一致。

    如果您确实需要知道每个类别中哪些变量最独特,您可以运行 K(假设您有 K 个类别)单独的一对一二元分类 RF,并使用这些排列重要性作为您的指标。

    【讨论】:

      猜你喜欢
      • 2021-08-13
      • 2019-11-16
      • 2018-10-23
      • 2018-02-18
      • 2019-09-05
      • 1970-01-01
      • 2018-05-20
      • 2022-01-25
      • 2023-03-09
      相关资源
      最近更新 更多