本文介绍了如何在sklearn中的每个交叉验证模型中计算特征重要性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将RandomForestClassifier()10 fold cross validation一起使用,如下所示.

I am using RandomForestClassifier() with 10 fold cross validation as follows.

clf=RandomForestClassifier(random_state = 42, class_weight="balanced")
k_fold = StratifiedKFold(n_splits=10, shuffle=True, random_state=42)
accuracy = cross_val_score(clf, X, y, cv=k_fold, scoring = 'accuracy')
print(accuracy.mean())

我想确定特征空间中的重要特征.如下所述,获得单一分类的特征重要性似乎很简单.

I want to identify the important features in my feature space. It seems to be straightforward to get the feature importance for single classification as follows.

print("Features sorted by their score:")
feature_importances = pd.DataFrame(clf.feature_importances_,
                                   index = X_train.columns,
                                    columns=['importance']).sort_values('importance', ascending=False)
print(feature_importances)

但是,我找不到如何在sklearn中为cross validation执行feature importance的操作.

However, I could not find how to perform feature importance for cross validation in sklearn.

总而言之,我想确定10倍交叉验证中最有效的功能(例如,使用average importance score).

In summary, I want to identify the most effective features (e.g., by using an average importance score) in the 10-folds of cross validation.

如果需要,我很乐意提供更多详细信息.

I am happy to provide more details if needed.

推荐答案

cross_val_score()不会针对火车测试折叠的每种组合返回估算器.

cross_val_score() does not return the estimators for each combination of train-test folds.

您需要使用 cross_validate() 并设置return_estimator =True.

这是一个可行的示例:

from sklearn import datasets
from sklearn.model_selection import cross_validate
from sklearn.svm import LinearSVC
from sklearn.ensemble import  RandomForestClassifier
import pandas as pd

diabetes = datasets.load_diabetes()
X, y = diabetes.data, diabetes.target

clf=RandomForestClassifier(n_estimators =10, random_state = 42, class_weight="balanced")
output = cross_validate(clf, X, y, cv=2, scoring = 'accuracy', return_estimator =True)
for idx,estimator in enumerate(output['estimator']):
    print("Features sorted by their score for estimator {}:".format(idx))
    feature_importances = pd.DataFrame(estimator.feature_importances_,
                                       index = diabetes.feature_names,
                                        columns=['importance']).sort_values('importance', ascending=False)
    print(feature_importances)

输出:

Features sorted by their score for estimator 0:
     importance
s6     0.137735
age    0.130152
s5     0.114561
s2     0.113683
s3     0.112952
bmi    0.111057
bp     0.108682
s1     0.090763
s4     0.056805
sex    0.023609
Features sorted by their score for estimator 1:
     importance
age    0.129671
bmi    0.125706
s2     0.125304
s1     0.113903
bp     0.111979
s6     0.110505
s5     0.106099
s3     0.098392
s4     0.054542
sex    0.023900

这篇关于如何在sklearn中的每个交叉验证模型中计算特征重要性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 07:24