如何在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)
相关推荐
宣宣猪的小花园.9 分钟前
【控制算法】PID 不只是三个参数:比例、积分、微分各在解决什么问题
人工智能·嵌入式硬件·机器学习
sukioe13 分钟前
一张图、两把锁:AI 物流履约平台的确定性边界设计
人工智能·python·ai·langchain
爱吃火鸡面呀16 分钟前
OpenCV 实战:文档扫描与神经风格迁移完整指南
人工智能·opencv·计算机视觉
2601_9622035128 分钟前
【SpringBoot3】面向切面 AspectJ AOP 使用详解
开发语言·前端·python
TechEdu20260629 分钟前
[人工智能]Gemini(Google DeepMind):多模态模型、智能体与工程实践
人工智能·ai
程序员大雄学编程30 分钟前
微积分43. 无穷积分入门:从概念到Python实战可视化
开发语言·python·学习·微积分
java1234_小锋31 分钟前
YOLO26 计算机视觉 - 训练自己的 YOLO26 模型
人工智能·yolo·机器学习·计算机视觉·yolo26
小程序设计36 分钟前
机械设计之大蒜茎叶粉碎抛送装置设计
人工智能·数据挖掘
测试老哥36 分钟前
Postman获取token并设置token依赖步骤
自动化测试·软件测试·python·测试工具·测试用例·接口测试·postman
郝学胜-神的一滴39 分钟前
C++11 工程级应用 06:自己造一个类似Python的Range迭代器
开发语言·c++·windows·python·程序人生·microsoft