XGBoost (三)计算案例

样本 ixy
112.1
224.0
336.2
448.1
5510.0
6612.2
7714.1
8816.0
9918.1
101020.2

损失函数:平方损失,λ = 1, γ = 0

损失函数一阶导和二阶导计算公式:

初始预测取均值:

计算每个样本的一阶导和二阶导值:

样本 ixy基础预测一阶导二阶导
112.111.19.01
224.011.17.11
336.211.14.91
448.111.13.01
5510.011.11.11
6612.211.1-1.11
7714.111.1-3.01
8816.011.1-4.91
9918.111.1-7.01
101020.211.1-9.11

我们以分裂点 x < 6 为例,计算下其分裂增益:

节点样本集合一阶导和 (G)二阶导和 (H)
左子集(1, 2, 3, 4, 5)25.15
右子集(6, 7, 8, 9, 10)-25.15
父节点所有样本010

带入到分裂增益计算公式中:

Gain = 0.5 ∗ (105.0 + 105.0 − 0)−0 = 0.5 ∗ 210.0 = 105.0

最后计算下叶子节点的输出值:

# pip install scikit-learn
# pip install xgboost
# pip install matplotlib

from xgboost import XGBRegressor, plot_tree
import numpy as np
import matplotlib.pyplot as plt

def demo():
    # 构造数据
    x = np.array([1,2,3,4,5,6,7,8,9,10]).reshape(-1,1)
    y = np.array([2.1,4.0,6.2,8.1,10.0,12.2,14.1,16.0,18.1,20.2])

    # 训练模型
    xgb = XGBRegressor(n_estimators=2, max_depth=2, learning_rate=0.1, objective='reg:squarederror')
    xgb.fit(x, y)

    # 绘制每棵树
    for idx in range(xgb.n_estimators):
        plt.figure(figsize=(12,8), dpi=150)  # 调整图像大小和分辨率
        plot_tree(xgb, tree_idx=idx, rankdir='LR', with_stats=True)  # 'LR' 横向展示
        plt.show()

    xgb.predict

if __name__ == '__main__':
    demo()