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

运行 MSE/交叉熵核对、有限差分检验及一维/二维梯度下降收敛实测

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-loss-function-and-gradient.py
explore-loss-function-and-gradient.py196 行
"""Independent offline lab for ML Ch 18: Loss Function and Gradient (MSE, Log Loss, 1D & 2D Gradient Descent)."""
import json
import math
import platform

import numpy as np
from sklearn.metrics import log_loss, mean_squared_error


def main():
    cases = []

    # 1. MSE manual vs sklearn & quadratic penalty ratio
    y_true = np.array([3.0, -0.5, 2.0, 7.0, 4.0])
    y_pred = np.array([2.5, 0.0, 2.0, 8.0, 5.0])
    mse_manual = float(np.sum((y_true - y_pred) ** 2) / len(y_true))
    mse_sklearn = float(mean_squared_error(y_true, y_pred))
    err_diff = abs(mse_manual - mse_sklearn)
    penalty_ratio = (10.0 ** 2) / (2.0 ** 2)

    c1_ok = abs(mse_manual - 0.5) < 1e-12 and err_diff < 1e-12 and penalty_ratio == 25.0
    cases.append(
        dict(
            name="mse_manual_vs_sklearn_and_penalty",
            inputs=dict(y_true=y_true.tolist(), y_pred=y_pred.tolist()),
            prerequisites="5 样本回归预测与真实值对照,核对手动 MSE 与 sklearn mean_squared_error。",
            action="计算手动与库函数 MSE 均为 0.5(误差 <1e-12),并核对误差放大 5 倍时平方惩罚放大 25 倍。",
            expected=dict(mse_manual=0.5, mse_sklearn=0.5, penalty_ratio_10_over_2=25.0),
            actual=dict(
                mse_manual=round(mse_manual, 6),
                mse_sklearn=round(mse_sklearn, 6),
                penalty_ratio_10_over_2=penalty_ratio,
            ),
            measurements=dict(
                abs_diff=err_diff,
                rmse=round(math.sqrt(mse_manual), 4),
            ),
            passed=c1_ok,
        )
    )

    # 2. Binary Cross-Entropy (Log Loss) manual vs sklearn & confident-error penalty
    y_bin = np.array([1, 0, 0, 1])
    p_bin = np.array([0.9, 0.1, 0.2, 0.8])
    bce_manual = float(-np.mean(y_bin * np.log(p_bin) + (1 - y_bin) * np.log(1.0 - p_bin)))
    bce_sklearn = float(log_loss(y_bin, p_bin))
    bce_diff = abs(bce_manual - bce_sklearn)
    loss_p09 = float(-math.log(0.9))
    loss_p01 = float(-math.log(0.1))

    c2_ok = bce_diff < 1e-12 and abs(bce_manual - 0.164252033486018) < 1e-9 and loss_p01 > 20.0 * loss_p09
    cases.append(
        dict(
            name="binary_cross_entropy_manual_vs_sklearn",
            inputs=dict(y_true=y_bin.tolist(), y_pred_prob=p_bin.tolist()),
            prerequisites="4 样本二分类概率与标签,核对自然对数交叉熵手动公式与 sklearn log_loss。",
            action="验证手动与库函数 Log Loss 精确一致(≈0.164252),且正类误判 p=0.1 的单样本损失约为 p=0.9 的 21.85 倍。",
            expected=dict(manual_matches_sklearn=True, log_loss_6dp=0.164252, wrong_penalty_gt_20x=True),
            actual=dict(
                manual_matches_sklearn=(bce_diff < 1e-12),
                log_loss_6dp=round(bce_manual, 6),
                wrong_penalty_gt_20x=(loss_p01 > 20.0 * loss_p09),
            ),
            measurements=dict(
                abs_diff=bce_diff,
                single_loss_p09=round(loss_p09, 4),
                single_loss_p01=round(loss_p01, 4),
                penalty_multiplier=round(loss_p01 / loss_p09, 2),
            ),
            passed=c2_ok,
        )
    )

    # 3. 1D Gradient Descent on L(w) = w^2 + finite-difference gradient check + LR regimes
    def loss_1d(w: float) -> float:
        return w ** 2

    def grad_1d(w: float) -> float:
        return 2.0 * w

    eps = 1e-6
    fd_grad = (loss_1d(5.0 + eps) - loss_1d(5.0 - eps)) / (2.0 * eps)
    grad_err = abs(fd_grad - grad_1d(5.0))

    def run_gd(start_w: float, lr: float, iters: int):
        w = start_w
        w_hist = [w]
        l_hist = [loss_1d(w)]
        for _ in range(iters):
            w = w - lr * grad_1d(w)
            w_hist.append(w)
            l_hist.append(loss_1d(w))
        return w_hist, l_hist

    w_good, l_good = run_gd(5.0, 0.1, 20)
    w_slow, l_slow = run_gd(5.0, 0.01, 20)
    w_div, l_div = run_gd(5.0, 1.1, 20)

    exact_w20 = 5.0 * (0.8 ** 20)
    monotone_dec = all(l_good[i + 1] < l_good[i] for i in range(len(l_good) - 1))
    c3_ok = (
        grad_err < 1e-8
        and abs(w_good[-1] - exact_w20) < 1e-12
        and monotone_dec
        and l_good[-1] < l_slow[-1] < l_good[0]
        and l_div[-1] > l_good[0]
    )
    cases.append(
        dict(
            name="gradient_descent_1d_and_lr_regimes",
            inputs=dict(start_w=5.0, iterations=20, lrs=[0.01, 0.1, 1.1]),
            prerequisites="L(w)=w² 的解析导数 2w 与中心有限差分核对,比较过小/合适/过大三种学习率。",
            action="验证 lr=0.1 迭代 20 步精确收敛至 w=5*0.8^20≈0.057646(损失 25.0→0.003323),lr=0.01 收敛慢而 lr=1.1 发散。",
            expected=dict(
                grad_matches_fd=True,
                closed_form_match=True,
                good_lr_monotone=True,
                slow_lr_higher_loss=True,
                large_lr_diverges=True,
            ),
            actual=dict(
                grad_matches_fd=(grad_err < 1e-8),
                closed_form_match=(abs(w_good[-1] - exact_w20) < 1e-12),
                good_lr_monotone=monotone_dec,
                slow_lr_higher_loss=(l_good[-1] < l_slow[-1] < l_good[0]),
                large_lr_diverges=(l_div[-1] > l_good[0]),
            ),
            measurements=dict(
                init_loss=round(l_good[0], 4),
                lr01_final_w=round(w_good[-1], 6),
                lr01_final_loss=round(l_good[-1], 6),
                lr001_final_w=round(w_slow[-1], 4),
                lr001_final_loss=round(l_slow[-1], 4),
                lr11_final_loss=round(l_div[-1], 2),
            ),
            passed=c3_ok,
        )
    )

    # 4. 2D multivariate gradient descent on L(w1, w2) = (w1 - 2)^2 + 3*(w2 + 1)^2
    def loss_2d(w: np.ndarray) -> float:
        return float((w[0] - 2.0) ** 2 + 3.0 * (w[1] + 1.0) ** 2)

    def grad_2d(w: np.ndarray) -> np.ndarray:
        return np.array([2.0 * (w[0] - 2.0), 6.0 * (w[1] + 1.0)])

    w_init = np.array([-3.0, 4.0])
    fd_2d = np.array(
        [
            (loss_2d(w_init + np.array([eps, 0.0])) - loss_2d(w_init - np.array([eps, 0.0]))) / (2.0 * eps),
            (loss_2d(w_init + np.array([0.0, eps])) - loss_2d(w_init - np.array([0.0, eps]))) / (2.0 * eps),
        ]
    )
    fd_2d_err = float(np.max(np.abs(fd_2d - grad_2d(w_init))))

    w_cur = w_init.copy()
    init_l2d = loss_2d(w_cur)
    for _ in range(40):
        w_cur = w_cur - 0.1 * grad_2d(w_cur)
    final_l2d = loss_2d(w_cur)
    dist_opt = float(np.linalg.norm(w_cur - np.array([2.0, -1.0])))

    c4_ok = fd_2d_err < 1e-7 and dist_opt < 1e-3 and final_l2d < 1e-6
    cases.append(
        dict(
            name="multivariate_gradient_descent_2d",
            inputs=dict(start_w=[-3.0, 4.0], optimum=[2.0, -1.0], lr=0.1, iterations=40),
            prerequisites="二维凸函数 L(w1,w2)=(w1-2)²+3(w2+1)² 的偏导向量 ∇L=[2(w1-2), 6(w2+1)]。",
            action="核对偏导向量与数值有限差分一致,沿负梯度 -∇L 更新 40 步收敛至最优点 (2, -1)。",
            expected=dict(partial_grad_matches_fd=True, converged_within_1e3=True, final_loss_lt_1e6=True),
            actual=dict(
                partial_grad_matches_fd=(fd_2d_err < 1e-7),
                converged_within_1e3=(dist_opt < 1e-3),
                final_loss_lt_1e6=(final_l2d < 1e-6),
            ),
            measurements=dict(
                init_loss=round(init_l2d, 4),
                final_w=[round(float(w_cur[0]), 6), round(float(w_cur[1]), 6)],
                final_loss=round(final_l2d, 8),
                dist_to_optimum=round(dist_opt, 6),
            ),
            passed=c4_ok,
        )
    )

    payload = dict(
        version=platform.python_version(),
        system=platform.system(),
        cases=cases,
    )
    print(json.dumps(payload, ensure_ascii=False))


if __name__ == "__main__":
    main()
本例需在 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-loss-function-and-gradient-lab/explore-loss-function-and-gradient.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-loss-function-and-gradient.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章) · 含当前章节或实例 · mbskycom202612a482.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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