首页 > 解决方案 > 有和没有基于目标的编码的管道

问题描述

如果我同时使用简单编码器和目标编码器,我对组装管道的最佳方式感到困惑。我在这里找到了这个示例,它说明问题与必须将目标变量与要编码的变量一起传递有关。

from examples.source_data.loaders import get_mushroom_data
from sklearn.compose import ColumnTransformer
from category_encoders import TargetEncoder

# get data from the mushroom dataset
X, y, _ = get_mushroom_data()

# encode the specified columns
ct = ColumnTransformer(
    [
        ('Target encoding', TargetEncoder(), ['bruises', 'odor'])
    ], remainder='passthrough'
)
encoded = ct.fit_transform(X=X, y=y)

但是,fit_transform我不想直接执行 a ,而是将其添加为我的管道的一部分,以便我可以在交叉折叠验证方案中执行此操作。

因此,不起作用的代码是:

pipeline_ordinal = Pipeline(steps=[('imputer', SimpleImputer(strategy='constant', fill_value='missing'))
    ,('ord encoding', ce.ordinal.OrdinalEncoder())])

pipeline_loo = Pipeline(steps=[('imputer', SimpleImputer(strategy='constant', fill_value='missing'))
    ,('loo encoding', ce.LeaveOneOutEncoder())])

preprocessor = ColumnTransformer(
    transformers=[('simple', pipeline_ordinal, ['x1','x2','x3']),
                  ('targetbased', pipeline_loo, ['x4','x5','y'])
                 ])

rf = RandomForestRegressor()

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

gs = GridSearchCV(pipe, param_grid=params, cv = cv)

gs.fit(X, y)

关于将这一切修补在一起的更好方法的任何想法?

编辑:

问题在于将 X 传递给 gs.fit()。照原样,上面的代码说:ValueError: A given column is not a column of the dataframe

如果我尝试变得聪明并在 X 中发送“y”,那么它会告诉我ValueError: cannot reindex from a duplicate axis

标签: pythonmachine-learningencodingscikit-learn

解决方案


目标变量y被传递并在gs.fit(X, y). 您不需要(也不应该)将其指定为ColumnTransformer.

(两者pipeline_ordinalpipeline_loo可以访问y,尽管前者实际上不会使用它。)


推荐阅读