gpt4 book ai didi

python - Eli5 treat_weights 不会使用 sklearn 随机森林分类器返回每个类的 feature_importance

转载 作者:太空宇宙 更新时间:2023-11-03 20:00:49 29 4
gpt4 key购买 nike

我正在使用 eli5 explain_weights scikit-learn 的随机森林分类器上的函数。我在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))

我已经重命名了功能和类,但这不是强制性的。同样,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

我找不到每个类(class)的详细结果,如this question所示。我正在使用 explain_weights show_weights函数,因为我想将输出存储在 DataFrame 中,但使用 show_weights 时会出现同样的问题。我使用其他分类器也遇到同样的问题,例如 SGDClassifier ,并删除 PermutationImportance 后步骤。

我的代码有什么问题吗?

谢谢大家!

最佳答案

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

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

关于python - Eli5 treat_weights 不会使用 sklearn 随机森林分类器返回每个类的 feature_importance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59245580/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com