PyTorch 线性回归
用带噪声的线性数据估计系数,比较三个实际优化过程及独立预测。
学完这一章,你能够
- 用带噪声的线性数据估计系数,比较三个实际优化过程及独立预测。
用权重和截距预测连续量
线性回归用 ŷ = w₁x₁ + w₂x₂ + … + b 预测连续值。各特征 xⱼ 有对应系数 wⱼ,b 是截距。训练目标 y 可以包含噪声,模型输出 ŷ 由输入和参数确定。
本站生成两列特征,真实权重为 [−1.75,0.60],真实截距为 2.50,另加标准差约 0.08 的噪声。固定生成器产生 176 条数据。其中 128 条训练,48 条保留给预测测试。同一环境可检查形状、生成规则和样本顺序。
建立线性层与可验证的损失
继承 nn.Module,构造 nn.Linear(2,1)。模块自动跟踪 [1,2] 权重和 [1] 偏置。本实验明确使用零初始化,forward 返回 [N,1]。参数可用 detach 检查,导出需要共享时要留意存储关系。
对同形目标采用 MSE,即各项平方误差的均值。学习率控制优化更新。SGD、Adam、RMSprop 都从相同初始权重开始,但每种记录自己的学习率和更新状态。收敛速度要依据样本、参数与优化设置比较。
看训练与留出预测的不同读数
训练循环每步清理梯度、前向、求损失、反向,再让优化器更新。实验全批运行 1000 步,每 100 步记录训练 MSE。train 和 eval 切换模块模式,线性层自身在两种模式下给出同值。no_grad 独立控制评估时的梯度记录。
检查拟合后权重和截距,再用独立 48 条样本测预测。本站的 SGD 权重约为 [−1.7572,0.5952],截距约为 2.4981,留出 MSE 约 0.00758。图左为实际训练损失,右侧逐点比较留出目标和预测,斜线表示二者相等。

Adam 的一阶、二阶矩估计与 RMSprop 的梯度平方滑动统计提供不同更新。三个模型的训练目标和划分保持一致。本次选定学习率下的实际变化由曲线表示。
处理形状和数据异常
如果预测为 [N,1]、标签为 [N],直接计算可能广播成 [N,N]。核对同形后,再用 squeeze(-1) 或 unsqueeze(-1) 只调整指定轴。无参数 squeeze 在 N=1 时也会移除批次轴。损失变化不正常时,检查学习率和尺度、缺失或非有限值。本站实测一种大尺度输入发散,过滤异常并改用训练统计后两种学习率表现不同。
是否增加轮次、修改学习率、扩充训练数据或换模型,应以验证数据判断。对真实线性关系,多层结构会增加自由度和调参成本。训练损失仍须与独立样本表现分别观察。
训练中的三个组件
| 组件 | 实际行为 |
|---|---|
| MSELoss | 在形状相同的样本上平方误差取平均,检查是否发生广播。 |
| SGD | 按梯度、学习率及可选动量更新参数。 |
| Adam | 用梯度与梯度平方的矩估计调整各参数的步幅。 |
优化器与可比较条件
| 优化器 | 更新规则 | 条件与观察 |
|---|---|---|
| SGD | 学习率控制步幅,可加动量。 | 本站实测全批线性拟合。性能需按数据规模和配置比较。 |
| Adam | 跟踪一阶和二阶矩估计。 | 随训练目标、数据和超参变化。可与新的同初始权重对比。 |
| RMSprop | 用梯度平方移动平均调节各参数。 | 可用于序列等任务,也实际运行了本站线性回归。 |
拟合系数并检查预测和标签形状
"""Fit a noisy linear relation and check shapes, optimizers and held-out predictions."""
import argparse
from hashlib import sha256
import json
import platform
from pathlib import Path
import warnings
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import torch
from torch import nn
class Regressor(nn.Module):
def __init__(self):
super().__init__()
self.projection=nn.Linear(2,1)
nn.init.zeros_(self.projection.weight)
nn.init.zeros_(self.projection.bias)
def forward(self, data):
return self.projection(data)
def record(cases,name,inputs,conditions,action,expected,actual):
assert actual==expected,(name,expected,actual)
cases.append(dict(name=name,inputs=inputs,prerequisites=conditions,action=action,
expected=expected,actual=actual,passed=True))
def fit(features, labels, kind, rate, steps):
model=Regressor()
optimizer=kind(model.parameters(),lr=rate)
model.train()
start=nn.functional.mse_loss(model(features),labels).item()
history=[]
for index in range(steps):
optimizer.zero_grad(set_to_none=True)
loss=nn.functional.mse_loss(model(features),labels)
if not torch.isfinite(loss):
return model, start, None, history
loss.backward()
optimizer.step()
if (index+1)%100==0:
history.append([index+1,loss.item()])
with torch.no_grad():
end=nn.functional.mse_loss(model(features),labels).item()
return model, start, end, history
def numerical_examples(cases):
torch.set_num_threads(1)
rng=torch.Generator().manual_seed(921)
features=torch.randn((176,2),generator=rng)
truth=torch.tensor([[-1.75],[.6]])
intercept=2.5
noiseless=features@truth+intercept
noise=0.08*torch.randn((176,1),generator=rng)
observed=noiseless+noise
sgd=fit(features[:128],observed[:128],torch.optim.SGD,.05,1000)
adam=fit(features[:128],observed[:128],torch.optim.Adam,.04,1000)
rms=fit(features[:128],observed[:128],torch.optim.RMSprop,.012,1000)
record(cases,"seeded_linear_data",{"seed":921,"rows":176,"noise_scale":0.08},
"Float32 features, true slope [-1.75,0.6] and intercept 2.5",
"Compute [N,1] targets and verify noise and separate data partitions",
[[128,2],[48,2],[176,1],True,True],
[list(features[:128].shape),list(features[128:].shape),list(observed.shape),
bool(torch.allclose(noiseless+noise,observed)),bool(torch.allclose(observed-noiseless,noise,atol=6e-7))])
linear=Regressor()
value=linear(features[:3])
with torch.no_grad():
linear.eval()
evaluations=linear(features[:3])
seen=[list(linear.projection.weight.shape),list(linear.projection.bias.shape),
list(value.shape),bool(torch.equal(value,evaluations)),value.requires_grad,evaluations.requires_grad]
record(cases,"linear_module_shapes",{"features":2,"outputs":1},"Pure Linear has no dropout or batch norm",
"Check parameter shapes and compare train/eval output with gradient tape disabled separately",
[[1,2],[1],[3,1],True,True,False],seen)
verify=[]
summary={}
goal=noiseless[128:]
for name,entry in (("SGD",sgd),("Adam",adam),("RMSprop",rms)):
model,start,end,series=entry
model.eval()
with torch.no_grad():
pred=model(features[128:])
summary[name]=dict(learned_weight=model.projection.weight.detach().tolist()[0],
learned_bias=model.projection.bias.detach().item(),initial_loss=start,final_loss=end,history=series,
holdout_mse=nn.functional.mse_loss(pred,observed[128:]).item())
verify.append([len(series),end<start*0.005,
bool(torch.allclose(model.projection.weight.detach().T,truth,atol=0.06,rtol=0)),
abs(model.projection.bias.detach().item()-intercept)<0.06,
nn.functional.mse_loss(pred,goal).item()<0.01])
assertions=[[10,True,True,True,True]]*3
record(cases,"optimizer_and_holdout",{"train":128,"holdout":48,"steps":1000},
"Three fresh zero-initialized models; recorded optimizer-specific rates",
"Train SGD, Adam and RMSprop separately, recover weights and score held-out points",
assertions,verify)
cases[-1]["measurements"]=summary
aligned=torch.tensor([[1.],[3.],[5.]])
targets=torch.tensor([1.,4.,5.])
vector=aligned.squeeze(-1)
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
wrong=nn.functional.mse_loss(aligned,targets).item()
correct=nn.functional.mse_loss(vector,targets).item()
manual=(vector-targets).square().mean().item()
record(cases,"squeeze_and_broadcast_loss",{"prediction":[[1],[3],[5]],"target":[1,4,5]},
"Torch permits broadcast and issues a warning; one-element batch also tested",
"Compare elementwise MSE, unintended 3x3 broadcast and explicit axes",
[True,True,True,True,[1],[],[3,1]],
[abs(correct-1/3)<1e-6,abs(wrong-17/3)<1e-6,any('broadcast' in str(x.message) for x in caught),
correct==manual,list(aligned[:1].squeeze(-1).shape),list(aligned[:1].squeeze().shape),
list(targets.unsqueeze(-1).shape)])
x=features[:32].clone()
x[:,0]*=500.
x[4,1]=float("nan")
finite=torch.isfinite(x).all(dim=1)
clean=x[finite]
matching=observed[:32][finite]
clean_z=(clean-clean.mean(dim=0))/clean.std(dim=0,unbiased=False)
bad=fit(clean,matching,torch.optim.SGD,.1,100)
tiny=fit(clean_z,matching,torch.optim.SGD,.000001,100)
regular=fit(clean_z,matching,torch.optim.SGD,.08,100)
record(cases,"scale_rate_and_nonfinite_input","Feature 0 rescaled by 500 and one non-finite row",
"Remove the invalid row and estimate mean/scale from the retained training rows",
"Observe numerical failure at high raw scale, then compare tiny and moderate learning rates",
[31,True,True,True,True],
[len(clean),bad[2] is None,tiny[2] > tiny[1]*.99,
regular[2] < regular[1]*.1,bool(torch.allclose(clean_z.mean(0),torch.zeros(2),atol=1e-6))])
with torch.no_grad():
prediction=sgd[0](features[128:]).squeeze(-1).numpy()
return summary,observed[128:,0].numpy(),prediction
def save_plot(path, cases, history, truth, prediction):
path.parent.mkdir(parents=True,exist_ok=True)
fig,axes=plt.subplots(1,2,figsize=(8.6,3.5),layout="constrained")
for name,info in history.items():
sequence=info["history"]
trace,=axes[0].plot([step for step,_ in sequence],[loss for _,loss in sequence],label=name)
assert list(trace.get_ydata())==[loss for _,loss in sequence]
axes[0].set(xlabel="Full-batch step",ylabel="Training MSE",yscale="log")
axes[0].legend()
dots=axes[1].scatter(truth,prediction,s=16,color="#16756b")
boundary=[min(truth.min(),prediction.min()),max(truth.max(),prediction.max())]
axes[1].plot(boundary,boundary,color="#746b76",linewidth=1)
axes[1].set(xlabel="Held-out target",ylabel="SGD prediction",aspect="equal")
assert len(dots.get_offsets())==len(truth)==len(prediction)==48
assert dots.get_offsets()[:,0].tolist()==truth.tolist() and dots.get_offsets()[:,1].tolist()==prediction.tolist()
fig.savefig(path,dpi=125)
plt.close(fig)
record(cases,"observed_regression_plot",[10,48],"Stored optimizer histories and held-out arrays, Matplotlib Agg",
"Check plotted lengths, actual traces and target/prediction correspondence",
[3,48],[len(history),len(dots.get_offsets())])
return sha256(path.read_bytes()).hexdigest()
def main():
parser=argparse.ArgumentParser()
parser.add_argument("--figures",type=Path)
args=parser.parse_args()
cases=[]
history,truth,prediction=numerical_examples(cases)
figures={}
if args.figures:
name="linear-fit-and-holdout.png"
figures[name]=save_plot(args.figures/name,cases,history,truth,prediction)
print(json.dumps(dict(version=platform.python_version(),torch=torch.__version__,system=platform.system(),
matplotlib=matplotlib.__version__,cases=cases,figures=figures)))
if __name__=="__main__":
main()
- 三个独立模型的系数接近固定真值,对照同形 MSE 和意外广播的损失。另验证留出预测。
所需环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。
当前源码 SHA256:7cbb8e00c643f777b1d550c84e8036351e1a67276a463a6cd7d3f1a62fec3f4b
本地运行
解压后按 README 选择对应构建并运行脚本。
所需环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。
ZIP SHA256:82b58a0d414a793a06862d3a648fdfc6eeb1743f37f8279e917aa20076f1379a
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
只有一个样本时,如何保留批次轴去掉末尾长度为 1 的输出轴?
展开参考解答
可以使用 predictions.squeeze(-1),让 [1,1] 成为 [1]。