统计与机器学习 / 53.1

梯度提升:逐轮拟合残差

从假设、目标到模型和评估。 梯度提升:逐轮拟合残差。

阅读说明: 保留原笔记的编号与章节顺序;代码只供查看,没有在本站运行。历史输出不代表当前版本的复现结果。截图/外链图以独立整理的公式、表格、示意或文字替换;纠错与必要补充均作说明。

PYTHON · 仅供阅读
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')

Data Generation

PYTHON · 仅供阅读
x = np.arange(0,50)
# just random uniform distributions in differnt range
y1 = np.random.uniform(10,15,10)
y2 = np.random.uniform(20,25,10)
y3 = np.random.uniform(0,5,10)
y4 = np.random.uniform(30,32,10)
y5 = np.random.uniform(13,17,10)
y = np.concatenate((y1,y2,y3,y4,y5))

y
原笔记输出 · 本次未执行
array([14.64512658, 10.13967931, 10.73836776, 12.68372377, 11.37316567,
       10.64054838, 13.70700724, 14.05256657, 10.18393492, 12.54870868,
       24.08965559, 21.9926196 , 22.02590842, 24.70557494, 22.96568662,
       23.57680567, 21.03480281, 23.82207593, 23.51348883, 21.15061034,
        1.3423075 ,  4.32583807,  0.08301714,  0.46767637,  0.46120377,
        4.31457794,  2.10375286,  1.61922885,  2.99698688,  0.2443609 ,
       31.0318623 , 30.0239959 , 30.13120532, 30.93835129, 30.08136955,
       31.38664964, 31.72237704, 30.40315855, 31.62612519, 30.90398874,
       14.01992461, 13.59519575, 16.21252021, 15.95595921, 14.83953088,
       14.05705303, 16.83312374, 13.88154479, 14.94078183, 14.93945268])
PYTHON · 仅供阅读
plt.figure(figsize=(15,5))
plt.plot(x, y, 'o-')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('To Fit A Model That Predict Y From X')
原笔记输出 · 本次未执行
Text(0.5, 1.0, 'To Fit A Model That Predict Y From X')
原笔记输出 · 本次未执行
<Figure size 1080x360 with 1 Axes>

输出图整理: 输入x依次为0到49;各10点分组来自[10,15)、[20,25)、[0,5)、[30,32)、[13,17)的均匀抽样。上方保留了完整50个y历史数值。

Fit models

PYTHON · 仅供阅读
from sklearn.tree import DecisionTreeRegressor
PYTHON · 仅供阅读
X = x.reshape(-1, 1)
plt.rcParams['figure.figsize'] = 20, 50
trees = []
err = y
plot_num = 1
# train 100 decision trees
for i in range(100):
    est = DecisionTreeRegressor(max_leaf_nodes=2)
    est.fit(X, err)
    trees.append(est)
    y_pred = np.sum([tree.predict(X) for tree in trees], axis=0)
    err = y - y_pred
    # err = np.array([1 if v > 0 else (-1 if v < 0 else 0) for v in (y - y_pred)])
    if i % 10 == 0:
        plt.subplot(10, 1, plot_num)
        plot_num += 1
        tx = np.linspace(0, 50, 100)
        ty = np.sum([tree.predict(tx.reshape(-1, 1)) for tree in trees], axis=0)
        plt.plot(x, y, 'o-', label = 'data')
        plt.plot(tx, ty, label='model')
        plt.plot(X, err, 'o-', label='error')
        plt.xlabel('X')
        plt.ylabel('Y')
        plt.title('tree %d' % (i+1))
        _ = plt.legend()
plt.tight_layout()
原笔记输出 · 本次未执行
<Figure size 1440x3600 with 10 Axes>

输出图整理: 每10轮展示前i棵树的累计预测和当前残差;训练流程为拟合残差后累加。学习率取1,训练点拟合更好并不证明泛化更好。原图曲线不作为新运行结果重画。

整理参考资料