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

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

PYTHONWindows、Python 3.12.14。numpy 2.5.4;torch 2.10.0+cpu。fit-line-by-gradient.py
fit-line-by-gradient.py103 行
"""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()

本例需在 Windows、Python 3.12.14。numpy 2.5.4;torch 2.10.0+cpu。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、Python 3.12.14。numpy 2.5.4;torch 2.10.0+cpu。

入口文件:projects/ai-math-gradient-descent-fit-lab/fit-line-by-gradient.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 fit-line-by-gradient.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、Python 3.12.14。numpy 2.5.4;torch 2.10.0+cpu。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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