"""Train a tiny residual classifier and measure pixel-derived boxes and masks."""
from base64 import b64encode
import json
from io import BytesIO
from PIL import Image, ImageDraw
import torch
from torch import nn
from torch.nn import functional as F
from lab_tools import run_exercise
class Residual(nn.Module):
def __init__(self, in_channels, out_channels, stride):
super().__init__()
self.branch=nn.Sequential(
nn.Conv2d(in_channels,out_channels,3,stride=stride,padding=1,bias=False),
nn.BatchNorm2d(out_channels),nn.ReLU(),
nn.Conv2d(out_channels,out_channels,3,padding=1,bias=False),
nn.BatchNorm2d(out_channels),
)
self.shortcut=(nn.Identity() if in_channels==out_channels and stride==1
else nn.Conv2d(in_channels,out_channels,1,stride=stride,bias=False))
def forward(self,x):
return F.relu(self.branch(x)+self.shortcut(x))
def dataset(seed,size):
g=torch.Generator().manual_seed(seed)
images=torch.randn((size,1,12,12),generator=g)*.06
labels=torch.arange(size)%2
starts=torch.randint(1,8,(size,2),generator=g)
for i,(label,(row,col)) in enumerate(zip(labels.tolist(),starts.tolist(),strict=True)):
if label==0:
images[i,0,row:row+4,col]=1
else:
images[i,0,row,col:col+4]=1
order=torch.randperm(size,generator=g)
return images[order],labels[order]
def train_classifier(checks):
torch.manual_seed(310)
identity=Residual(4,4,1)
projection=Residual(4,8,2)
sample=torch.zeros(2,4,12,12)
checks.expect("cv_residual",list(sample.shape),"Exercise identity and projected residual paths",
[True,[2,4,12,12],[2,8,6,6]],
[isinstance(identity.shortcut,nn.Identity),list(identity(sample).shape),list(projection(sample).shape)])
model=nn.Sequential(nn.Conv2d(1,4,3,padding=1),nn.ReLU(),identity,projection,
nn.AdaptiveAvgPool2d(1),nn.Flatten(),nn.Linear(8,2))
train_x,train_y=dataset(417,192)
val_x,val_y=dataset(540,64)
opt=torch.optim.AdamW(model.parameters(),lr=.012)
model.eval()
with torch.inference_mode():
baseline=float(F.cross_entropy(model(val_x),val_y))
for _ in range(9):
model.train()
for x,y in zip(train_x.split(24),train_y.split(24),strict=True):
opt.zero_grad(set_to_none=True)
F.cross_entropy(model(x),y).backward()
opt.step()
model.eval()
with torch.inference_mode():
logits=model(val_x)
loss=float(F.cross_entropy(logits,val_y))
hits=int((logits.argmax(-1)==val_y).sum())
checks.expect("cv_trained_classifier",[[417,192],[540,64],9,24],
"Learn orientation from synthetic lines and evaluate held-out examples",
[[64,2],True,True],[list(logits.shape),loss<baseline*.65,hits>=60])
checks.rows[-1]["report"]={"baseline_loss":round(baseline,5),"loss":round(loss,5),"hits":hits,"total":64}
return model
class MiniViT(nn.Module):
def __init__(self):
super().__init__()
self.patch=nn.Conv2d(1,8,4,stride=4)
self.cls=nn.Parameter(torch.zeros(1,1,8))
self.positions=nn.Parameter(torch.randn(1,5,8)*.03)
self.norm=nn.LayerNorm(8)
self.attention=nn.MultiheadAttention(8,2,batch_first=True)
self.feedforward=nn.Sequential(nn.LayerNorm(8),nn.Linear(8,16),nn.GELU(),nn.Linear(16,8))
self.classify=nn.Linear(8,3)
def forward(self,image):
patches=self.patch(image).flatten(2).transpose(1,2)
tokens=torch.cat((self.cls.expand(image.shape[0],-1,-1),patches),dim=1)+self.positions
x=self.norm(tokens)
values,weights=self.attention(x,x,x,average_attn_weights=False)
tokens=tokens+values
tokens=tokens+self.feedforward(tokens)
return self.classify(tokens[:,0]),weights
def transformer(checks):
torch.manual_seed(703)
model=MiniViT()
image=torch.arange(128,dtype=torch.float32).reshape(2,1,8,8)/127
logits,weights=model(image)
changed=image.clone()
changed[0,0,0,0]+=2
next_logits,_=model(changed)
loss=F.cross_entropy(logits,torch.tensor([0,2]))
loss.backward()
checks.expect("cv_vit_attention",[[2,1,8,8],4,2,3],
"Observe four patches plus class token, per-head attention, changed input and backward flow",
[[2,3],[2,2,5,5],True,True,True,True],
[list(logits.shape),list(weights.shape),bool(torch.allclose(weights.sum(-1),torch.ones_like(weights[...,0]))),
not torch.allclose(logits[0],next_logits[0]),bool(model.patch.weight.grad.abs().sum()>0),
bool(model.positions.grad.abs().sum()>0)])
def components(mask):
remaining={(x,y) for y,x in torch.nonzero(mask).tolist()}
groups=[]
while remaining:
first=min(remaining)
remaining.remove(first)
group={first}
todo=[first]
while todo:
x,y=todo.pop()
for point in ((x-1,y),(x+1,y),(x,y-1),(x,y+1)):
if point in remaining:
remaining.remove(point)
group.add(point)
todo.append(point)
groups.append(group)
return groups
def bounds(group):
x,y=zip(*group,strict=True)
return [min(x),min(y),max(x)+1,max(y)+1]
def prompt_mask(groups,*,points=(),box=None):
mask=set()
for group in groups:
if any((x,y) in group for x,y,label in points if label==0):
continue
seeded=any((x,y) in group for x,y,label in points if label==1)
inside=box is not None and any(box[0]<=x<box[2] and box[1]<=y<box[3] for x,y in group)
if seeded or inside:
mask.update(group)
return mask
def build_report(checks,model,folder):
values=torch.zeros(12,20,dtype=torch.uint8)
values[2:6,3]=235
values[7:10,12:18]=190
groups=components(values>=128)
boxes=[bounds(group) for group in groups]
altered=values.clone()
altered[:,12:]=0
checks.expect("cv_pixel_boxes",[[20,12],128],"Compute half-open pixel boxes and verify the second vanishes when its pixels are erased",
[[[3,2,4,6],[12,7,18,10]],[[3,2,4,6]]],
[boxes,[bounds(group) for group in components(altered>=128)]])
positive=prompt_mask(groups,points=[(3,4,1)])
window=prompt_mask(groups,box=[11,6,19,11])
combined=prompt_mask(groups,points=[(3,4,1),(13,8,1),(3,3,0)])
checks.expect("cv_prompt_masks",["foreground point","box","two foreground points and one exclusion"],
"Find connected foreground pixels by point or box and exclude a selected component",
[4,18,18,True],[len(positive),len(window),len(combined),combined==window])
crop=values[0:12,0:12].float().unsqueeze(0).unsqueeze(0)/235
with torch.inference_mode():
classified=int(model(crop).argmax(-1))
report={"crop_class":classified,"boxes_xyxy":boxes,"mask_pixels":[len(positive),len(window)]}
payload=folder/"observation.json"
payload.write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding="utf8")
preview=Image.frombytes("L",(20,12),bytes(values.flatten().tolist())).convert("RGB")
preview=preview.resize((320,192),Image.Resampling.NEAREST)
overlay=preview.copy()
draw=ImageDraw.Draw(overlay)
for x,y in window:
draw.rectangle((x*16,y*16,(x+1)*16-1,(y+1)*16-1),fill="#ecb84a")
for x0,y0,x1,y1 in boxes:
draw.rectangle((x0*16,y0*16,x1*16-1,y1*16-1),outline="#39dbd4",width=2)
result=folder/"annotated.png"
overlay.save(result)
buffer=BytesIO()
preview.save(buffer,format="PNG")
with Image.open(result) as observed:
pixels=[observed.getpixel((px,py)) for px,py in ((0,0),(220,130),(48,32))]
saved=json.loads(payload.read_text(encoding="utf8"))
checks.expect("cv_pipeline_files",["generated scene","trained line classifier","JSON","PNG"],
"Run classification, save coordinates and overlay, then reopen both files",
[0,boxes,[[0,0,0],[236,184,74],[57,219,212]]],
[saved["crop_class"],saved["boxes_xyxy"],[list(x) for x in pixels]])
checks.rows[-1]["report"]={**report,"overlay_png":b64encode(result.read_bytes()).decode(),
"scene_png":b64encode(buffer.getvalue()).decode()}
def exercise(checks,folder):
torch.set_num_threads(1)
model=train_classifier(checks)
transformer(checks)
build_report(checks,model,folder)
if __name__=="__main__":
run_exercise(exercise)
本例需在 CPython 3.12.14、PyTorch 2.10.0+cpu、Pillow 13.0.0,固定种子、CPU 单线程和本站合成样本。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:CPython 3.12.14、PyTorch 2.10.0+cpu、Pillow 13.0.0,固定种子、CPU 单线程和本站合成样本。
入口文件:projects/ai-computer-vision/vision_lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
vision_lab.py,或下载右侧课程工程包。 - 确认本地已准备 CPython 3.12.14、PyTorch 2.10.0+cpu、Pillow 13.0.0,固定种子、CPU 单线程和本站合成样本。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联30章) · 含当前章节或实例 · mbskycom202612a5.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a6.zip