python - 有和没有基于目标的编码的管道
问题描述
如果我同时使用简单编码器和目标编码器,我对组装管道的最佳方式感到困惑。我在这里找到了这个示例,它说明问题与必须将目标变量与要编码的变量一起传递有关。
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
解决方案
目标变量y
被传递并在gs.fit(X, y)
. 您不需要(也不应该)将其指定为ColumnTransformer
.
(两者pipeline_ordinal
都pipeline_loo
可以访问y
,尽管前者实际上不会使用它。)
推荐阅读
- c# - 如何替换 DataGridView 中的整行值?
- javascript - 在Angular中倒退时间的最佳方法是什么
- java - 使用 RestTemplate 调用 API 时如何捕获超时异常
- javascript - 如何避免标题标签中的换行符?
- python - 通过 SqlAlchemy 中的 M2M 关系“跳转”的关系(用户 -> 角色 -> 权限)
- android - ffmpeg解码,通过shader得到avFrame(yuv420p),yuv转rgb,但是太绿了
- git - git interactive rebase squash 创建了全新的分支
- c - 如何将int类型转换为ieee754?
- python - 如何使用 Opencv 检测另一个轮廓中的一个轮廓?
- node.js - 访问 Firebase 存储中的文件会导致 403(“要计费的项目与缺少的计费帐户相关联”)