如何在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)
相关推荐
zm-v-159304339862 分钟前
ChatGPT 与 DeepSeek:学术科研的智能 “双引擎”
人工智能·chatgpt
果冻人工智能4 分钟前
美国狂奔,中国稳走,AI赛道上的龟兔之争?
人工智能
果冻人工智能14 分钟前
再谈AI与程序员: AI 写的代码越来越多,那我们还需要开发者吗?
人工智能
大脑探路者18 分钟前
【PyTorch】继承 nn.Module 创建简单神经网络
人工智能·pytorch·神经网络
无代码Dev39 分钟前
如何使用AI去水印(ChatGPT去除图片水印)
人工智能·ai·ai-native
达柳斯·绍达华·宁1 小时前
自动驾驶04:点云预处理03
人工智能·机器学习·自动驾驶
wgc2k1 小时前
吴恩达深度学习复盘(4)神经网络的前向传播
人工智能·深度学习
屎派克1 小时前
神经网络知识
人工智能·深度学习·神经网络
liuhaoran___1 小时前
计算机求职面试中高频出现的经典题目分类整理
python
补三补四1 小时前
k近邻算法K-Nearest Neighbors(KNN)
人工智能·机器学习