首页 > 解决方案 > 使用 scikit learn 在 python 中进行管道和交叉验证

问题描述

我对交叉验证有一个普遍的怀疑。

在模块 2 的笔记本中提到应该使用管道进行交叉验证,以防止数据泄漏。我理解为什么,但是对管道功能有疑问:

如果我想在管道中使用三个函数:MinMaxScaler(), PolynomialFeatures(用于多个度数)和 ARidge最后(用于多个 alpha 值)。由于我想在使用多个参数值后找到最佳模型,因此我将使用进行GridSearchCV()交叉验证并给出最佳模型分数的函数。

但是,在我用三个函数初始化管道对象并将其插入GridSearchCV()函数后,如何在函数的params参数中插入多个度数和 aplha 值GridSearchCV()。我是按照在管道对象中定义函数的顺序将参数作为两个列表的列表插入,还是发送两个列表的字典,其中键是管道中函数的对象名称? ???

标签: pythonscikit-learnpipelinecross-validationpolynomials

解决方案


您只需将其作为字典提供即可。

试试这个例子:

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}

推荐阅读