首页 文章

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

提问于
浏览
1

我正在编写一个函数,其中选择最佳模型而不是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)

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

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

如果是这种情况,它可以在内部保存转换,因此答案可能是积极的 .

1 回答

  • 1

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

    这里的文档:http://scikit-learn.org/stable/modules/pipeline.html#notes

相关问题