梯度下降法
实际更新线性回归参数,比较步长、批量与学习率调度。
学完这一章,你能够
- 实际更新线性回归参数,比较步长、批量与学习率调度。
跟踪一次真实更新
每步先用旧参数做预测,再用预测和标签计算损失,再求梯度,最后同时更新参数 θ新=θ旧−η∇J。把步行下坡看成局部比喻,每走一步都要在新的位置重新测坡度。
以 x=[0,1,2,3]、y=3x+2 为例。初始权重和截距为零,MSE 是 53.5,梯度为 (−27,−13)。学习率 0.1 的第一次更新产生 (2.7,1.3),损失降到 1.435。图表逐步计算,横轴的零步表示尚未更新。
历史样本用旧 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 | 损失超过初值的百万倍,超出此二次目标的稳定区间。 |
从回归误差推导并运行梯度更新
展开查看收起
"""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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
复跑实验
解压后按 README 运行自编程序。
本章附件与实例包
常见错误与边界检查
- 区分更新前与更新后的损失。
- 学习率选择要结合目标曲率与数据尺度。
技术规范与官方资料
练习与参考解答
查看参考解答
先根据新的曲率或实际损失检查步长。