Scikit learn GridSearchCV、数据泄漏和;生产过程清晰度
我读过一些关于在不冒数据泄漏风险的情况下将缩放与交叉折叠验证和超参数调优集成在一起的文章。据我所知,我发现的最有意义的解决方案是创建一个包含标量和GridSeachCV的管道,用于网格搜索和交叉折叠验证。我还读到,即使在使用交叉折叠验证时,在一开始创建一个保持测试集,以便在超参数调整后对模型进行额外的最终评估,也是很有用的。把这些放在一起看起来像这样:Scikit learn GridSearchCV、数据泄漏和;生产过程清晰度,scikit-learn,memory-leaks,pipeline,gridsearchcv,data-preprocessing,Scikit Learn,Memory Leaks,Pipeline,Gridsearchcv,Data Preprocessing,我读过一些关于在不冒数据泄漏风险的情况下将缩放与交叉折叠验证和超参数调优集成在一起的文章。据我所知,我发现的最有意义的解决方案是创建一个包含标量和GridSeachCV的管道,用于网格搜索和交叉折叠验证。我还读到,即使在使用交叉折叠验证时,在一开始创建一个保持测试集,以便在超参数调整后对模型进行额外的最终评估,也是很有用的。把这些放在一起看起来像这样: # train, test, split, unscaled data to create a final test set X_train,
# 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)
假设我的理解和上述过程是正确的,我的问题是下一步是什么
我猜我们:
# 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个相等的子集)。这意味着您的最佳估计值将在80%的列车组上进行训练
正如您所知,模型看到的数据越多,其结果就越好。因此,一旦获得最佳超参数,明智的做法是在所有训练集上重新训练最佳估计器,并使用测试集评估其性能
通过指定Gridsearch的参数refit=True
,您可以使用整个序列集重新训练最佳估计器,然后在最佳估计器上对您的模型进行评分,如下所示:
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)
非常感谢。我的理解是,使用refit将使用管道指定的缩放器缩放整个X_系列,并使用最佳参数在整个X_系列上拟合最终模型,从而完成GridSearchCV。因此,当我想使用此模型预测新数据上的新标签时,我是否首先使用scaler I fit to X_train缩放新数据(在本例中,scaler.fit(X_train)使用MinMaxScaler())?管道中的StandardScaler
将进行拟合,因此您不必缩放要预测的集,这将在管道中完成。predict()
哦!比如说。。如果我有一个新的、未标记的数据集,我想为其预测名为X_predict的标签,那么我可以将其传递给调优的_pipe.predict()?tuned_pipe.predict(X_predict)查看文档和您所说的内容,search.best_estimator_uu是改装模型本身,因此这也是我可以保存并在其他地方重新加载的内容。我理解得对吗?你明白了:)一旦你的模型安装好,你可以使用pickle
对它进行序列化,然后在新数据集的其他地方使用它。