如何在Sklearn Pipeline中运行CatBoost

介绍

CatBoost的一大特点是可以很好的处理类别特征(Categorical Features)。当我们将其结合到Sklearn的Pipeline中时,会发生如下报错:

shell 复制代码
_catboost.CatBoostError: 'data' is numpy array of floating point numerical type, it means no categorical features, but 'cat_features' parameter specifies nonzero number of categorical features

因为CatBoost需要检查输入训练数据pandas.DataFrame中对应的cat_features。如果我们使用Pipeline后,输入给.fit()的数据是被修改过的,DataFrame中的columns的名字变为了数字。

解决方案

我们提前在数据上使用Pipeline,然后将原始数据转换为Pipeline处理后的数据,然后检索出其中包含的类别特征,将其传输给Catboost。

python 复制代码
# define your pipeline
pipeline = Pipeline(steps=[
    ('preprocessor', preprocessor),
    ('classifier', model),
])

preprocessor.fit(X_train)
transformed_X_train = pd.DataFrame(preprocessor.transform(X_train)).convert_dtypes()

new_cat_feature_idx = [transformed_X_train.columns.get_loc(col) for col in transformed_X_train.select_dtypes(include=['int64', 'bool']).columns]

pipeline.fit(X_train, y_train, classifier__cat_features=new_cat_feature_idx)
相关推荐
Together_CZ6 分钟前
DarkIR: Robust Low-Light Image Restoration——鲁棒的低光照图像复原
python·image·robust·darkir·鲁棒的低光照图像复原·low-light·restoration
探索宇宙真理.6 分钟前
WordPress AI Engine信息泄露漏洞 | CVE-2025-11749 复现&研究
人工智能·经验分享·开源·安全漏洞
_妲己10 分钟前
stable diffusion的MLSD直线(AI室内设计)
人工智能·stable diffusion
拾贰_C20 分钟前
【python | pytorch | scipy】scipy scikit-learn库相互依赖?
pytorch·python·scipy
FF-Studio27 分钟前
Ubuntu 24.04 磁盘爆满“灵异“事件:Btrfs, Snapper 与删不掉的空间
linux·运维·人工智能·ubuntu
BoBoZz1927 分钟前
PolyDataContourToImageData 3D集合图像转换成等效3D二值图像
python·vtk·图形渲染·图形处理
2401_8414956431 分钟前
【自然语言处理】关系性形容词的特征
人工智能·python·自然语言处理·自动识别·特征验证·关系性形容词·语言学规则和计算
rebekk38 分钟前
Hydra介绍
人工智能·python
我不是小upper39 分钟前
从理论到代码:随机森林 + GBDT+LightGBM 融合建模解决回归问题
人工智能·深度学习·算法·随机森林·机器学习·回归
青啊青斯42 分钟前
python markdown转word【包括字体指定】
开发语言·python·word