如何在 python 中使用交叉验证执行 GridSearchCV

How to perform GridSearchCV with cross validation in python

我正在使用 GridSearchCV.

执行 RandomForest 的超参数调整,如下所示
X = np.array(df[features]) #all features
y = np.array(df['gold_standard']) #labels

x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

param_grid = { 
    'n_estimators': [200, 500],
    'max_features': ['auto', 'sqrt', 'log2'],
    'max_depth' : [4,5,6,7,8],
    'criterion' :['gini', 'entropy']
}
CV_rfc = GridSearchCV(estimator=rfc, param_grid=param_grid, cv= 5)
CV_rfc.fit(x_train, y_train)
print(CV_rfc.best_params_)

我得到的结果如下

{'criterion': 'gini', 'max_depth': 6, 'max_features': 'auto', 'n_estimators': 200}

之后,我将调整后的参数重新应用到 x_test,如下所示。

rfc=RandomForestClassifier(random_state=42, criterion ='gini', max_depth= 6, max_features = 'auto', n_estimators = 200, class_weight = 'balanced')
rfc.fit(x_train, y_train)
pred=rfc.predict(x_test)
print(precision_recall_fscore_support(y_test,pred))
print(roc_auc_score(y_test,pred))

但是,我仍然不清楚如何将 GridSearchCV10-fold cross validation 一起使用(即不只是将调整后的参数应用于 x_test)。即如下所示。

kf = StratifiedKFold(n_splits=10)
for fold, (train_index, test_index) in enumerate(kf.split(X, y), 1):
    X_train = X[train_index]
    y_train = y[train_index]
    X_test = X[test_index]
    y_test = y[test_index]

因为GridSearchCV使用了crossvalidation,我们可以使用所有的Xy并得到最好的结果作为最终结果吗?

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

在这种情况下不应执行网格搜索。

在内部,GridSearchCV 将提供给它的数据集拆分为各种 trainingvalidation 子集,并且使用超参数提供给它的网格,找到在验证子集上给出最佳分数的单组超参数

train-test split 的重点是,在这个过程完成后,对测试数据执行 one 最终评分,这是迄今为止未知的模型,以查看您的超参数是否已过拟合验证子集。如果效果不错,那么下一步就是将模型放入 production/deployment.

如果您在 交叉验证中执行网格搜索,那么您将拥有 多个 组超参数,每个超参数都执行最好在交叉验证拆分的网格搜索验证子集上。您无法将这些集合组合成一个统一的超参数规范,因此您无法部署您的模型。

sinceGridSearchCV uses crossvalidation can we use all X and y and get the best result as the final result?

不,你不应该调整你的超参数(通过 GridSearchCV 或单个 gridSearch()),因为模型会选择最适合测试数据的超参数。这种方法失去了测试数据的真正用途。该模型性能不可泛化,因为它在超参数调整期间已经看到了这些数据。

查看 this 文档以更好地理解超参数调整和交叉验证。

文档中的一些图片: