sklearn:应用相同的缩放来训练和预测管道

Posted

技术标签:

【中文标题】sklearn:应用相同的缩放来训练和预测管道【英文标题】:sklearn: apply same scaling to train and predict in a pipeline 【发布时间】:2018-05-03 18:43:37 【问题描述】:

我正在编写一个函数,通过 k 折交叉验证选择最佳模型。在函数内部,我有一个管道

    缩放数据 寻找决策树回归器的最佳参数

那我想用模型来预测一些目标值。为此,我必须应用在网格搜索期间应用的相同缩放。

管道是否使用与训练数据相同的拟合来转换我想要预测目标的数据,即使我没有指定它?我一直在查看documentation 和here 似乎可以做到这一点,但我完全不确定,因为这是我第一次使用管道。

def build_model(data, target, param_grid):
    # compute feature range
    features = df.keys()
    feature_range = dict()
    maxs = df.max(axis=0)
    mins = df.min(axis=0)
    for feature in features:
        if feature is not 'metric':
            feature_range[feature] = 'max': maxs[feature], 'min': mins[feature]

    # initialise the k-fold cross validator
    no_split = 10
    kf = KFold(n_splits=no_split, shuffle=True, random_state=42)
    # create the pipeline
    pipe = make_pipeline(MinMaxScaler(), 
                         GridSearchCV(
                             estimator=DecisionTreeRegressor(), 
                             param_grid=param_grid, 
                             n_jobs=-1, 
                             cv=kf, 
                             refit=True))
    pipe.fit(data, target)

    return pipe, feature_range

max_depth = np.arange(1,10)
min_samples_split = np.arange(2,10)
min_samples_leaf = np.arange(2,10) 
param_grid = 'max_depth': max_depth, 
              'min_samples_split': min_samples_split, 
              'min_samples_leaf': min_samples_leaf
pipe, feature_range = build_model(data=data, target=target, param_grid=param_grid)

# could that be correct?
pipe.fit(test_data)

编辑:我在 [preprocessing] 的文档中发现每个预处理工具都有一个 API,

在训练集上计算[变换],以便能够在测试集上重新应用相同的变换

如果是这种情况,它可能会在内部保存转换,因此答案可能是肯定的。

【问题讨论】:

【参考方案1】:

sklearn 管道将调用fit_transformfit,然后调用transform,如果除了最后一步之外的所有步骤都不存在fit_transform 方法。因此,在您的管道中,缩放步骤将导致数据在 GridSearchCV 之前进行转换。

文档here。

【讨论】:

我明白了,但是你能确认训练数据上的学习转换将应用于测试数据吗?如果是这样,问题就解决了:) 是的!它会在您调用管道的预测函数时应用。

以上是关于sklearn:应用相同的缩放来训练和预测管道的主要内容,如果未能解决你的问题,请参考以下文章

sklearn.pipeline.Pileline

如何缩放训练模型的输入数据?

使用列操作步骤创建 sklearn 管道

如何将不同的输入拟合到 sklearn 管道中?

如何腌制sklearn管道中的各个步骤?

在 Sklearn 管道和交叉验证中使用缩放器