【问题标题】:How to get the selected features in GridSearchCV in sklearn in python如何在 python 中的 sklearn 中获取 GridSearchCV 中的选定功能
【发布时间】:2019-09-03 04:03:16
【问题描述】:

我使用recurive feature elimination with cross validation (rfecv) 作为GridSearchCV 的特征选择技术。

我的代码如下。

X = df[my_features_all]
y = df['gold_standard']

x_train, x_test, y_train, y_test = train_test_split(X, y, random_state=0)

k_fold = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)

clf = RandomForestClassifier(random_state = 42, class_weight="balanced")

rfecv = RFECV(estimator=clf, step=1, cv=k_fold, scoring='roc_auc')

param_grid = {'estimator__n_estimators': [200, 500],
    'estimator__max_features': ['auto', 'sqrt', 'log2'],
    'estimator__max_depth' : [3,4,5]
    }

CV_rfc = GridSearchCV(estimator=rfecv, param_grid=param_grid, cv= k_fold, scoring = 'roc_auc', verbose=10, n_jobs = 5)
CV_rfc.fit(x_train, y_train)
print("Finished feature selection and parameter tuning")

现在,我想从上面的代码中获取optimal number of featuresselected features

为此,我运行了以下代码。

#feature selection results
print("Optimal number of features : %d" % rfecv.n_features_)
features=list(X.columns[rfecv.support_])
print(features)

但是,我收到以下错误: AttributeError: 'RFECV' object has no attribute 'n_features_'

还有其他方法可以获取这些详细信息吗?

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

【问题讨论】:

    标签: python machine-learning scikit-learn data-mining gridsearchcv


    【解决方案1】:

    您传递给GridSearchCV 的对象rfecv 不适合它。它首先被克隆,然后将这些克隆拟合到数据中,并针对所有不同的超参数组合进行评估。

    因此,要访问最佳功能,您需要访问GridSearchCVbest_estimator_ 属性:-

    CV_rfc.fit(x_train, y_train)
    print("Finished feature selection and parameter tuning")
    
    print("Optimal number of features : %d" % rfecv.n_features_)
    features=list(X.columns[CV_rfc.best_estimator_.support_])
    print(features)
    

    【讨论】:

    • 非常感谢。有效:) 只是一个简单的问题。我上面使用的过程是否正确?即首先我执行rfecv,然后执行gridsearchcv。期待您的回音。非常感谢:)
    • 如果你知道这个stackoverflow.com/questions/55671530/…的答案,请告诉我非常感谢你:)
    猜你喜欢
    • 2021-02-26
    • 2019-08-31
    • 2019-06-11
    • 2019-09-07
    • 2018-01-05
    • 2015-06-28
    • 1970-01-01
    • 2021-11-12
    相关资源
    最近更新 更多