Python实现CatBoost分类模型实战指南_从入门到精通

2025-05-03 27

Image

使用Python实现CatBoost分类模型

CatBoost是由Yandex开发的一种梯度提升决策树算法,特别适合处理分类特征。下面我将展示如何使用Python实现CatBoost分类模型。

1. 安装CatBoost

需要安装CatBoost库:

pip install catboost

2. 基本实现代码

import numpy as np
import pandas as pd
from catboost import CatBoostClassifier, Pool
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report

# 加载数据集(这里以鸢尾花数据集为例)
from sklearn.datasets import load_iris
data = load_iris()
X = pd.DataFrame(data.data, columns=data.feature_names)
y = data.target

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 定义分类特征(如果有的话)
# CatBoost可以自动处理分类特征,但需要明确指定哪些是分类特征
cat_features = []  # 在这个例子中没有分类特征

# 创建CatBoost分类器
model = CatBoostClassifier(
    iterations=500,  # 树的数量
    learning_rate=0.1,  # 学习率
    depth=6,  # 树的深度
    loss_function='MultiClass',  # 多分类问题
    verbose=100,  # 每100次迭代显示一次日志
    random_seed=42
)

# 训练模型
model.fit(
    X_train, y_train,
    cat_features=cat_features,
    eval_set=(X_test, y_test),
    plot=True  # 显示训练过程图表
)

# 预测
y_pred = model.predict(X_test)
y_pred_proba = model.predict_proba(X_test)

# 评估模型
print(f"Accuracy: {accuracy_score(y_test, y_pred):.4f}")
print("\nClassification Report:")
print(classification_report(y_test, y_pred))

# 特征重要性
feature_importance = model.get_feature_importance()
feature_names = X.columns
for score, name in sorted(zip(feature_importance, feature_names), reverse=True):
    print(f"{name}: {score:.2f}")

3. 使用分类特征示例

如果数据集中包含分类特征,可以这样处理:

# 假设我们有一个包含分类特征的数据集
data = {
    'num_feature1': np.random.rand(1000),
    'num_feature2': np.random.rand(1000),
    'cat_feature1': np.random.choice(['A', 'B', 'C'], size=1000),
    'cat_feature2': np.random.choice(['X', 'Y'], size=1000),
    'target': np.random.choice([0, 1], size=1000)
}
df = pd.DataFrame(data)

X = df.drop('target', axis=1)
y = df['target']

# 指定分类特征列名
cat_features = ['cat_feature1', 'cat_feature2']

# 划分数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 创建模型
model = CatBoostClassifier(
    iterations=500,
    learning_rate=0.05,
    depth=5,
    loss_function='Logloss',  # 二分类问题
    eval_metric='AUC',
    cat_features=cat_features,
    verbose=100
)

# 训练模型
model.fit(X_train, y_train, eval_set=(X_test, y_test))

# 预测和评估
y_pred = model.predict(X_test)
print(f"Accuracy: {accuracy_score(y_test, y_pred):.4f}")

4. 高级功能

交叉验证

from catboost import cv

params = {
    'loss_function': 'Logloss',
    'iterations': 100,
    'learning_rate': 0.1,
    'depth': 3
}

cv_data = cv(
    params=params,
    pool=Pool(X, y, cat_features=cat_features),
    fold_count=5,
    shuffle=True,
    partition_random_seed=0,
    plot=True
)

自定义评估指标

class LoglossMetric(object):
    def get_final_error(self, error, weight):
        return error / (weight + 1e-38)

    def is_max_optimal(self):
        return False

    def evaluate(self, approxes, target, weight):
        # approxes - 预测值
        # target - 真实值
        # weight - 权重
        
        error_sum = 0.0
        weight_sum = 0.0
        
        for i in range(len(target)):
            w = 1.0 if weight is None else weight[i]
            weight_sum += w
            error_sum += w * (target[i] * approxes[i] + (1 - target[i]) * (1 - approxes[i]))
        
        return error_sum, weight_sum

model = CatBoostClassifier(
    iterations=100,
    learning_rate=0.1,
    eval_metric=LoglossMetric()
)

5. 模型保存与加载

# 保存模型
model.save_model('catboost_model.cbm')

# 加载模型
loaded_model = CatBoostClassifier()
loaded_model.load_model('catboost_model.cbm')

# 使用加载的模型进行预测
y_pred_loaded = loaded_model.predict(X_test)

CatBoost的优势在于它对分类特征的原生支持、自动处理缺失值、减少过拟合的特性,以及通常不需要太多的参数调优就能获得不错的结果。

(牛站网络)

1. 本站所有资源来源于用户上传和网络,因此不包含技术服务请大家谅解!如有侵权请邮件联系客服!cheeksyu@vip.qq.com
2. 本站不保证所提供下载的资源的准确性、安全性和完整性,资源仅供下载学习之用!如有链接无法下载、失效或广告,请联系客服处理!
3. 您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容资源!如用于商业或者非法用途,与本站无关,一切后果请用户自负!
4. 如果您也有好的资源或教程,您可以投稿发布,成功分享后有积分奖励和额外收入!
5.严禁将资源用于任何违法犯罪行为,不得违反国家法律,否则责任自负,一切法律责任与本站无关