我对交叉验证普遍存在疑问。
在模块2的笔记本中,提到应该使用管道进行交叉验证,以防止数据泄漏。我了解为什么,但是对管道功能有疑问:
如果我想在管道中使用三个函数:MinMaxScaler()
,PolynomialFeatures
(用于多个度数)和最后一个Ridge
(用于多个alpha值)。由于我想在使用多个参数值后找到最佳模型,因此我将使用GridSearchCV()
函数,该函数会进行交叉验证并给出最佳模型得分。
但是,在使用三个函数初始化管道对象并将其插入到GridSearchCV()
函数中之后,如何在{{1}的params
参数中插入多个度数和aplha值}功能。我应该按在管道对象中定义函数的顺序将参数作为两个列表的列表插入,还是发送两个列表的字典,其中键是管道中函数的对象名称? ???
答案 0 :(得分:0)
您只需要将其作为词典来提供即可。
尝试以下示例:
from sklearn.preprocessing import MinMaxScaler, PolynomialFeatures
from sklearn.linear_model import Ridge
from sklearn.pipeline import make_pipeline
from sklearn.datasets import make_regression
from sklearn.model_selection import GridSearchCV
X, y = make_regression(random_state=42)
pipe = make_pipeline(MinMaxScaler(), PolynomialFeatures(), Ridge())
pipe
# Pipeline(steps=[('minmaxscaler', MinMaxScaler()),
# ('polynomialfeatures', PolynomialFeatures()),
# ('ridge', Ridge())])
gs = GridSearchCV(pipe, param_grid={'polynomialfeatures__degree': [2,4],
'ridge__alpha': [1,10]}).fit(X, y)
# gs.best_params_
# {'polynomialfeatures__degree': 2, 'ridge__alpha': 1}