zwi*_*uta 5 python nested python-3.x scikit-learn cross-validation
以下代码cross_validate
与结合以GridSearchCV
对 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))
Run Code Online (Sandbox Code Playgroud)
cross_validate
将每个折叠中的数据集拆分为训练集和测试集。在每个折叠中,然后基于与折叠关联的训练集训练输入估计器。这里输入的估计器是clf
一个参数化的GridSearchCV
估计器,即一个再次交叉验证自己的估计器。
我对整件事有三个问题:
clf
用作 的估计器cross_validate
,它(在GridSearchCV
交叉验证过程中)是否将上述训练集拆分为子训练集和验证集以确定最佳超参数组合?GridSearchCV
,是否cross_validate
仅验证存储在best_estimator_
属性中的模型?cross_validate
训练模型(如果是,为什么?)还是best_estimator_
直接通过测试集验证存储的模型?为了更清楚地说明问题的含义,以下是我目前如何想象双重交叉验证的说明。
如果
clf
用作 的估计器cross_validate
,它是否将上述训练集拆分为子训练集和验证集以确定最佳超参数组合?
是的,正如您在第 230 行看到的,训练集再次分为子训练和验证集(特别是在第 240 行)。
更新是的,当您将GridSearchCV
分类器传递给cross-validate
它时,它将再次将训练集拆分为测试集和训练集。这是一个更详细描述这一点的链接。你的图表和假设是正确的。
在通过 GridSearchCV 测试的所有模型中,cross_validate 是否仅训练和验证存储在变量 best_estimator 中的模型?
是的,正如您从此处和此处的答案中看到的,GridSearchCV 在您的情况下返回 best_estimator(因为在您的情况下refit
参数是True
默认值。)但是,必须再次训练这个最佳估计器
cross_validate 是否完全训练模型(如果是,为什么?)还是存储在 best_estimator_ 中的模型直接通过测试集验证?
根据您的第三个也是最后一个问题,是的,它训练一个估计器并return_estimator
在设置为 时返回它True
。看到这一行。这是有道理的,因为它应该如何在不训练估计器的情况下返回分数?
更新
模型再次训练的原因是因为交叉验证的默认用例不假设您提供具有最佳参数的最佳分类器。具体来说,在这种情况下,您将发送来自 的分类器,GridSearchCV
但如果您发送任何未经训练的分类器,则应该对其进行训练。我的意思是,是的,在您的情况下,它不应该再次训练它,因为您已经在使用GridSearchCV
和使用最佳估计器进行交叉验证。但是,没有办法cross-validate
知道这一点,因此,它假设您发送的是未优化或未经训练的估计器,因此它必须再次训练它并返回相同的分数。
归档时间: |
|
查看次数: |
781 次 |
最近记录: |