蓝色天空网mbsky.com · 知识 · 实践 · 创造AI 数学基础 · 本地阅读预览
教程 / AI / 智能开发 / AI 数学基础

梯度下降法

实际更新线性回归参数,比较步长、批量与学习率调度。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

跟踪一次真实更新

每步先用旧参数做预测,再用预测和标签计算损失,再求梯度,最后同时更新参数 θ新=θ旧−η∇J。把步行下坡看成局部比喻,每走一步都要在新的位置重新测坡度。

以 x=[0,1,2,3]、y=3x+2 为例。初始权重和截距为零,MSE 是 53.5,梯度为 (−27,−13)。学习率 0.1 的第一次更新产生 (2.7,1.3),损失降到 1.435。图表逐步计算,横轴的零步表示尚未更新。

学习率零点一时,四十步后的回归损失已很低。
本站完整回归轨迹,以学习率 0.10 更新 40 步后,损失约为 0.000639。

历史样本用旧 RandomState(42) 在 [0,10] 生成 100 个含噪观测。按这些条件复算 200 步,参数约为 (3.0928,1.2209),初始 MSE 约 363.1700,最后一步更新后约 3.3073。若先记录损失再更新,记录末项约 3.3078,对应的是更新之前的参数。

控制步长与训练流程

常见 PyTorch 循环先清累积梯度,再调用模型得到预测,按目标函数算 loss,调用 loss.backward(),最后 optimizer.step()。全量梯度和普通 SGD 的更新式可对照验证,带调度或其他优化器时参数步按各自规则。

若二次目标 Hessian 正定,固定学习率在 0<η<2/λ最大 时让各误差方向收缩。本例 η=0.01 进展较慢,0.1 收敛明显,0.3 发散。StepLR 在指定间隔衰减,余弦调度按曲线变步长,warmup 先增大学习率。GPT-3 论文的训练配置记录了线性 warmup 与余弦衰减。

全量梯度读同批全部训练数据。单样本随机更新成本较低、方差通常更高。小批量 SGD 可用向量化处理来平衡吞吐和方差。在同一点,等大小批的梯度平均等于全量梯度。逐批已经更新参数时,后一批的梯度在不同位置计算。

梯度接近零只能表明一阶变化较小,极小、极大与鞍点仍需分开判断。在 x²−y² 的原点,普通梯度法和 Adam 都没有信号推动初始点离开。实际逃离行为与扰动、噪声和更新历史有关。

同一目标的三种步长

来源情形实验步长40 步后的观察
较慢0.01约 0.101128,仍可继续下降。
稳定0.10约 0.000639,这组参数及特征尺度下有效。
发散0.30损失超过初值的百万倍,超出此二次目标的稳定区间。

从回归误差推导并运行梯度更新

python · 阅读源码
"""Compute regression updates, learning-rate branches, and scheduler steps."""
import argparse
import json
import platform

import numpy as np


def fit(rows,target,learning_rate,iterations):
    weights=np.zeros(rows.shape[1])
    history=[]
    for _ in range(iterations):
        error=rows@weights-target
        history.append(float(np.mean(error**2)))
        weights-=learning_rate*(2*rows.T@error/len(rows))
    history.append(float(np.mean((rows@weights-target)**2)))
    return weights,history


def main():
    parser=argparse.ArgumentParser()
    parser.add_argument("--torch",action="store_true")
    args=parser.parse_args()
    cases=[]
    versions={"numpy":np.__version__}

    def check(name,inputs,expected,actual,operation):
        assert expected==actual,(name,expected,actual)
        cases.append(dict(name=name,input=inputs,expected=expected,actual=actual,operation=operation,passed=True))

    rows=np.column_stack([np.arange(4,dtype=float),np.ones(4)])
    target=3*rows[:,0]+2
    common={"x":rows[:,0].tolist(),"y":target.tolist(),"steps":40}
    slow,normal,large=[fit(rows,target,eta,40) for eta in (.01,.1,.3)]
    check("step_small",{**common,"eta":.01},True,5>slow[1][-1]>normal[1][-1],"run and measure residual loss under the smaller step")
    check("step_working",{**common,"eta":.1},[53.5,True,True],
          [normal[1][0],all(a>=b for a,b in zip(normal[1],normal[1][1:])),normal[1][-1]<.025],
          "run full-batch updates and measure a stable loss trace")
    check("step_diverges",{**common,"eta":.3},True,large[1][-1]>large[1][0]*1e6,
          "measure growth when the step exceeds the stable quadratic range")
    for case,result in zip(cases,(slow,normal,large),strict=True):
        case["losses_at_initial_first_final"]=[result[1][0],result[1][1],result[1][-1]]
    limit=2/np.linalg.eigvalsh(2*rows.T@rows/len(rows))[-1]
    check("quadratic_spectral_rate_bound",common,[True,True],
          [.1<float(limit),.3>float(limit)],"derive the stable interval for the convex quadratic")
    old_x=np.linspace(0,10,100)
    old_rows=np.column_stack([old_x,np.ones(100)])
    old_target=3*old_x+2+np.random.RandomState(42).normal(0,2,100)
    weights,trace=fit(old_rows,old_target,.01,200)
    least_squares=np.linalg.lstsq(old_rows,old_target,rcond=None)[0]
    check("legacy_regression_recomputed",{"seed":42,"steps":200,"eta":.01},
          [True,True,True],[trace[-1]<trace[0],trace[-1]!=trace[-2],
                           trace[-1]>float(np.mean((old_rows@least_squares-old_target)**2))],
          "reproduce the historical seed, then distinguish pre-update and post-update loss")
    cases[-1]["observed_parameters"]=weights.tolist()
    cases[-1]["observed_losses"]=[trace[0],trace[-2],trace[-1]]
    residual=-target
    gradient_rows=2*rows*residual[:,None]
    check("batch_gradients",common,[-27.,-13.,True],
          [*gradient_rows.mean(axis=0).tolist(),
           bool(np.allclose(np.mean([gradient_rows[:2].mean(axis=0),gradient_rows[2:].mean(axis=0)],axis=0),gradient_rows.mean(axis=0)))],
          "compare full gradient with two equal-sized mini-batch gradients at the same weights")

    if args.torch:
        import torch
        versions["torch"]=torch.__version__
        x=torch.tensor(rows,dtype=torch.float64)
        y=torch.tensor(target,dtype=torch.float64)
        parameters=torch.nn.Parameter(torch.zeros(2,dtype=torch.float64))
        model=torch.optim.SGD([parameters],lr=.1)
        for _ in range(40):
            model.zero_grad(set_to_none=True)
            loss=(x@parameters-y).square().mean()
            loss.backward()
            model.step()
        check("torch_training_matches_numpy",common,True,bool(np.allclose(parameters.detach().tolist(),normal[0])),
              "run full-batch SGD and compare the fitted weight and bias")
        p=torch.nn.Parameter(torch.zeros(2,dtype=torch.float64))
        adam=torch.optim.Adam([p],lr=.2)
        adam.zero_grad(set_to_none=True)
        (p[0]**2-p[1]**2).backward()
        adam.step()
        check("adam_can_stay_at_saddle",[0,0],[0,0],p.detach().tolist(),
              "run Adam from an exact stationary saddle")
        rates=[]
        for scheduler in ("step","cosine"):
            opt=torch.optim.SGD([p],lr=.1)
            driver=(torch.optim.lr_scheduler.StepLR(opt,step_size=2,gamma=.5) if scheduler=="step"
                else torch.optim.lr_scheduler.CosineAnnealingLR(opt,T_max=4,eta_min=0))
            history=[opt.param_groups[0]["lr"]]
            for _ in range(4):
                opt.step()
                driver.step()
                history.append(opt.param_groups[0]["lr"])
            rates.append([round(value,6) for value in history])
        check("actual_pytorch_schedules",{"initial":.1,"steps":4},
              [[.1,.1,.05,.05,.025],[.1,.085355,.05,.014645,0.]],rates,
              "run optimizer steps before the StepLR and cosine scheduler updates")
        warmup=[.1*i/4 for i in range(1,5)]
        check("linear_warmup",{"to":.1,"steps":4},[.025,.05,.075,.1],
              [round(x,6) for x in warmup],"compute a short warmup before applying a decay schedule")

    print(json.dumps(dict(version=platform.python_version(),library_versions=versions,cases=cases)))


if __name__=="__main__":
    main()
预期结果 · 待实际运行核验
  • 初始损失 53.5。以 0.1 为学习率,第一次更新后损失为 1.435。
从回归误差推导并运行梯度更新

所需环境:Windows、Python 3.12.14。numpy 2.5.4;torch 2.10.0+cpu。

当前源码 SHA256:8597c3b0c4ec4ab841dd24f876536c66d1367d2880a87fc8df5a6e6a5fa2564f

复跑实验

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

下载梯度下降法实验

所需环境:Windows、Python 3.12.14。numpy 2.5.4;torch 2.10.0+cpu。

ZIP SHA256:dcfd5bf42560f0ab291114acd77ec801e1f4438da82cc69a0942fbcaba15bd57

常见错误与边界

  • 区分更新前与更新后的损失。
  • 学习率选择要结合目标曲率与数据尺度。

练习与解答

一个微调好的步长可直接用于另一个特征尺度吗?

展开参考解答

先根据新的曲率或实际损失检查步长。

规范与官方依据