如何在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)
相关推荐
TMT星球6 分钟前
轻松健康集团携手武汉市数据局等发布数智产业创新联合发展计划
人工智能
AI的探索之旅9 分钟前
AI + LLM Wiki 高效学习 OpenCV:我的 8 步闭环方法论
人工智能·opencv·学习
FriendshipT10 分钟前
Ultralytics:解读 YOLO26 知识蒸馏
人工智能·pytorch·python·深度学习·yolo
蓝田~13 分钟前
AI Demo到上线有多远?→ 安全纵深防御+Token成本精确计算+可观测性,PrismAI三周工程化复盘
人工智能·安全
东坡肘子18 分钟前
Apple Intelligence 已通过审核,即将在中国提供服务 -- 肘子的 Swift 周报 #148
人工智能·swiftui·swift
BUG研究员_20 分钟前
工具绑定与调用
python·agent
苏灿烤鱼20 分钟前
AI Agent 深拆 | 图能让 AI 决策可追责吗?Semantica 登顶拆解
python·github·agent
watersink21 分钟前
机器学习FM、FFM
人工智能·机器学习
九硕智慧建筑一体化厂家26 分钟前
从光伏板到护眼灯,直流照明如何重构绿色校园的能源基因
运维·人工智能·重构·智慧城市·能源
user-猴子1 小时前
2026国产AI智能体七强横评:WorkBuddy、AiPy、悟空、Kimi Work、TRAE Work、QoderWork、百度搭子怎么选?
人工智能·百度·dubbo