首页 > 解决方案 > 在 sklearn Pipeline 中为每一列使用特定的 IterativeImputer

问题描述

我正在运行回归算法并使用 sklearn Pipelines 进行预处理。最初,我对所有数值列都使用了 Iterative Imputer,但我更愿意为某些列添加一些额外的步骤,因此对每个列或至少某些列使用不同的预处理步骤。在某些列中,零值是有效的,在其他列中,缺失值是如何标记的。

from sklearn.impute import IterativeImputer
from sklearn.impute import KNNImputer
from sklearn.ensemble import ExtraTreesRegressor, RandomForestRegressor
import sklearn.preprocessing
from sklearn.impute import SimpleImputer

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(df_ml.iloc[:, :].drop(columns=['ClosePrice']), 
                                                    df_ml.iloc[:, :]['ClosePrice'], 
                                                    test_size=.33
                                                    )


tic = time.perf_counter()

cat_pipe = Pipeline([
    ('imputer', SimpleImputer(strategy='most_frequent'))
                     
                    ])

# Define numerical pipeline
# IterativeImputer(estimator=ExtraTreesRegressor())
num_pipe = Pipeline([
    ('imputer', IterativeImputer(estimator=ExtraTreesRegressor(), missing_values=-1))

preprocessor = ColumnTransformer(transformers=[('cat', cat_pipe, categorical),
                                               ('num', num_pipe, numerical)

pipe = Pipeline(steps=[('preprocessor', preprocessor)])

#pipe.fit(X_train, y_train)

X_train_pre = pipe.fit_transform(X_train)
X_test_pre = pipe.fit_transform(X_test)
print(X_train_pre.shape, X_test_pre.shape)

此处的数字表示单个列,其中 -1 是缺失值指示符。当我运行这段代码时,所有缺失的值都会变成相同的值 - 6.77。

pd.DataFrame(X_train_pre).iloc[:, -1].value_counts().head()

6.000000     899
7.000000     823
8.000000     673
5.000000     671
6.772953     511

我可以看到这是因为 imputer 只考虑一列标记为数字的列并取平均值。如何使它考虑数据集中的所有列,尤其是目标变量?

更新:当我包含几列时,结果不再相同,但我仍然无法指定要添加哪些列,以便在为每个列使用特定管道时考虑到 imputer。

标签: pythonpython-3.xmachine-learningscikit-learnimputation

解决方案


推荐阅读