PyTorch 第一个神经网络
以两套真实 CPU 训练观察概率、损失、独立测试与分类边界。
学完这一章,你能够
- 以两套真实 CPU 训练观察概率、损失、独立测试与分类边界。
先跑通十个样本的二分类网络
先用 Sequential 串起线性层、ReLU、输出线性层和 Sigmoid。该历史练习用每行一个概率、MSE 和 SGD 来展示训练步骤。记录损失后,由 backward 和 step 修改参数。
输入尺寸 [10,10] 表示十个样本,每行十个特征。五个隐藏单元把数据送到一个输出单元,标签保持 [10,1]。模型输出是连续概率,阈值判断才给出 0 或 1。本站从前两个特征导出固定标签。
从实际曲线读训练进展
训练在每轮计算一批预测,清梯度后反传,并按 SGD 的学习率更新。本站独立重写的 50 步 MSE 从约 0.2577 降到 0.1971。曲线上的损失取本步更新前的值,最后的预测则在所有更新后计算。
左图显示每轮的 MSE,右图逐样本对照训练标签和概率。标签和概率复用同一顺序,便于看到阈值 0.5 下仍可能有错分。十条训练样本的图用于理解流程,泛化需独立数据。

构造二维圆形标签并分开数据
二维例在固定方形范围生成点。圆形标签按 x²+y²<r² 计算,反映位置中的非线性关系。本站选择 r=0.85,分出 512 点训练和 256 点测试。
散点图按实际标签涂色,训练分布由采样决定。边界上和圆外属于类别 0,圆内属于类别 1。切分后保留各点顺序和标签,以方便核对后续结果。

用 logits 训练并核对留出集
前馈模型依次做线性变换和 ReLU,最后返回一个 logit。历史路径使用 Sigmoid 加 BCELoss,本站训练用 BCEWithLogitsLoss,预测时再取 Sigmoid。两种表示下的留出损失也做数值对照。使用带动量的 SGD 训练 220 步,256 条留出样本实测正确率 98.05%。
画出计算得来的决策边界
在同一坐标系上建 101×101 的网格,每个坐标对都经过训练后的模型。用概率 0.5 等高线划出预测区域,同时叠加留出点的真实标签。网格的 x、y 坐标与绘图轴保持对应。
完整脚本同时生成损失、训练数据以及决策边界图,另输出留出交叉熵和混淆计数。固定种子只保证本环境能复验这些样本和参数。改变数据、超参数或运行平台后,应重新检查结果。

训练概率模型与圆形分类器并复验三张图
"""Train two small binary classifiers and draw their observed training results."""
import argparse
from hashlib import sha256
import json
from pathlib import Path
import platform
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import torch
from torch import nn
def report(cases,name,inputs,conditions,action,expected,actual):
assert expected == actual,(name,expected,actual)
cases.append(dict(name=name,inputs=inputs,prerequisites=conditions,action=action,
expected=expected,actual=actual,passed=True))
def fit(model, features, labels, loss_function, optimizer, epochs):
model.train()
values = []
for _ in range(epochs):
optimizer.zero_grad(set_to_none=True)
loss = loss_function(model(features),labels)
values.append(loss.item())
loss.backward()
optimizer.step()
return values
def small_binary(cases):
rng = torch.Generator().manual_seed(102)
data = torch.randn((10,10),generator=rng)
labels = (data[:, :1] + data[:, 1:2] > 0).float()
model = nn.Sequential(nn.Linear(10,5),nn.ReLU(),nn.Linear(5,1),nn.Sigmoid())
before = model[0].weight.detach().clone()
optimizer = torch.optim.SGD(model.parameters(),lr=0.08)
initial = model(data)
losses = fit(model,data,labels,nn.MSELoss(),optimizer,50)
model.eval()
with torch.no_grad():
predictions = model(data)
report(cases,"small_shapes_and_activation",[10,5,1,10],
"Fixed CPU samples; label has one float per row",
"Run forward and check two linear layers and final sigmoid range",
[[10,10],[10,1],[5,10],[1,5],[10,1],True],
[list(data.shape),list(labels.shape),list(model[0].weight.shape),list(model[2].weight.shape),
list(initial.shape),bool(((predictions>0)&(predictions<1)).all())])
report(cases,"mse_sgd_fifty",{"rows":10,"epochs":50,"lr":0.08},
"MSE on probabilities; separate SGD state",
"Check fifty evaluations and weight update plus lower final training loss",
[50,True,True,True],
[len(losses),not torch.equal(before,model[0].weight),losses[-1]<losses[0],
abs(losses[0]-nn.functional.mse_loss(initial,labels).item())<1e-6])
cases[-1]["measurements"] = dict(first=losses[0],last=losses[-1],targets=labels[:,0].tolist(),
probability=predictions[:,0].tolist())
return losses,labels[:,0].tolist(),predictions[:,0].tolist()
def circle_classifier(cases):
rng = torch.Generator().manual_seed(890)
features = 2.2*torch.rand((768,2),generator=rng)-1.1
binary = (features.square().sum(dim=1,keepdim=True)<0.85**2).float()
test_quad = torch.tensor([[0.,0.],[0.85,0.],[1.1,0.],[-0.2,0.2]])
test_labels = (test_quad.square().sum(dim=1)<0.85**2).int()
report(cases,"radial_labels",test_quad.tolist(),"Source goal recreated on a fixed radius-0.85 disk",
"Apply a strict less-than rule and check the balanced generated shapes",
[[1,0,0,1],[768,2],[768,1],True],
[test_labels.tolist(),list(features.shape),list(binary.shape),0.3<binary.mean().item()<0.65])
model = nn.Sequential(nn.Linear(2,16),nn.ReLU(),nn.Linear(16,12),nn.ReLU(),nn.Linear(12,1))
optimizer = torch.optim.SGD(model.parameters(),lr=0.12,momentum=0.9)
criterion = nn.BCEWithLogitsLoss()
training = 512
losses = fit(model,features[:training],binary[:training],criterion,optimizer,220)
model.eval()
with torch.no_grad():
score = model(features[training:])
predicted = (score.sigmoid()>=0.5)
target = binary[training:].bool()
accuracy = (predicted==target).float().mean().item()
errors = criterion(score,binary[training:]).item()
confusion = [int((predicted&target).sum()),int((predicted&~target).sum()),
int((~predicted&target).sum()),int((~predicted&~target).sum())]
equivalent_loss = nn.BCELoss()(score.sigmoid(),binary[training:]).item()
report(cases,"logits_bce_training",{"train":512,"test":256,"epochs":220},
"Fixed seed, independent heldout split, SGD with momentum, raw logits for stable BCE",
"Train the model and compare heldout BCE computed in logit and probability space",
[220,True,True,True,256],
[len(losses),losses[-1]<losses[0]*0.4,accuracy>=0.90,abs(errors-equivalent_loss)<1e-5,sum(confusion)])
cases[-1]["measurements"] = dict(first=losses[0],last=losses[-1],test_bce=errors,
test_accuracy=accuracy,tp_fp_fn_tn=confusion)
axis = torch.linspace(-1.1,1.1,101)
grid_x,grid_y = torch.meshgrid(axis,axis,indexing="xy")
grid = torch.stack((grid_x.reshape(-1),grid_y.reshape(-1)),dim=1)
with torch.no_grad():
probability = model(grid).sigmoid().reshape(grid_x.shape)
probes = model(torch.tensor([[0.,0.],[1.1,1.1]])).sigmoid()[:,0].tolist()
report(cases,"actual_decision_grid",{"extent":[-1.1,1.1],"count":101,"probability_threshold":0.5},
"Each grid cell runs the trained model; horizontal x and vertical y",
"Check grid dimensions, positive center, negative corner and bracketed contour threshold",
[[101,101],[10201,2],True,True,True],
[list(probability.shape),list(grid.shape),probes[0]>0.5,probes[1]<0.5,
probability.min().item()<0.5<probability.max().item()])
return features,binary,(grid_x,grid_y,probability)
def charts(destination, cases, first, radial):
destination.mkdir(parents=True,exist_ok=True)
names = ("small-training.png","circle-inputs.png","circle-boundary.png")
figure,axes = plt.subplots(1,2,figsize=(9,3.5),layout="constrained")
history,labels,predicted = first
line, = axes[0].plot(range(1,len(history)+1),history,color="#14675e")
axes[0].set(xlabel="Epoch",ylabel="Training MSE")
targets, = axes[1].plot(range(1,len(labels)+1),labels,"o-",label="Target",color="#304e75")
probabilities, = axes[1].plot(range(1,len(labels)+1),predicted,"x--",label="Probability",color="#b04d30")
axes[1].set(xlabel="Training row",ylabel="Value",ylim=(-0.08,1.08))
axes[1].legend()
assert list(line.get_ydata())==history and list(targets.get_ydata())==labels
assert list(probabilities.get_ydata())==predicted
figure.savefig(destination/names[0],dpi=120)
plt.close(figure)
features,labels,grid = radial
color = ["#17665d" if value==1 else "#bf5f3e" for value in labels[:512,0].tolist()]
figure,axis=plt.subplots(figsize=(5.2,4.7),layout="constrained")
dots=axis.scatter(features[:512,0],features[:512,1],c=color,s=12,alpha=.65)
axis.set(xlabel="Feature x",ylabel="Feature y",aspect="equal")
assert len(dots.get_offsets())==512
figure.savefig(destination/names[1],dpi=120)
plt.close(figure)
xx,yy,z = (x.numpy() for x in grid)
figure,axis=plt.subplots(figsize=(5.2,4.7),layout="constrained")
fill=axis.contourf(xx,yy,z,levels=[0.,.5,1.],colors=["#fae1d2","#b8e0d7"],alpha=.7)
boundary=axis.contour(xx,yy,z,levels=[.5],colors=["#124e47"])
test_count=features.shape[0]-512
test_color=["#17665d" if value==1 else "#bf5f3e" for value in labels[512:,0].tolist()]
check=axis.scatter(features[512:,0],features[512:,1],c=test_color,s=10,alpha=.6)
axis.set(xlabel="Feature x",ylabel="Feature y",aspect="equal")
assert len(fill.levels)==3 and list(boundary.levels)==[.5] and any(len(x)>1 for x in boundary.allsegs[0])
figure.savefig(destination/names[2],dpi=120)
plt.close(figure)
report(cases,"matplotlib_semantic_artists",{"loss_count":len(history),"training_points":512,"test_points":test_count},
"Matplotlib Agg renders actual stored arrays from the two experiments",
"Inspect series, groups and populated decision contour before writing PNG",
[50,10,10,512,256,0.5],
[len(history),len(targets.get_ydata()),len(probabilities.get_ydata()),
len(dots.get_offsets()),len(check.get_offsets()),float(boundary.levels[0])])
return {name:sha256((destination/name).read_bytes()).hexdigest() for name in names}
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--figures",type=Path)
args = parser.parse_args()
torch.set_num_threads(1)
torch.manual_seed(145)
observations = []
first=small_binary(observations)
radial=circle_classifier(observations)
artifacts=charts(args.figures,observations,first,radial) if args.figures else {}
print(json.dumps(dict(version=platform.python_version(),torch=torch.__version__,system=platform.system(),
matplotlib=matplotlib.__version__,cases=observations,figures=artifacts)))
if __name__=="__main__":
main()
- 50 步 MSE 下降。圆形模型使用预测概率实际生成边界,在固定留出集上核对分类准确率。
所需环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。
当前源码 SHA256:82b6be316fe33c23d098ce16228e85c0f59af41a8dea7cf7c40743710b79552b
本地运行
解压后按 README 选择对应构建并运行脚本。
所需环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。
ZIP SHA256:2c2d8e9c2848343b4886a9b95845836da28ce74e6577e346823716b266ade676
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
当输出层只给一个 logit 时,训练和推理分别怎样用它?
展开参考解答
训练交给 BCEWithLogitsLoss。推理可用 Sigmoid 取得概率,再按所选阈值判别。