从‘欠拟合’到‘过拟合’:手把手用AdaBoostRegressor可视化理解集成学习的拟合过程

张开发
2026/4/21 3:34:19 15 分钟阅读

分享文章

从‘欠拟合’到‘过拟合’:手把手用AdaBoostRegressor可视化理解集成学习的拟合过程
从‘欠拟合’到‘过拟合’用AdaBoostRegressor可视化集成学习的拟合演变当第一次接触机器学习中的集成学习概念时很多人会被弱学习器组合成强学习器的说法所困惑。究竟这些弱学习器是如何协同工作的为什么增加学习器数量有时能提升性能有时却会导致过拟合本文将通过可视化手段带你直观理解AdaBoost回归模型从欠拟合到过拟合的完整演变过程。1. 理解AdaBoost回归的核心机制AdaBoostAdaptive Boosting是一种迭代式的集成学习方法其核心思想是通过调整样本权重分布让后续的弱学习器更加关注之前被错误预测的样本。在回归任务中这种关注体现在对误差较大的样本赋予更高权重。1.1 权重调整的动态过程AdaBoost回归的权重更新遵循以下数学原理样本i在第t轮的权重更新公式 w_i^(t1) w_i^(t) * exp(α_t * L(y_i, H_t(x_i))) 其中 - α_t是第t个弱学习器的权重 - L是损失函数线性、平方或指数 - H_t是第t轮的集成预测结果这个公式表明预测误差越大的样本在下一轮迭代中会获得越高的权重迫使后续的弱学习器更加关注这些困难样本。1.2 弱学习器的组合策略与分类任务不同AdaBoost回归采用加权中位数作为最终预测最终预测 median{w1*h1(x), w2*h2(x), ..., wT*hT(x)}这种策略比简单平均更鲁棒能有效抵抗异常弱学习器的干扰。下表对比了不同组合策略的特点组合方式优点缺点适用场景简单平均计算简单受异常值影响大弱学习器性能均衡加权平均区分贡献度权重难确定学习器差异明显加权中位数抗干扰强计算稍复杂存在不稳定弱学习器2. 构建可视化实验环境为了直观展示拟合过程我们创建一个含噪声的正弦波组合数据集。这种数据具有足够的复杂性能清晰展现模型从欠拟合到过拟合的演变。2.1 数据生成与特征import numpy as np import matplotlib.pyplot as plt # 生成训练数据 np.random.seed(42) X np.linspace(0, 10, 300) y np.sin(X) np.sin(2*X) np.random.normal(0, 0.2, len(X)) # 生成测试数据用于观察泛化能力 X_test np.linspace(0, 10, 100) y_test np.sin(X_test) np.sin(2*X_test) np.random.normal(0, 0.2, len(X_test))2.2 基础可视化函数创建一个绘制拟合曲线的函数方便观察不同阶段的模型表现def plot_fitting_curve(estimator, X, y, X_testNone, y_testNone, axNone): if ax is None: _, ax plt.subplots(figsize(10, 6)) # 绘制训练数据 ax.scatter(X, y, ck, alpha0.5, labelTraining data) # 绘制测试数据如果提供 if X_test is not None and y_test is not None: ax.scatter(X_test, y_test, cr, alpha0.3, labelTest data) # 生成预测曲线 X_plot np.linspace(0, 10, 500).reshape(-1, 1) y_plot estimator.predict(X_plot) ax.plot(X_plot, y_plot, linewidth2, labelfn_estimators{estimator.n_estimators}) ax.set_xlabel(X) ax.set_ylabel(y) ax.legend() return ax3. 观察n_estimators的影响n_estimators参数控制弱学习器的数量是影响模型拟合程度的关键因素之一。我们固定决策树深度max_depth3观察增加弱学习器数量时的变化。3.1 从1到100的演变过程from sklearn.ensemble import AdaBoostRegressor from sklearn.tree import DecisionTreeRegressor # 创建不同n_estimators的模型 estimators [ AdaBoostRegressor( DecisionTreeRegressor(max_depth3), n_estimatorsn, random_state42 ) for n in [1, 5, 10, 50, 100] ] # 训练并可视化 fig, axes plt.subplots(2, 3, figsize(18, 10)) for ax, est in zip(axes.ravel(), estimators): est.fit(X.reshape(-1, 1), y) plot_fitting_curve(est, X, y, X_test, y_test, axax) plt.tight_layout()3.2 关键观察点通过可视化可以清晰看到n_estimators1严重欠拟合只能捕捉最基础的趋势n_estimators5开始拟合主要波动但细节不足n_estimators10捕捉到主要模式局部仍有偏差n_estimators50拟合效果良好接近真实函数n_estimators100可能开始过拟合训练数据中的噪声提示在测试数据上红色点当n_estimators超过50后预测曲线开始过度贴合训练数据中的噪声点这是过拟合的典型表现。4. 探索max_depth的作用决策树深度决定了每个弱学习器的表达能力。我们固定n_estimators50观察不同max_depth的影响。4.1 深度变化的对比实验depths [1, 2, 3, 5, 7, 10] models [ AdaBoostRegressor( DecisionTreeRegressor(max_depthd), n_estimators50, random_state42 ) for d in depths ] fig, axes plt.subplots(2, 3, figsize(18, 10)) for ax, model, d in zip(axes.ravel(), models, depths): model.fit(X.reshape(-1, 1), y) plot_fitting_curve(model, X, y, X_test, y_test, axax) ax.set_title(fmax_depth{d}) plt.tight_layout()4.2 深度与模型复杂度关系观察发现max_depth1严重欠拟合只能产生分段常数预测max_depth2开始呈现基本波动趋势max_depth3达到较好平衡拟合主要模式max_depth≥5明显过拟合开始捕捉噪声细节下表总结了不同深度下的表现max_depth训练误差测试误差拟合状态模型复杂度1高高欠拟合低2中中适度中低3低最低最佳中等5很低升高过拟合中高7极低很高严重过拟合高5. 寻找最佳平衡点理想的模型应该在欠拟合和过拟合之间找到平衡点。我们可以通过交叉验证来量化这个过程。5.1 定义评估函数from sklearn.model_selection import cross_val_score def evaluate_model(estimator, X, y): scores cross_val_score(estimator, X.reshape(-1, 1), y, scoringneg_mean_squared_error, cv5) return -scores.mean()5.2 参数网格搜索import pandas as pd results [] for depth in [1, 2, 3, 4, 5]: for n_est in [10, 30, 50, 100]: model AdaBoostRegressor( DecisionTreeRegressor(max_depthdepth), n_estimatorsn_est, random_state42 ) score evaluate_model(model, X, y) results.append({ max_depth: depth, n_estimators: n_est, MSE: score }) results_df pd.DataFrame(results) pivot_table results_df.pivot(max_depth, n_estimators, MSE)5.3 热力图可视化import seaborn as sns plt.figure(figsize(10, 6)) sns.heatmap(pivot_table, annotTrue, fmt.3f, cmapYlGnBu) plt.title(Cross-validated MSE for different parameters) plt.xlabel(Number of estimators) plt.ylabel(Max tree depth)从热力图可以清晰看出当max_depth3、n_estimators50时模型达到了最佳的偏差-方差平衡。6. 阶段性预测可视化AdaBoost的迭代特性让我们可以观察模型在训练过程中的逐步改进。下面展示前10个弱学习器的累积效果。6.1 阶段性预测函数def plot_staged_predictions(estimator, X, y, n_steps10): plt.figure(figsize(10, 6)) plt.scatter(X, y, ck, alpha0.5, labelTraining data) # 获取阶段性预测 predictions [] for pred in estimator.staged_predict(X.reshape(-1, 1)): predictions.append(pred) # 绘制前n_steps步 for i in range(min(n_steps, len(predictions))): plt.plot(X, predictions[i], alpha(i1)/n_steps, labelfStep {i1}) plt.xlabel(X) plt.ylabel(y) plt.legend() plt.title(fFirst {n_steps} boosting steps)6.2 逐步改进过程model AdaBoostRegressor( DecisionTreeRegressor(max_depth3), n_estimators50, random_state42 ) model.fit(X.reshape(-1, 1), y) plot_staged_predictions(model, X, y)可以看到最初的几步改进最为显著随着迭代进行后续改进逐渐趋于平缓。这正是boosting算法的特点——前期快速降低偏差后期主要优化方差。

更多文章