【问题标题】:Using a specific IterativeImputer in sklearn Pipeline for each column在 sklearn Pipeline 中为每一列使用特定的 IterativeImputer
【发布时间】:2022-03-29 17:45:22
【问题描述】:

我正在运行回归算法并使用 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

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

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

【问题讨论】:

    标签: python python-3.x machine-learning scikit-learn imputation


    【解决方案1】:

    imputer 只考虑传递给它的列。例如,如果您想在数值的插补过程中包含一些分类列,您还需要将分类列传递给管道。

    numerical.extend(['cat1', 'cat2'])
    

    这里出现的问题是,分类和数值管道中的列都会重复,因此您必须对此采取一些措施,但我不确定到底是什么。

    在插补过程中考虑目标变量似乎是数据泄漏,所以我不建议这样做。

    【讨论】:

      猜你喜欢
      • 2020-05-30
      • 2020-02-25
      • 2021-01-23
      • 2017-08-31
      • 2020-09-08
      • 2018-01-24
      • 2019-06-05
      • 2021-11-04
      • 1970-01-01
      相关资源
      最近更新 更多