我应该先执行交叉验证然后再进行网格搜索吗?

Should I perform Cross Validation first and then do grid search?

我是机器学习领域的新手。我的问题如下:我已经建立了一个模型,并且正在尝试优化该模型。通过做一些研究,我发现交叉验证可以用来帮助我避免过度拟合的模型。此外,Gridsearchcv 可用于帮助我优化此类模型的参数并最终确定最佳参数。

现在我的问题是,我应该先进行交叉验证,然后使用网格搜索来确定最佳参数,还是使用 GridsearchCV 就足够了,因为它本身会执行交叉验证?

参见Cross validation with test data set

如果你的数据集足够大,我的建议是:

  1. 将您的数据集拆分为训练和测试子集。
  2. 对您的训练数据集执行 GridSearchCV
  3. 在您的测试子集上评估您的最佳模型(来自 GridSearchCV)。

Now my question is should I do cross-validation first and then use grid search to identify the best parameters or using GridsearchCV would be enough given it performs cross-validation itself?

第二个。 GridSearchCV 使用交叉验证拆分策略来 select 最佳参数。如果你阅读 scikit-learn documentation,有一个名为 "cv" 的参数,它默认定义了 5 折交叉验证。如果你需要使用另一种交叉验证策略,你可以给它一个int,交叉验证生成器或者一个iterable

根据@Noki 的建议,您可以在 Grid Search CV 中使用 cv 参数。

GridSearchCV(estimator, param_grid, scoring=None, n_jobs=None, iid='deprecated', 
refit=True, cv=None, verbose=0, 
pre_dispatch='2*n_jobs',error_score=nan,return_train_score=False)

文档也明确指出,如果是分类问题,它会自动确保它是分层的。

For integer/None inputs, if the estimator is a classifier and y is either binary or multiclass, StratifiedKFold is used. In all other cases, KFold is used.

但是,我想补充一点: 您可以根据 Y_target 变量的值计数使 K 折动态化。 您不能将 K-fold 中频率的最低计数设为 1,这会在训练时引发错误。我碰巧遇到过这个。使用下面的代码片段来帮助您。

例如

import pandas as pd
Y_target=pd.Series([0,1,1,1,1,0,0,0,6,6,6,6,6,6,6,6,6])

if Y_target.value_counts().iloc[-1]<2:
    raise Exception ("No value can have frequency count as 1 in Y-target")
else:
    Kfold=Y_target.value_counts().iloc[-1]

然后您可以在网格搜索中将 Kfold 分配给您的 cv 参数