嵌套交叉验证:cross_validate 如何处理 GridSearchCV 作为其输入估计器?

Nested cross-validation: How does cross_validate handle GridSearchCV as its input estimator?

以下代码结合了 cross_validateGridSearchCV 以在 iris 数据集上对 SVC 执行嵌套交叉验证。

(以下文档页面的修改示例: https://scikit-learn.org/stable/auto_examples/model_selection/plot_nested_cross_validation_iris.html#sphx-glr-auto-examples-model-selection-plot-nested-cross-validation-iris-py.)


from sklearn.datasets import load_iris
from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV, cross_validate, KFold
import numpy as np
np.set_printoptions(precision=2)

# Load the dataset
iris = load_iris()
X_iris = iris.data
y_iris = iris.target

# Set up possible values of parameters to optimize over
p_grid = {"C": [1, 10],
          "gamma": [.01, .1]}

# We will use a Support Vector Classifier with "rbf" kernel
svm = SVC(kernel="rbf")

# Choose techniques for the inner and outer loop of nested cross-validation
inner_cv = KFold(n_splits=5, shuffle=True, random_state=1)
outer_cv = KFold(n_splits=4, shuffle=True, random_state=1)

# Perform nested cross-validation
clf = GridSearchCV(estimator=svm, param_grid=p_grid, cv=inner_cv, iid=False)
clf.fit(X_iris, y_iris)
best_estimator = clf.best_estimator_

cv_dic = cross_validate(clf, X_iris, y_iris, cv=outer_cv, scoring=['accuracy'], return_estimator=False, return_train_score=True)
mean_val_score = cv_dic['test_accuracy'].mean()

print('nested_train_scores: ', cv_dic['train_accuracy'])
print('nested_val_scores:   ', cv_dic['test_accuracy'])
print('mean score:            {0:.2f}'.format(mean_val_score))

cross_validate 将每个折叠中的数据集拆分为 训练 和测试集。在每个折叠中,然后根据与折叠关联的训练集训练输入估计器。这里输入的估计量是clf,参数化的GridSearchCV估计量,即再次交叉验证自身的估计量。

我对整个事情有三个问题:

  1. 如果 clf 被用作 cross_validate 的估计器,它是否(在 GridSearchCV 交叉验证过程中)拆分上述 训练集 进入子训练集和验证集以确定最佳超参数组合?
  2. 在通过 GridSearchCV 测试的所有模型中,cross_validate 是否仅验证存储在 best_estimator_ 属性中的模型?
  3. cross_validate 是否训练模型(如果是,为什么?)或者存储在 best_estimator_ 中的模型是否直接通过测试集验证?

为了更清楚地说明问题的含义,下面是我目前想象的双交叉验证的图示。

If clf is used as the estimator for cross_validate, does it split the above mentioned training set into a subtraining set and a validation set in order to determine the best hyper parameter combination?

是的,如您所见here at Line 230 the training set is again split into a subtraining and validation set (Specifically at line 240)。

更新 是的,当您将 GridSearchCV 分类器传递给 cross-validate 时,它会再次将训练集拆分为测试集和训练集。这里 a link 更详细地描述了这一点。您的图表和假设是正确的。

Out of all models tested via GridSearchCV, does cross_validate train & validate only the model stored in the variable best_estimator?

是的,正如您从答案 and here 中看到的那样,GridSearchCV return 是您案例中的 best_estimator(因为 refit 参数是 True 默认情况下。)但是,这个最佳估计器必须再次训练

Does cross_validate train a model at all (if so, why?) or is the model stored in best_estimator_ validated directly via the test set?

根据您的第三个也是最后一个问题,是的,如果 return_estimator 设置为 True,它会训练一个估计器并 return 估计它。参见 this line。这是有道理的,因为如果不首先训练估算器,还应该如何 return 分数?

更新 再次训练模型的原因是因为交叉验证的默认用例不假设您给出具有最佳参数的最佳分类器。具体来说,在这种情况下,您从 GridSearchCV 发送一个分类器,但如果您发送任何未经训练的分类器,它应该是经过训练的。我在这里要说的是,是的,在您的情况下,它不应该再次训练它,因为您已经在使用 GridSearchCV 并使用最佳估算器进行交叉验证。但是,cross-validate 无法知道这一点,因此,它假定您发送的是未优化或未经训练的估计器,因此它必须再次训练它并且 return 的分数一样。