首页 > 解决方案 > 在 Pipeline 中的特定列上使用 StandardScaler 并连接到原始数据

问题描述

我有一个包含 4 个数字列的数据框,我试图StandardScalerPipeline. 我使用下面的代码来缩放和转换我的列。

num_feat = ['Quantity']
num_trans = Pipeline([('scale', StandardScaler())])

preprocessor = ColumnTransformer(transformers = ['num', num_trans, num_feat])

pipe = Pipeline([('preproc', preprocessor),
                ('rf', RandomForestRegressor(random_state = 0))
                ])

完成此操作后,我将拆分数据并训练我的模型,如下所示。

y = df1['target']
x = df1.drop(['target','ID'], axis = 1)
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2)
pipe.fit(x_train, y_train)

这给了我错误 ValueError: not enough values to unpack (expected 3, got 1)。我知道这可能是因为我的数据框中的其他 3 个数字列。那么如何将缩放数据连接到剩余的数据帧并在整个数据上训练我的模型。或者有没有更好的方法来做到这一点。

标签: pythonscikit-learnpipeline

解决方案


请在初始化变压器时添加一个括号。

preprocessor = ColumnTransformer(transformers = [('num', num_trans, num_feat)],remainder='passthrough')

推荐阅读