"""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()
本例需在 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。
入口文件:projects/pytorch-first-neural-network-lab/train-two-binary-models.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
train-two-binary-models.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a409.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a420.zip