我正在使用 sk learn 进行预处理,并想使用 ColumnTransformer 将几个步骤添加在一起。
这是我的代码:
## numerical features
numerical_transformer = make_pipeline(
KNNImputer(n_neighbors=3),
StandardScaler()
)
## Categorical features
from sklearn.impute import SimpleImputer
categorical_transformer = make_pipeline(
SimpleImputer(strategy='most_frequent'),
OneHotEncoder(handle_unknown='ignore')
)
## Combine both steps
from sklearn.compose import ColumnTransformer
preprocessor = ColumnTransformer(
transformers=[
('numerical', numerical_transformer, numerical_cols),
('categorical', categorical_transformer, categorical_cols)
])
为了使其适合训练数据,即学习模式等,并实际执行上述所有步骤,即填充缺失值等,我使用:
# Fit the training (!) data to the pipeline
preprocessor.fit_transform(train_df2)
现在,我想在预处理后进行一些特征工程和选择,因此 preprocessor.fit_transform
步骤将返回一个数据框而不是 np 数组会很方便。
我的问题是,这是一种合法的方式吗?因为我见过的大多数管道也在其末尾直接添加模型并将数据拟合到模型中。 (在那种情况下,如果它“返回”一个数据框是完全没问题的,因为我真的看不到它,它会直接放入模型中。)
我已经尝试过:
# Fit the training (!) data to the pipeline
pd.DataFrame(preprocessor.fit_transform(train_df2))
但这需要很长时间。 我只是想知道我是否做错了什么,或者是否有不同的方法来完成这项任务。