繁体   English   中英

Eli5 Explain_weights 不使用 sklearn 随机森林分类器为每个类返回 feature_importance

[英]Eli5 explain_weights does not returns feature_importance for each class with sklearn Random Forest classifier

我现在用的是eli5 explain_weights从一个随机森林分类功能scikit学习。 我在 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))

我重命名了特性和类,但这不是强制性的。 同样,可以通过将eli5.explain_weightsperm参数eli5.explain_weightsrf来避免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

我找不到每个班级的详细结果,如这个问题所示。 我现在用的是explain_weightsshow_weights充当我想存储在数据帧输出,但使用时同样的问题出现show_weights 我在使用其他分类器(例如SGDClassifier )和删除PermutationImportance步骤后SGDClassifier了同样的问题。

我的代码有什么问题?

谢谢你们!

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM