0

我已经阅读了一些关于将缩放与交叉折叠验证和超参数调整集成而不会冒数据泄漏风险的文章。我发现的最合理的解决方案(据我所知)涉及创建一个包含标量和 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. 使用我们的缩放器转换 X_train 和 X_test
  3. 使用 X_train 和我们从网格搜索过程中新发现的最佳参数训练一个新模型
  4. 使用我们的第一个保持测试集测试新模型。

据推测,因为 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)
4

1 回答 1

1

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)
于 2021-05-27T06:18:25.107 回答