我使用带有交叉验证的递归特征消除(rfecv)
作为随机森林分类器
的特征选择器,代码如下所示。
X = df[[my_features]] #所有我的特征y = df['gold_standard'] #标签clf = RandomForestClassifier(random_state = 42, class_weight="balanced")rfecv = RFECV(estimator=clf, step=1, cv=StratifiedKFold(10), scoring='roc_auc')rfecv.fit(X,y)print("最佳特征数量 : %d" % rfecv.n_features_)features=list(X.columns[rfecv.support_])
我还使用GridSearchCV
来调整RandomForestClassifier
的超参数,代码如下所示。
X = df[[my_features]] #所有我的特征y = df['gold_standard'] #标签x_train, x_test, y_train, y_test = train_test_split(X, y, random_state=0)rfc = RandomForestClassifier(random_state=42, class_weight = 'balanced')param_grid = { 'n_estimators': [200, 500], 'max_features': ['auto', 'sqrt', 'log2'], 'max_depth' : [4,5,6,7,8], 'criterion' :['gini', 'entropy']}k_fold = StratifiedKFold(n_splits=10, shuffle=True, random_state=0)CV_rfc = GridSearchCV(estimator=rfc, param_grid=param_grid, cv= k_fold, scoring = 'roc_auc')CV_rfc.fit(x_train, y_train)print(CV_rfc.best_params_)print(CV_rfc.best_score_)print(CV_rfc.best_estimator_)pred = CV_rfc.predict_proba(x_test)[:,1]print(roc_auc_score(y_test, pred))
然而,我不清楚如何将特征选择(rfecv
)与GridSearchCV
结合起来使用。
编辑:
当我运行由@Gambit建议的答案时,我得到了以下错误:
ValueError: 无效的参数 criterion 用于估计器 RFECV(cv=StratifiedKFold(n_splits=10, random_state=None, shuffle=False), estimator=RandomForestClassifier(bootstrap=True, class_weight='balanced', criterion='gini', max_depth=None, max_features='auto', max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators='warn', n_jobs=None, oob_score=False, random_state=42, verbose=0, warm_start=False), min_features_to_select=1, n_jobs=None, scoring='roc_auc', step=1, verbose=0). 使用 `estimator.get_params().keys()` 检查可用参数列表。
我通过在param_grid
参数列表中使用estimator__
解决了上述问题。
我的问题现在是 如何使用选定的特征和参数在x_test
上验证模型是否能很好地处理未见数据。我如何获得最佳特征
并使用最优超参数
进行训练?
如果需要,我很乐意提供更多细节。
回答:
基本上,你想在使用递归特征消除(带有交叉验证)进行特征选择后,通过交叉验证来微调分类器的超参数。
Pipeline对象正是为此目的设计的,用于组合数据转换和应用估计器。
你可以使用不同的模型(如GradientBoostingClassifier
等)进行最终分类。以下方法可以实现这一目标:
from sklearn.datasets import load_breast_cancerfrom sklearn.feature_selection import RFECVfrom sklearn.model_selection import GridSearchCVfrom sklearn.model_selection import train_test_splitfrom sklearn.ensemble import RandomForestClassifierX, y = load_breast_cancer(return_X_y=True)X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)from sklearn.pipeline import Pipeline#这是用于特征选择的分类器clf_featr_sele = RandomForestClassifier(n_estimators=30, random_state=42, class_weight="balanced") rfecv = RFECV(estimator=clf_featr_sele, step=1, cv=5, scoring = 'roc_auc')#你可以为最终分类使用不同的分类器clf = RandomForestClassifier(n_estimators=10, random_state=42, class_weight="balanced") CV_rfc = GridSearchCV(clf, param_grid={'max_depth':[2,3]}, cv= 5, scoring = 'roc_auc')pipeline = Pipeline([('feature_sele',rfecv), ('clf_cv',CV_rfc)])pipeline.fit(X_train, y_train)pipeline.predict(X_test)
现在,你可以将这个pipeline(包括特征选择)应用于测试数据。