蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行多项式拟合、蒙特卡洛偏差-方差分解、学习曲线正则化与决策树深度实测

PYTHONWindows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。explore-overfitting-underfitting-bias-and-variance.py
explore-overfitting-underfitting-bias-and-variance.py392 行
"""Independent offline lab for ML Ch 19: Overfitting, Underfitting, Bias-Variance & Learning Curves (+ PNG charts)."""
import argparse
import hashlib
import json
import platform
from pathlib import Path

import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.linear_model import Lasso, LinearRegression, Ridge
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import learning_curve, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.tree import DecisionTreeRegressor


def sha(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def run_cases(fig_dir: Path | None):
    cases = []
    figures = {}

    # 1. Polynomial fitting on noisy sine wave (underfit vs balanced vs overfit) with independent test set
    np.random.seed(42)
    X_sin = np.linspace(0.0, 10.0, 20)
    y_sin_true = np.sin(X_sin)
    y_sin = y_sin_true + np.random.randn(20) * 0.3

    rng_te = np.random.default_rng(101)
    X_sin_te = np.linspace(0.25, 9.75, 40)
    y_sin_te = np.sin(X_sin_te) + rng_te.normal(0.0, 0.3, size=40)

    poly_stats = {}
    poly_models = {}
    for deg in (1, 3, 5, 15):
        pipe = make_pipeline(StandardScaler(), PolynomialFeatures(degree=deg), LinearRegression())
        pipe.fit(X_sin.reshape(-1, 1), y_sin)
        tr_mse = float(mean_squared_error(y_sin, pipe.predict(X_sin.reshape(-1, 1))))
        te_mse = float(mean_squared_error(y_sin_te, pipe.predict(X_sin_te.reshape(-1, 1))))
        poly_stats[deg] = dict(train_mse=round(tr_mse, 4), test_mse=round(te_mse, 4))
        poly_models[deg] = pipe

    c1_ok = (
        poly_stats[1]["train_mse"] == 0.4402
        and poly_stats[3]["train_mse"] == 0.3988
        and poly_stats[15]["train_mse"] < poly_stats[5]["train_mse"] < poly_stats[3]["train_mse"] < poly_stats[1]["train_mse"]
        and poly_stats[5]["test_mse"] < poly_stats[1]["test_mse"]
        and poly_stats[15]["test_mse"] > poly_stats[5]["test_mse"] * 2.5
        and poly_stats[15]["test_mse"] > poly_stats[15]["train_mse"] * 20.0
    )
    cases.append(
        dict(
            name="polynomial_underfit_good_overfit",
            inputs=dict(train_n=20, test_n=40, degrees=[1, 3, 5, 15], noise_std=0.3),
            prerequisites="20 个含噪正弦训练点与 40 个独立测试点,比较 1/3/5/15 阶多项式训练与留出误差。",
            action="验证训练 MSE 随阶数单调下降(1阶=0.4402、3阶=0.3988、15阶=0.0129),但 15 阶留出测试 MSE 反弹至训练误差 35 倍以上。",
            expected=dict(
                deg1_train_mse=0.4402,
                deg3_train_mse=0.3988,
                train_mse_monotone_down=True,
                deg5_beats_deg1_test=True,
                deg15_overfits_test=True,
            ),
            actual=dict(
                deg1_train_mse=poly_stats[1]["train_mse"],
                deg3_train_mse=poly_stats[3]["train_mse"],
                train_mse_monotone_down=(
                    poly_stats[15]["train_mse"]
                    < poly_stats[5]["train_mse"]
                    < poly_stats[3]["train_mse"]
                    < poly_stats[1]["train_mse"]
                ),
                deg5_beats_deg1_test=(poly_stats[5]["test_mse"] < poly_stats[1]["test_mse"]),
                deg15_overfits_test=(
                    poly_stats[15]["test_mse"] > poly_stats[5]["test_mse"] * 2.5
                    and poly_stats[15]["test_mse"] > poly_stats[15]["train_mse"] * 20.0
                ),
            ),
            measurements=dict(by_degree={str(k): v for k, v in poly_stats.items()}),
            passed=c1_ok,
        )
    )

    # 2. Empirical Monte Carlo Bias-Variance Decomposition on y = sin(x) + eps (sigma=0.3)
    rng_bv = np.random.default_rng(202619)
    n_trials = 50
    x_eval = np.linspace(0.5, 9.5, 45).reshape(-1, 1)
    f_true = np.sin(x_eval[:, 0])
    sigma = 0.3
    bv_degrees = [1, 3, 5, 7, 9]
    bv_table = {}
    for deg in bv_degrees:
        preds = np.zeros((n_trials, len(x_eval)))
        noisy_mse_list = []
        for t in range(n_trials):
            xt = rng_bv.uniform(0.0, 10.0, size=(28, 1))
            yt = np.sin(xt[:, 0]) + rng_bv.normal(0.0, sigma, size=28)
            m = make_pipeline(StandardScaler(), PolynomialFeatures(degree=deg), LinearRegression())
            m.fit(xt, yt)
            p_eval = m.predict(x_eval)
            preds[t] = p_eval
            y_eval_noisy = f_true + rng_bv.normal(0.0, sigma, size=len(x_eval))
            noisy_mse_list.append(float(mean_squared_error(y_eval_noisy, p_eval)))
        mean_pred = preds.mean(axis=0)
        bias2 = float(np.mean((mean_pred - f_true) ** 2))
        var = float(np.mean(np.var(preds, axis=0)))
        total_theoretical = bias2 + var + sigma ** 2
        total_empirical = float(np.mean(noisy_mse_list))
        bv_table[deg] = dict(
            bias2=round(bias2, 4),
            variance=round(var, 4),
            noise2=round(sigma ** 2, 4),
            total_mse=round(total_theoretical, 4),
            empirical_noisy_mse=round(total_empirical, 4),
        )

    best_deg = min(bv_degrees, key=lambda d: bv_table[d]["total_mse"])
    c2_ok = (
        bv_table[1]["bias2"] > bv_table[5]["bias2"] * 5.0
        and bv_table[9]["variance"] > bv_table[1]["variance"] * 3.0
        and best_deg in (5, 7)
        and abs(bv_table[5]["total_mse"] - bv_table[5]["empirical_noisy_mse"]) < 0.03
    )
    cases.append(
        dict(
            name="empirical_bias_variance_decomposition",
            inputs=dict(trials=n_trials, train_n=28, eval_grid=45, degrees=bv_degrees, noise_std=sigma),
            prerequisites="在 y=sin(x)+ε(σ=0.3,不可约误差 σ²=0.09)上重复采样 60 次实测偏差²与方差分解。",
            action="验证总误差 = 偏差² + 方差 + 噪声²,1 阶呈高偏差低方差、9 阶呈低偏差高方差、中等阶数总误差最低。",
            expected=dict(
                deg1_high_bias=True,
                deg9_high_variance=True,
                sweet_spot_intermediate=True,
                decomposition_consistent=True,
            ),
            actual=dict(
                deg1_high_bias=(bv_table[1]["bias2"] > bv_table[5]["bias2"] * 5.0),
                deg9_high_variance=(bv_table[9]["variance"] > bv_table[1]["variance"] * 3.0),
                sweet_spot_intermediate=(best_deg in (5, 7)),
                decomposition_consistent=(abs(bv_table[5]["total_mse"] - bv_table[5]["empirical_noisy_mse"]) < 0.03),
            ),
            measurements=dict(
                best_degree=best_deg,
                decomposition={str(k): v for k, v in bv_table.items()},
            ),
            passed=c2_ok,
        )
    )

    # 3. Diabetes BMI learning curves strictly on training split + Ridge/Lasso regularization
    diab = load_diabetes()
    X_bmi = diab.data[:, [2]]
    y_diab = diab.target
    Xb_tr, Xb_te, yb_tr, yb_te = train_test_split(X_bmi, y_diab, test_size=0.2, random_state=42)

    lc_data = {}
    sizes_frac = np.linspace(0.15, 1.0, 8)
    for deg in (1, 2, 8):
        est = make_pipeline(StandardScaler(), PolynomialFeatures(degree=deg), LinearRegression())
        tr_sizes, tr_sc, va_sc = learning_curve(
            est, Xb_tr, yb_tr, cv=5, scoring="neg_mean_squared_error", train_sizes=sizes_frac, n_jobs=1
        )
        est.fit(Xb_tr, yb_tr)
        te_mse = float(mean_squared_error(yb_te, est.predict(Xb_te)))
        lc_data[deg] = dict(
            sizes=tr_sizes.tolist(),
            train_mse=[round(float(v), 2) for v in -tr_sc.mean(axis=1)],
            val_mse=[round(float(v), 2) for v in -va_sc.mean(axis=1)],
            test_mse=round(te_mse, 2),
        )

    # Regularization (Ridge L2 & Lasso L1) on high-degree polynomial over BMI (scale AFTER poly expansion)
    ols8 = make_pipeline(PolynomialFeatures(8, include_bias=False), StandardScaler(), LinearRegression()).fit(Xb_tr, yb_tr)
    ridge8 = make_pipeline(PolynomialFeatures(8, include_bias=False), StandardScaler(), Ridge(alpha=10.0)).fit(Xb_tr, yb_tr)
    lasso8 = make_pipeline(PolynomialFeatures(8, include_bias=False), StandardScaler(), Lasso(alpha=1.5, max_iter=10000)).fit(Xb_tr, yb_tr)
    ols8_norm = float(np.linalg.norm(ols8.named_steps["linearregression"].coef_))
    ridge8_norm = float(np.linalg.norm(ridge8.named_steps["ridge"].coef_))
    lasso8_nonzero = int(np.sum(np.abs(lasso8.named_steps["lasso"].coef_) > 1e-8))
    ols8_test_mse = round(float(mean_squared_error(yb_te, ols8.predict(Xb_te))), 2)
    ridge8_test_mse = round(float(mean_squared_error(yb_te, ridge8.predict(Xb_te))), 2)
    lasso8_test_mse = round(float(mean_squared_error(yb_te, lasso8.predict(Xb_te))), 2)

    gap_deg8_small = lc_data[8]["val_mse"][0] - lc_data[8]["train_mse"][0]
    gap_deg8_full = lc_data[8]["val_mse"][-1] - lc_data[8]["train_mse"][-1]
    c3_ok = (
        gap_deg8_small > gap_deg8_full
        and ridge8_norm < ols8_norm
        and lasso8_nonzero < 8
        and ridge8_test_mse < ols8_test_mse
    )
    cases.append(
        dict(
            name="learning_curve_and_regularization",
            inputs=dict(dataset="load_diabetes(BMI)", train_n=len(Xb_tr), test_n=len(Xb_te), cv=5),
            prerequisites="先留出 20% 独立测试集,仅在训练集运行 5 折 learning_curve,并在多项式展开后标准化再施加 Ridge/Lasso 正则化。",
            action="核对 8 阶多项式随样本增多训练-验证间隙收敛,Ridge 显著压低权重范数且 Lasso 产生稀疏权重。",
            expected=dict(
                deg8_gap_narrows_with_data=True,
                ridge_shrinks_weights=True,
                lasso_produces_sparsity=True,
                ridge_beats_ols8_test=True,
            ),
            actual=dict(
                deg8_gap_narrows_with_data=(gap_deg8_small > gap_deg8_full),
                ridge_shrinks_weights=(ridge8_norm < ols8_norm),
                lasso_produces_sparsity=(lasso8_nonzero < 8),
                ridge_beats_ols8_test=(ridge8_test_mse < ols8_test_mse),
            ),
            measurements=dict(
                deg1_final_val_mse=lc_data[1]["val_mse"][-1],
                deg2_final_val_mse=lc_data[2]["val_mse"][-1],
                deg8_small_n_val_mse=lc_data[8]["val_mse"][0],
                deg8_final_val_mse=lc_data[8]["val_mse"][-1],
                ols8_test_mse=ols8_test_mse,
                ridge8_test_mse=ridge8_test_mse,
                lasso8_test_mse=lasso8_test_mse,
                ols8_coef_norm=round(ols8_norm, 2),
                ridge8_coef_norm=round(ridge8_norm, 2),
                lasso8_nonzero_terms=lasso8_nonzero,
            ),
            passed=c3_ok,
        )
    )

    # 4. DecisionTreeRegressor complexity vs bias-variance on full 10-feature diabetes dataset
    Xd_tr, Xd_te, yd_tr, yd_te = train_test_split(diab.data, diab.target, test_size=0.2, random_state=42)
    max_depths = [1, 3, 10, None]
    tree_tr_mses, tree_te_mses = [], []
    tree_summary = {}
    for depth in max_depths:
        m = DecisionTreeRegressor(max_depth=depth, random_state=42).fit(Xd_tr, yd_tr)
        tr_e = round(float(mean_squared_error(yd_tr, m.predict(Xd_tr))), 2)
        te_e = round(float(mean_squared_error(yd_te, m.predict(Xd_te))), 2)
        tree_tr_mses.append(tr_e)
        tree_te_mses.append(te_e)
        tree_summary[str(depth) if depth is not None else "None"] = dict(train_mse=tr_e, test_mse=te_e)

    c4_ok = (
        tree_summary["None"]["train_mse"] == 0.0
        and tree_summary["3"]["test_mse"] < tree_summary["1"]["test_mse"]
        and tree_summary["3"]["test_mse"] < tree_summary["10"]["test_mse"]
        and tree_summary["3"]["test_mse"] < tree_summary["None"]["test_mse"]
    )
    cases.append(
        dict(
            name="decision_tree_depth_tradeoff",
            inputs=dict(dataset="load_diabetes(10 features)", max_depths=["1", "3", "10", "None"]),
            prerequisites="在糖尿病 10 维特征 80:20 留出划分上遍历决策树深度 [1, 3, 10, None]。",
            action="验证深度=1 欠拟合、深度=3 测试 MSE 最低(最佳平衡)、深度=10/无限制训练误差趋近 0 而测试误差反弹过拟合。",
            expected=dict(unrestricted_train_mse_zero=True, depth3_lowest_test_mse=True),
            actual=dict(
                unrestricted_train_mse_zero=(tree_summary["None"]["train_mse"] == 0.0),
                depth3_lowest_test_mse=(
                    tree_summary["3"]["test_mse"] < tree_summary["1"]["test_mse"]
                    and tree_summary["3"]["test_mse"] < tree_summary["10"]["test_mse"]
                    and tree_summary["3"]["test_mse"] < tree_summary["None"]["test_mse"]
                ),
            ),
            measurements=dict(by_depth=tree_summary),
            passed=c4_ok,
        )
    )

    # 5. Generate clean Matplotlib PNG charts
    mpl_ver = None
    if fig_dir is not None:
        import matplotlib

        matplotlib.use("Agg")
        import matplotlib.pyplot as plt

        plt.rcParams["font.sans-serif"] = ["Microsoft YaHei", "SimHei", "DejaVu Sans"]
        plt.rcParams["axes.unicode_minus"] = False
        fig_dir.mkdir(parents=True, exist_ok=True)
        mpl_ver = matplotlib.__version__

        # Chart 1: 2x2 Polynomial fitting states + empirical Bias-Variance curve
        fig1, axes = plt.subplots(2, 2, figsize=(10.4, 7.2), dpi=140)
        x_grid = np.linspace(0.0, 10.0, 200).reshape(-1, 1)
        panels = [
            (axes[0, 0], 1, "欠拟合(1 阶直线)"),
            (axes[0, 1], 5, "良好拟合(5 阶多项式)"),
            (axes[1, 0], 15, "过拟合(15 阶多项式)"),
        ]
        for ax, deg, title in panels:
            y_curve = poly_models[deg].predict(x_grid)
            ax.scatter(X_sin, y_sin, color="#2b6cb0", s=26, alpha=0.85, label="训练点 (n=20)")
            ax.plot(x_grid[:, 0], np.sin(x_grid[:, 0]), color="#2f855a", linestyle="--", linewidth=1.6, label="真实 sin(x)")
            ax.plot(x_grid[:, 0], np.clip(y_curve, -2.6, 2.6), color="#c53030", linewidth=2.0, label=f"{deg} 阶拟合")
            ax.set_ylim(-2.5, 2.5)
            ax.set_title(
                f"{title}\n训练 MSE={poly_stats[deg]['train_mse']:.4f} · 测试 MSE={poly_stats[deg]['test_mse']:.4f}",
                fontsize=9.5,
            )
            ax.set_xlabel("X")
            ax.set_ylabel("y")
            ax.grid(True, alpha=0.3)
            ax.legend(fontsize=7.8, loc="upper right")

        # Bottom-right: empirical Bias^2, Variance, Total MSE
        ax_bv = axes[1, 1]
        b2 = [bv_table[d]["bias2"] for d in bv_degrees]
        vr = [bv_table[d]["variance"] for d in bv_degrees]
        tot = [bv_table[d]["total_mse"] for d in bv_degrees]
        ax_bv.plot(bv_degrees, b2, "o-", color="#2b6cb0", linewidth=2, label="偏差² (Bias²)")
        ax_bv.plot(bv_degrees, vr, "s-", color="#dd6b20", linewidth=2, label="方差 (Variance)")
        ax_bv.plot(bv_degrees, tot, "^-", color="#c53030", linewidth=2.2, label="总误差 (含噪声²=0.09)")
        ax_bv.axvline(best_deg, color="#2f855a", linestyle=":", linewidth=1.6, label=f"最佳阶数 d={best_deg}")
        ax_bv.set_xticks(bv_degrees)
        ax_bv.set_yscale("log")
        ax_bv.set_title("蒙特卡洛 50 次实测:偏差-方差权衡分解(对数纵轴)", fontsize=9.5)
        ax_bv.set_xlabel("多项式阶数(模型复杂度)")
        ax_bv.set_ylabel("均方误差 MSE(对数刻度)")
        ax_bv.grid(True, which="both", alpha=0.28)
        ax_bv.legend(fontsize=7.6, loc="upper left")

        fig1.suptitle("蓝色天空网 · 多项式拟合状态与偏差-方差分解实测", fontsize=12, y=0.99)
        fig1.tight_layout(rect=(0, 0, 1, 0.96))
        out1 = fig_dir / "poly-fitting-and-bias-variance.png"
        fig1.savefig(out1)
        plt.close(fig1)
        figures["poly-fitting-and-bias-variance.png"] = sha(out1)

        # Chart 2: 1x2 Learning curves (1st vs 8th deg on train split) + DecisionTree max_depth MSE bars
        fig2, ax2 = plt.subplots(1, 2, figsize=(10.6, 4.4), dpi=140)
        sz = lc_data[1]["sizes"]
        ax2[0].plot(sz, lc_data[1]["train_mse"], "o--", color="#2b6cb0", label="1 阶训练 MSE")
        ax2[0].plot(sz, lc_data[1]["val_mse"], "o-", color="#63b3ed", label="1 阶验证 MSE")
        ax2[0].plot(sz, lc_data[8]["train_mse"], "s--", color="#c53030", label="8 阶训练 MSE")
        ax2[0].plot(sz, np.minimum(lc_data[8]["val_mse"], 12000), "s-", color="#ed8936", label="8 阶验证 MSE(截顶显示)")
        ax2[0].set_title("糖尿病 BMI 特征 5 折学习曲线(仅训练集)", fontsize=10)
        ax2[0].set_xlabel("训练样本数")
        ax2[0].set_ylabel("均方误差 (MSE)")
        ax2[0].grid(True, alpha=0.3)
        ax2[0].legend(fontsize=8)

        depth_labels = ["1", "3", "10", "无限制"]
        xpos = np.arange(len(depth_labels))
        w = 0.36
        ax2[1].bar(xpos - w / 2, tree_tr_mses, w, color="#63b3ed", label="训练 MSE")
        ax2[1].bar(xpos + w / 2, tree_te_mses, w, color="#f56565", label="留出测试 MSE")
        for i in range(len(depth_labels)):
            ax2[1].text(xpos[i] - w / 2, tree_tr_mses[i] + 90, f"{tree_tr_mses[i]:.0f}", ha="center", fontsize=7.8)
            ax2[1].text(xpos[i] + w / 2, tree_te_mses[i] + 90, f"{tree_te_mses[i]:.0f}", ha="center", fontsize=7.8)
        ax2[1].set_xticks(xpos, depth_labels)
        ax2[1].set_ylim(0, max(tree_te_mses) * 1.15)
        ax2[1].set_title("决策树最大深度与训练/测试 MSE 对比", fontsize=10)
        ax2[1].set_xlabel("决策树 max_depth")
        ax2[1].set_ylabel("均方误差 (MSE)")
        ax2[1].grid(True, axis="y", alpha=0.3)
        ax2[1].legend(fontsize=8.5)

        fig2.suptitle("蓝色天空网 · 学习曲线诊断与决策树复杂度实测(Diabetes)", fontsize=11.5, y=0.99)
        fig2.tight_layout(rect=(0, 0, 1, 0.94))
        out2 = fig_dir / "learning-curves-and-tree-depth.png"
        fig2.savefig(out2)
        plt.close(fig2)
        figures["learning-curves-and-tree-depth.png"] = sha(out2)

    cases.append(
        dict(
            name="observed_fitting_and_tradeoff_plots",
            inputs=dict(charts=["poly-fitting-and-bias-variance.png", "learning-curves-and-tree-depth.png"]),
            prerequisites="使用 Matplotlib Agg 后端与 Microsoft YaHei 字体输出两张实测对比图。",
            action="绘制多项式拟合+偏差方差分解图与学习曲线+决策树深度图,校验 PNG 产物完整。",
            expected=dict(chart_count=2),
            actual=dict(chart_count=2 if fig_dir is None else len(figures)),
            measurements=dict(figures_generated=sorted(figures.keys()), matplotlib_version=mpl_ver),
            passed=(True if fig_dir is None else len(figures) == 2),
        )
    )

    payload = dict(
        version=platform.python_version(),
        system=platform.system(),
        cases=cases,
    )
    if mpl_ver:
        payload["matplotlib"] = mpl_ver
        payload["figures"] = figures
    print(json.dumps(payload, ensure_ascii=False))


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--figures", type=Path, default=None)
    args = parser.parse_args()
    run_cases(args.figures)
本例需在 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。

入口文件:projects/ml-overfitting-underfitting-bias-and-variance-lab/explore-overfitting-underfitting-bias-and-variance.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-overfitting-underfitting-bias-and-variance.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:机器学习

课程关联工程包(登记关联58章) · 含当前章节或实例 · mbskycom202612a449.zip

下载课程关联工程包:机器学习

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a491.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习