首页 > 解决方案 > Eli5 explain_weights 不会为每个使用 sklearn 随机森林分类器的类返回 feature_importance

问题描述

我在eli5 explain_weightsscikit-learn 的随机森林分类器上使用该函数。我在 eli5文档(第 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))

我已经重命名了特性和类,但这不是强制性的。同样,PermutationImportance可以通过将perm参数eli5.explain_weights替换为来避免该步骤rf

此代码返回以下内容:

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_weights函数show_weights,因为我想将输出存储在 DataFrame 中,但是在使用show_weights. 我在使用其他分类器时遇到了同样的问题,例如SGDClassifier, 并且在删除PermutationImportance步骤之后。

我的代码有什么问题?

谢谢你们!

标签: pythonrandomscikit-learnclassificationrandom-forest

解决方案


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

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


推荐阅读