蓝色天空.知识 · 实践 · 创造
我的收藏
AI 数学基础 教程目录 54章
课程介绍
AI 数学基础 / LEARN BY DOING

手写梯度下降拟合一条直线

用均方误差拟合带噪声样本,逐步核对梯度、损失与最小二乘结果。

学完这一章,你能够

  • 用均方误差拟合带噪声样本,逐步核对梯度、损失与最小二乘结果。

先定义拟合目标

给定若干点 (xᵢ,yᵢ),模型用 wxᵢ+b 预测 yᵢ。均方误差衡量竖直残差的平方平均;斜率 w 和截距 b 可从任意初始点开始逐步调整。数据含噪时,最小二乘直线通常只让总体误差最小,各点仍有残差。给定模型、数据和学习率后才能判断是否收敛。

从同一组参数求两项梯度

令 rᵢ = wxᵢ+b−yᵢ,则 L=(∑rᵢ²)/n。斜率偏导为 (2/n)∑rᵢxᵢ,截距偏导为 (2/n)∑rᵢ。两项偏导都用更新前的 w、b 计算,再分别减去学习率乘偏导。日志里的损失和参数使用一致的时点。

复算历史样本并验证收敛条件

采用固定种子的 60 个样本和学习率 0.05。原始生成参数为 (2,1),实际最小二乘解约为 (1.903742,1.038813)。更新 100 次后约为 (1.903744,1.038787),损失约 0.585246。初始 MSE 约 11.913912,第一次更新后约 6.820829。旧输出里的数值与代码定义并不一致。

训练常按预测、损失、求导、更新四步循环。PyTorch 中每次重新计算前要按设计清除累积梯度,然后调用 loss.backward() 与 optimizer.step()。示例将解析偏导、中心差分和自动求导相互核对,并用最小二乘解作终点对照。

从零更新斜率与截距并复查损失

含完整源码 · 103 行
展开查看收起
python
"""Fit a line by hand with simultaneous gradient updates."""
import argparse
import json
import platform

import numpy as np


CASES = []


def record(name, operation, inputs, expected, actual):
    assert actual == expected, (name, expected, actual)
    CASES.append(dict(name=name, operation=operation, inputs=inputs,
                      expected=expected, actual=actual, passed=True))


def objective(design, target, coefficients):
    residual = design @ coefficients - target
    return float(np.mean(residual ** 2))


def gradient(design, target, coefficients):
    residual = design @ coefficients - target
    return 2 * (design.T @ residual) / len(target)


def iterate(design, target, rate, steps):
    coefficients = np.zeros(design.shape[1])
    log = [(coefficients.copy(), objective(design, target, coefficients))]
    for _ in range(steps):
        coefficients -= rate * gradient(design, target, coefficients)
        log.append((coefficients.copy(), objective(design, target, coefficients)))
    return log


def main():
    cli = argparse.ArgumentParser()
    cli.add_argument("--torch", action="store_true")
    args = cli.parse_args()
    versions = {"numpy": np.__version__}
    rng = np.random.RandomState(0)
    x = rng.uniform(-3, 3, 60)
    target = 2 * x + 1 + .8 * rng.standard_normal(60)
    design = np.column_stack((x, np.ones_like(x)))
    log = iterate(design, target, .05, 100)
    end, loss = log[-1]
    record("fit_seeded_samples", "apply 100 gradient updates on fixed data",
           {"seed": 0, "rows": 60, "rate": .05, "updates": 100},
           [[1.903744, 1.038787], .585246],
           [np.round(end, 6).tolist(), round(loss, 6)])
    first, first_loss = log[1]
    record("fixed_point_after_step", "read the initial loss and the first updated parameter pair and loss",
           {"start": [0, 0]}, [11.913912, [.528159, .122629], 6.820829],
           [round(log[0][1], 6), np.round(first, 6).tolist(), round(first_loss, 6)])
    point = np.array([.25, -.75])
    perturbation = np.eye(2) * 1e-5
    numerical = np.array([(objective(design, target, point + direction)
                           - objective(design, target, point - direction)) / (2e-5)
                          for direction in perturbation])
    record("analytic_vs_numeric_gradients", "check both analytic derivatives with centered differences",
           point.tolist(), True, bool(np.allclose(gradient(design, target, point), numerical)))
    solution, _, rank, _ = np.linalg.lstsq(design, target, rcond=None)
    record("compare_least_squares", "solve by least squares and compare reduction after 100 updates",
           {"design_columns": 2}, [[1.903742, 1.038813], 2, True],
           [np.round(solution, 6).tolist(), int(rank), bool(np.max(np.abs(end - solution)) < 3e-5)])
    record("loss_at_every_step", "check the loss recorded with its simultaneous parameter update",
           {"records": 101}, [101, True, True], [len(log),
              all(loss0 >= loss1 for (_, loss0), (_, loss1) in zip(log, log[1:])),
              all(objective(design, target, coefficients) == loss_i for coefficients, loss_i in log)])
    high = iterate(design, target, .7, 10)
    upper_bound = 2 / np.linalg.eigvalsh(2 * design.T @ design / len(target))[-1]
    record("rate_can_diverge", "compare the rate with the Hessian stability bound and observe growth",
           {"rate": .7, "updates": 10}, [True, True],
           [bool(.7 > upper_bound), high[-1][1] > high[0][1]])
    degenerate = np.column_stack((np.ones(4), np.ones(4)))
    best, _, rank_1, _ = np.linalg.lstsq(degenerate, np.array([2., 2., 2., 2.]), rcond=None)
    record("constant_feature_rank_deficiency", "fit constant x and check multiple minimizers",
           {"x": [1, 1, 1, 1], "y": 2}, [1, [1., 1.], True],
           [int(rank_1), np.round(best, 6).tolist(), np.array_equal(degenerate @ [0., 2.], degenerate @ [2., 0.])])
    if args.torch:
        import torch
        versions["torch"] = torch.__version__
        features = torch.from_numpy(design)
        labels = torch.from_numpy(target)
        coefficients = torch.zeros(2, dtype=torch.float64, requires_grad=True)
        optimizer = torch.optim.SGD([coefficients], lr=.05)
        torch_matches = []
        for iteration in range(3):
            optimizer.zero_grad()
            loss_value = (features @ coefficients - labels).square().mean()
            loss_value.backward()
            optimizer.step()
            torch_matches.append(np.allclose(coefficients.detach().numpy(), log[iteration + 1][0]))
        record("torch_matches_manual_updates", "compare PyTorch SGD updates with NumPy",
               {"rounds": 3, "rate": .05}, [True, True, True], list(map(bool, torch_matches)))
    print(json.dumps(dict(version=platform.python_version(), library_versions=versions, cases=CASES)))


if __name__ == "__main__":
    main()

100 次更新后斜率约 1.903744、截距约 1.038787,MSE 约 0.585246。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

复跑实验

解压后按 README 运行自编程序。

下载本章实验包 (mbskycom202612a33.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:AI 数学基础

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

下载课程关联工程包:AI 数学基础

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

常见错误与边界检查

  • 系数学习率应结合数据尺度和损失曲率。
  • 记录每条曲线是更新前还是更新后计算。

技术规范与官方资料

练习与参考解答

查看参考解答

有限样本里的误差项不必恰好与 x 正交。最小二乘解由这批观测决定。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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