如何在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)
相关推荐
月白风清江有声1 小时前
爆炸仿真的学习日志
人工智能
风逸hhh1 小时前
python打卡day46@浙大疏锦行
开发语言·python
火兮明兮2 小时前
Python训练第四十三天
开发语言·python
华奥系科技2 小时前
智慧水务发展迅猛:从物联网架构到AIoT系统的跨越式升级
人工智能·物联网·智慧城市
R²AIN SUITE2 小时前
MCP协议重构AI Agent生态:万能插槽如何终结工具孤岛?
人工智能
互联网杂货铺3 小时前
完美搭建appium自动化环境
自动化测试·软件测试·python·测试工具·职场和发展·appium·测试用例
b***25113 小时前
动力电池点焊机:驱动电池焊接高效与可靠的核心力量|比斯特自动化
人工智能·科技·自动化
Gyoku Mint3 小时前
机器学习×第二卷:概念下篇——她不再只是模仿,而是开始决定怎么靠近你
人工智能·python·算法·机器学习·pandas·ai编程·matplotlib
小和尚同志3 小时前
通俗易懂的 MCP 概念入门
人工智能·aigc
莱茵菜苗3 小时前
Python打卡训练营day46——2025.06.06
开发语言·python