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

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

PYTHONWindows、Python 3.12.14。numpy 2.5.4;torch 2.10.0+cpu。descent-lab.py
descent-lab.py108 行
"""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()
本例需在 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-lab/descent-lab.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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