如何在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)
相关推荐
独行soc21 分钟前
2025年渗透测试面试题总结-234(题目+回答)
网络·python·安全·web安全·渗透测试·1024程序员节·安全狮
木头左32 分钟前
年化波动率匹配原则在ETF网格区间选择中的应用
python
清空mega36 分钟前
从零开始搭建 flask 博客实验(3)
后端·python·flask
熙梦数字化1 小时前
2025汽车零部件行业数字化转型落地方案
大数据·人工智能·汽车
刘海东刘海东1 小时前
逻辑方程结构图语言的机器实现(草稿)
人工智能
亮剑20181 小时前
第2节:程序逻辑与控制流——让程序“思考”
开发语言·c++·人工智能
hixiong1231 小时前
C# OpenCVSharp使用 读光-票证检测矫正模型
人工智能·opencv·c#
程序员小远1 小时前
7个常见的Jmeter压测问题
自动化测试·软件测试·python·测试工具·测试用例·压力测试·性能测试
大千AI助手1 小时前
HotpotQA:推动多跳推理问答发展的标杆数据集
人工智能·神经网络·llm·qa·大千ai助手·hotpotqa·多跳推理能力
红尘炼丹客1 小时前
《DeepSeek-OCR: Contexts Optical Compression》速览
人工智能·python·自然语言处理·ocr