GridSearchCV、数据泄露和生产过程清晰度

GridSearchCV, Data Leaks & Production Process Clarity

我读过一些关于将缩放与交叉验证和超参数调整相结合而不冒数据泄漏风险的文章。我发现的最明智的解决方案(据我所知)涉及创建一个包含标量和 GridSeachCV 的管道,以便在您想要网格搜索和交叉折叠验证时使用。我还读到,即使在使用交叉验证时,在一开始创建一个保留测试集以在超参数调整后对模型进行额外的最终评估也是有用的。将它们放在一起看起来像这样:

# train, test, split, unscaled data to create a final test set
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)

# instantiate pipeline with scaler and model, so that each training set
# in each fold is fit to the scalar and each training/test set in each fold 
# is respectively transformed by fit scalar, preventing data leaks between each test/train

pipe = Pipeline([('sc', StandardScaler()),  
                 ('knn', KNeighborsClassifier())
                 ])

# define hypterparameters to search
params = {'knn_n_neighbors': [3, 5, 7, 11]}

# create grid
search = GridSearchCV(estimator=pipe, 
                      param_grid=params, 
                      cv=5, 
                      return_train_Score=True)
    
search.fit(X_train, y_train)

假设我的理解和上述过程是正确的,我的问题是下一步是什么?

我猜我们:

  1. 适合 X_train 我们的洁牙器
  2. 用我们的缩放器
  3. 转换X_train和X_test
  4. 使用 X_train 和我们从网格搜索过程中新发现的最佳参数训练新模型
  5. 使用我们的第一个 holdout 测试集测试新模型。

据推测,由于 Gridsearch 评估了基于各种数据切片的缩放模型,因此缩放我们的最终、整个训练和测试数据的值差异应该没问题。

最后,当需要通过我们的生产模型处理全新的数据点时,这些数据点是否需要根据我们原始 X_train 的标量拟合进行转换?

感谢您的帮助。我希望我没有完全误解这个过程的基本方面。

奖金问题: 我从许多来源看到了上面的示例代码。管道如何知道将标量拟合到交叉折叠的训练数据,然后转换训练和测试数据?通常我们必须定义那个过程:

# define the scaler
scaler = MinMaxScaler()

# fit on the training dataset
scaler.fit(X_train)

# scale the training dataset
X_train = scaler.transform(X_train)

# scale the test dataset
X_test = scaler.transform(X_test)

GridSearchCV 将帮助您根据您的管道和数据集找到最佳超参数集。为了做到这一点,它将使用交叉验证(在你的情况下将你的火车数据集分成 5 个相等的子集)。这意味着您的 best_estimator 将在 80% 的训练集上接受训练。

如您所知,模型看到的数据越多,其结果就越好。因此,一旦您拥有最佳超参数,明智的做法是在所有训练集上重新训练最佳估计器并使用测试集评估其性能。

您可以通过指定 Gridsearch 的参数 refit=True 使用整个训练集重新训练最佳估计器,然后按如下方式在 best_estimator 上对您的模型进行评分:

search = GridSearchCV(estimator=pipe, 
                      param_grid=params, 
                      cv=5,
                      return_train_Score=True,
                      refit=True)
    
search.fit(X_train, y_train)
tuned_pipe = search.best_estimator_
tuned_pipe.score(X_test, y_test)