XGBoost

技术栈
AI 框架
gradient-boostingdecision-treekaggleclassificationregressiongpu

概览

XGBoost

XGBoost(eXtreme Gradient Boosting)是由陈天奇于 2014 年创建的梯度提升树算法优化实现,被誉为机器学习竞赛的「瑞士军刀」。Kaggle 上超过 50% 的冠军方案都使用了 XGBoost。

核心价值:

  • 极致性能:C++ 底层,多线程并行,比 scikit-learn GBDT 快 10x+
  • 正则化:L1/L2 防止过拟合,比传统 GBDT 泛化更好
  • 原生缺失值处理:自动学习缺失值最佳分支方向
  • GPU 加速tree_method='gpu_hist' 再加速 5-20x
  • 可解释性plot_importance / SHAP 一体化

适用场景: 表格数据分类/回归/排序,金融风控,推荐系统,Kaggle 竞赛。

安装

环境准备

  • Python:>= 3.8(推荐 3.10)
  • 系统:Linux / macOS / Windows 均支持
  • GPU(可选):NVIDIA CUDA 11.4+

安装命令

CPU 版

pip install xgboost

GPU 版

# CUDA 12
pip install xgboost --config-settings cmake.define.CUDA_ARCH=80

# 或直接 pip(需预编译 wheel 匹配)
pip install xgboost==2.0.3

验证安装

import xgboost as xgb
print(xgb.__version__)

# 验证 GPU
from xgboost import XGBClassifier
model = XGBClassifier(tree_method='hist', device='cuda')
print("GPU 可用" if model.get_params()['device'] == 'cuda' else "CPU 模式")

常见安装问题

Q1: ModuleNotFoundError: No module named 'xgboost'

虚拟环境未激活或 pip 路径不一致。确认 which python 对应的 pip:python -m pip install xgboost

Q2: GPU 不可用

检查:nvidia-smi 确认驱动正常。xgboost GPU 需要编译时指定 CUDA 支持,部分 pip wheel 仅 CPU。从源码编译使用 cmake -DUSE_CUDA=ON

Q3: Mac M 系列芯片

xgboost 原生支持 Apple Silicon。pip install xgboost 自动安装 arm64 wheel。

示例

XGBoost 鸢尾花分类 Hello World

目标

用 XGBoost 在经典 Iris 数据集上完成分类,展示训练、交叉验证、特征重要性可视化。

完整代码

import xgboost as xgb
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.metrics import accuracy_score, classification_report
import matplotlib.pyplot as plt

# ─── 1. 加载数据 ───
iris = load_iris()
X, y = iris.data, iris.target
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

# ─── 2. 训练模型 ───
model = xgb.XGBClassifier(
    n_estimators=100,
    max_depth=4,
    learning_rate=0.1,
    subsample=0.8,
    colsample_bytree=0.8,
    objective="multi:softprob",
    random_state=42,
    eval_metric="mlogloss",
)

model.fit(
    X_train, y_train,
    eval_set=[(X_train, y_train), (X_test, y_test)],
    verbose=False,
)

# ─── 3. 评估 ───
y_pred = model.predict(X_test)
acc = accuracy_score(y_test, y_pred)
print(f"测试准确率: {acc:.4f}")
print("\n分类报告:\n", classification_report(y_test, y_pred, target_names=iris.target_names))

# ─── 4. 5 折交叉验证 ───
cv_scores = cross_val_score(model, X, y, cv=5)
print(f"5 折 CV 平均准确率: {cv_scores.mean():.4f} (±{cv_scores.std():.4f})")

# ─── 5. 特征重要性 ───
xgb.plot_importance(model, importance_type="gain")
plt.title("XGBoost Feature Importance (Gain)")
plt.tight_layout()
plt.savefig("feature_importance.png")
plt.show()

print("\n特征重要性 (Gain):")
for name, score in zip(iris.feature_names, model.feature_importances_):
    print(f"  {name}: {score:.4f}")

运行步骤

pip install xgboost scikit-learn matplotlib
python xgboost_iris.py

预期输出

测试准确率: 0.9667

分类报告:
              precision    recall  f1-score   support
      setosa       1.00      1.00      1.00        10
  versicolor       0.91      1.00      0.95        10
   virginica       1.00      0.90      0.95        10

    accuracy                           0.97        30

5 折 CV 平均准确率: 0.95330.0400)

特征重要性 (Gain):
  sepal length (cm): 0.1234
  sepal width (cm):  0.0876
  petal length (cm): 0.4567
  petal width (cm):  0.3323

教程

XGBoost 入门教程:调参心法与数学原理

1. XGBoost 是什么?

XGBoost 是基于 梯度提升决策树 (GBDT) 的并行优化实现。核心思想:串行训练多棵弱决策树,每棵新树拟合前一步的残差。

$$ \hat{y}_i^{(t)} = \hat{y}_i^{(t-1)} + \eta \cdot f_t(x_i) $$

其中 $f_t$ 是第 t 棵树,$\eta$ 是学习率。

2. 相比传统 GBDT 的改进

改进 说明
二阶泰勒展开 使用 Hessian 矩阵,收敛更精确
正则化 L1 + L2 惩罚叶子权重,防止过拟合
列采样 每棵树随机选特征子集(类似 Random Forest)
缺失值处理 自动学习缺失值走左还是右子节点
并行化 特征预排序 + Block 结构,并行找最佳分裂点

3. 三大核心参数

树结构参数

max_depth=6          # 树深度(越大越复杂 → 过拟合风险 ↑)
min_child_weight=1   # 叶子最小样本权重和(越大越保守)
gamma=0              # 分裂所需最小损失减少(越大越保守)

采样参数

subsample=1.0        # 每棵树随机采样的样本比例(0.8 常用)
colsample_bytree=1.0 # 每棵树随机采样的特征比例(0.8 常用)
colsample_bylevel=1.0# 每层分裂时的特征采样

学习参数

learning_rate=0.3    # 学习率(越小需要越多树,0.01-0.1 常用)
n_estimators=100     # 树数量(配合 early_stopping)

4. 调参实战流程

Step 1: 固定 lr=0.1, n_est=1000 + early_stopping=50
         → 调 max_depth(369) 和 min_child_weight(135)
Step 2: 调 subsample(0.60.81.0) 和 colsample_bytree(0.60.81.0)
Step 3: 调 gamma(00.10.5)
Step 4: 降低 lr(0.10.01),增加 n_est,再次 early_stopping

5. 关键参数详解

scale_pos_weight:处理样本不平衡

# 二分类正负比 1:9
scale_pos_weight = 9   # sum(negative) / sum(positive)

objective 选择

任务 objective
二分类 binary:logistic
多分类 multi:softmax (需设 num_class)
回归 reg:squarederror
排序 rank:pairwise

6. 特征重要性类型

  • weight:特征被用于分裂的次数
  • gain:特征分裂带来的平均损失减少(⭐推荐)
  • cover:特征分裂覆盖的样本比例

7. XGBoost vs LightGBM vs CatBoost

维度 XGBoost LightGBM CatBoost
树生长 Level-wise Leaf-wise Symmetric
类别特征 需编码 需编码 原生支持
速度 中等 最快 较慢
小数据 ⭐⭐⭐ ⭐⭐ ⭐⭐
GPU ⭐⭐⭐ ⭐⭐⭐ ⭐⭐

思考题

  1. 为什么 XGBoost 使用二阶泰勒展开而 GBDT 只用一阶?二阶带来了什么?
  2. gamma=0.5min_child_weight=5 都抑制树复杂度,有何不同?
  3. 如果训练集 loss 远低于验证集 loss,应优先调哪个参数?

参考资料

暂无参考文献