gpt4 book ai didi

python - 如何在python中的sklearn中获取GridSearchCV中的选定特征

转载 作者:太空宇宙 更新时间:2023-11-03 11:13:46 25 4
gpt4 key购买 nike

我正在使用通过交叉验证 (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")

现在,我想从上面的代码中获取最优数量的特征选择的特征

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

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

但是,我收到以下错误:AttributeError:“RFECV”对象没有属性“n_features_”

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

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

最佳答案

您传递给 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)

关于python - 如何在python中的sklearn中获取GridSearchCV中的选定特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55650782/

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