如何在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)
相关推荐
华研前沿标杆游学12 小时前
2026走进滕讯:小游戏×大模型产业交流记
python
_codemonster12 小时前
计算机视觉入门到实战系列(八)Harris角点检测算法
python·算法·计算机视觉
数说星榆18112 小时前
在线高清泳道图制作工具 无水印 PC
大数据·人工智能·架构·机器人·流程图
默默前行的虫虫12 小时前
nicegui的3D可视化
python
说私域12 小时前
B站内容生态下的私域流量运营创新:基于AI智能名片链动2+1模式与S2B2C商城小程序的融合实践
人工智能·小程序·流量运营
特立独行的猫a12 小时前
告别写作焦虑:用 n8n + AI 打造“输入即发布”的自驱动写作工作流
人工智能·工作流·n8n
老胡全房源系统12 小时前
2026年1月适合房产经纪人用的房产中介管理系统
大数据·人工智能·房产经纪人培训
GISer_Jing12 小时前
智能体工具使用、规划模式
人工智能·设计模式·prompt·aigc
小小工匠12 小时前
LLM - Claude Code Skills 实战指南:用模块化“技能包”重构AI 开发工作流
人工智能·claude code·skills
双翌视觉13 小时前
深入解析远心镜头的工作原理与选型
人工智能·数码相机·机器学习