【发布时间】:2021-12-28 01:25:08
【问题描述】:
我使用 20% 的数据集作为我的测试集,并使用 GridSearchCV 实现 K 折交叉验证来调整超参数。
通过使用管道,我们可以将列转换器和机器学习算法一起放入 GridSearchCV。如果我为 GridSearchCV 设置 5 折交叉验证,该函数将使用 5 个不同的训练和验证集来训练和验证超参数的每个组合。据我所知,GridSearchCV 使用 5 折分数的平均值来选择最佳模型。
那么我的问题是,它如何转换测试集?
我对此很困惑,因为为了避免数据泄漏,我们应该只使用训练集来拟合转换器,但是在这种情况下,我们有 5 个不同的训练集,我不知道 GridSearchCV 函数是哪一个用于拟合和转换验证和测试集。
我的代码如下
X_other, X_test, y_other, y_test = train_test_split(X, y, test_size = 0.2, random_state = i)
kf = KFold(n_splits = 4, shuffle = True, random_state = i)
pipe = Pipeline(steps = [("preprocessor", preprocessor),("model", ML_algo)])
grid = GridSearchCV(estimator = pipe, param_grid=param_grid,
scoring = make_scorer(mean_squared_error, greater_is_better=False,
squared=False),cv=kf, return_train_score = True, n_jobs=-1, verbose=False)
grid.fit(X_other, y_other)
test_score = mean_squared_error(y_test, grid.predict(X_test), squared=False)
【问题讨论】:
标签: python machine-learning scikit-learn cross-validation