"""Independent PyTorch CPU image-classification lab with offline CIFAR-10 binary archive support."""
import argparse
import hashlib
import json
import platform
import tarfile
import tempfile
from pathlib import Path
import numpy as np
import PIL
from PIL import Image
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader, Dataset
import torchvision
from torchvision import transforms
CLASSES = ("plane", "car", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck")
class Net(nn.Module):
"""Classic 2-conv + 3-fc CIFAR-10 CNN (32x32x3 -> 10 classes)."""
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = torch.flatten(x, 1)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
return self.fc3(x)
class ArrayImageDataset(Dataset):
def __init__(self, images_hwc: np.ndarray, labels: np.ndarray, transform=None):
self.images = images_hwc
self.labels = labels.astype(np.int64)
self.transform = transform
def __len__(self) -> int:
return len(self.labels)
def __getitem__(self, idx: int):
img = Image.fromarray(self.images[idx], mode="RGB")
if self.transform is not None:
img = self.transform(img)
return img, int(self.labels[idx])
def load_cifar10_binary_subset(tar_path: Path, train_per_class: int = 200, test_per_class: int = 50):
def read_bin(raw: bytes):
arr = np.frombuffer(raw, dtype=np.uint8).reshape(-1, 3073)
labels = arr[:, 0]
imgs = arr[:, 1:].reshape(-1, 3, 32, 32).transpose(0, 2, 3, 1)
return imgs, labels
def pick_balanced(imgs, labels, per_class):
picked_x, picked_y = [], []
for cls in range(10):
idx = np.flatnonzero(labels == cls)[:per_class]
picked_x.append(imgs[idx])
picked_y.append(labels[idx])
return np.concatenate(picked_x, axis=0), np.concatenate(picked_y, axis=0)
with tarfile.open(tar_path, "r:gz") as tf:
tr_raw = tf.extractfile("cifar-10-batches-bin/data_batch_1.bin").read()
te_raw = tf.extractfile("cifar-10-batches-bin/test_batch.bin").read()
tr_x, tr_y = read_bin(tr_raw)
te_x, te_y = read_bin(te_raw)
return pick_balanced(tr_x, tr_y, train_per_class), pick_balanced(te_x, te_y, test_per_class)
def make_synthetic_subset(train_per_class: int = 40, test_per_class: int = 10):
rng = np.random.default_rng(2026)
palettes = [
(210, 60, 60), (60, 180, 75), (60, 90, 215), (225, 185, 45), (175, 65, 200),
(55, 195, 205), (235, 125, 50), (140, 140, 140), (225, 110, 165), (110, 160, 60),
]
def build(n_per):
xs, ys = [], []
for cls in range(10):
base = np.array(palettes[cls], dtype=np.float32)
for _ in range(n_per):
img = np.clip(base + rng.normal(0, 28, size=(32, 32, 3)), 0, 255).astype(np.uint8)
xs.append(img)
ys.append(cls)
return np.stack(xs), np.array(ys, dtype=np.int64)
return build(train_per_class), build(test_per_class)
def sha(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def run_cases(cifar_path: Path | None, fig_dir: Path | None):
torch.manual_seed(2026)
cases = []
figures = {}
if cifar_path is not None:
(tr_x, tr_y), (te_x, te_y) = load_cifar10_binary_subset(cifar_path, train_per_class=200, test_per_class=50)
source_mode = "cifar10_binary_subset"
else:
(tr_x, tr_y), (te_x, te_y) = make_synthetic_subset(train_per_class=40, test_per_class=10)
source_mode = "synthetic_rgb_fallback"
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])
train_ds = ArrayImageDataset(tr_x, tr_y, transform=transform)
test_ds = ArrayImageDataset(te_x, te_y, transform=transform)
train_loader = DataLoader(train_ds, batch_size=32, shuffle=True, generator=torch.Generator().manual_seed(42))
test_loader = DataLoader(test_ds, batch_size=32, shuffle=False)
# 1. Data preprocessing & range check [-1, 1]
bx, by = next(iter(train_loader))
min_v, max_v = float(bx.min().item()), float(bx.max().item())
c1_ok = list(bx.shape) == [32, 3, 32, 32] and -1.001 <= min_v <= max_v <= 1.001 and len(CLASSES) == 10
cases.append(dict(
name="data_loading_and_normalize",
inputs=dict(source=source_mode, train_size=len(train_ds), test_size=len(test_ds)),
prerequisites="ToTensor() + Normalize((0.5,0.5,0.5), (0.5,0.5,0.5)) 映射至 [-1, 1]",
action="验证 10 类 RGB 32×32 数据批次形状与标准化值域。",
expected=dict(batch_shape=[32, 3, 32, 32], in_neg1_to_1=True, num_classes=10),
actual=dict(batch_shape=list(bx.shape), in_neg1_to_1=-1.001 <= min_v <= max_v <= 1.001, num_classes=len(CLASSES)),
measurements=dict(min_val=round(min_v, 4), max_val=round(max_v, 4)),
passed=c1_ok,
))
# 2. CNN layer-by-layer shape verification
net = Net()
with torch.inference_mode():
s1 = net.pool(F.relu(net.conv1(bx[:2])))
s2 = net.pool(F.relu(net.conv2(s1)))
out2 = net(bx[:2])
param_count = sum(p.numel() for p in net.parameters())
c2_ok = list(s1.shape) == [2, 6, 14, 14] and list(s2.shape) == [2, 16, 5, 5] and list(out2.shape) == [2, 10] and param_count == 62006
cases.append(dict(
name="cnn_architecture_shapes",
inputs=dict(input_shape=[2, 3, 32, 32]),
prerequisites="Conv2d(3,6,5)->Pool->Conv2d(6,16,5)->Pool->FC(400,120,84,10)",
action="逐层核对特征图尺寸 32->28->14->10->5 与总参数量 62,006。",
expected=dict(after_pool1=[2, 6, 14, 14], after_pool2=[2, 16, 5, 5], logits_shape=[2, 10], params=62006),
actual=dict(after_pool1=list(s1.shape), after_pool2=list(s2.shape), logits_shape=list(out2.shape), params=param_count),
passed=c2_ok,
))
# 3. Training loop with CrossEntropyLoss + SGD(momentum=0.9)
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.015, momentum=0.9)
epoch_losses = []
for _ in range(12):
net.train()
total_l = 0.0
for imgs, lbls in train_loader:
optimizer.zero_grad(set_to_none=True)
loss = criterion(net(imgs), lbls)
loss.backward()
optimizer.step()
total_l += float(loss.item()) * imgs.size(0)
epoch_losses.append(round(total_l / len(train_ds), 5))
c3_ok = epoch_losses[-1] < epoch_losses[0] * 0.75
cases.append(dict(
name="cnn_training_convergence",
inputs=dict(epochs=12, optimizer="SGD(lr=0.015, momentum=0.9)", batch_size=32),
prerequisites="固定随机种子训练 12 轮",
action="验证训练损失相对首轮显著下降。",
expected=dict(epochs=12, loss_dropped_25pct=True),
actual=dict(epochs=len(epoch_losses), loss_dropped_25pct=epoch_losses[-1] < epoch_losses[0] * 0.75),
measurements=dict(epoch1_loss=epoch_losses[0], epoch12_loss=epoch_losses[-1]),
passed=c3_ok,
))
# 4. Held-out overall & per-class evaluation (safe for arbitrary / size-1 tail batch)
net.eval()
class_correct = [0] * 10
class_total = [0] * 10
total_correct = 0
total_count = 0
with torch.inference_mode():
for imgs, lbls in test_loader:
preds = net(imgs).argmax(dim=1)
total_count += lbls.size(0)
total_correct += int((preds == lbls).sum().item())
for p_idx, y_idx in zip(preds.tolist(), lbls.tolist()):
class_total[y_idx] += 1
if p_idx == y_idx:
class_correct[y_idx] += 1
# Also test a size-1 batch explicitly to confirm no squeeze() crash
one_pred = net(bx[:1]).argmax(dim=1)
tail_batch1_safe = len(one_pred.tolist()) == 1
overall_acc = round(total_correct / total_count, 4)
per_class_acc = {CLASSES[i]: round(class_correct[i] / class_total[i], 4) for i in range(10)}
# Random 10-class baseline is 0.10; real CIFAR-10 2k subset easily exceeds 0.30
c4_ok = overall_acc >= 0.30 and sum(class_total) == len(test_ds) and tail_batch1_safe
cases.append(dict(
name="heldout_overall_and_per_class_eval",
inputs=dict(test_samples=len(test_ds), random_baseline=0.10),
prerequisites="model.eval() + torch.inference_mode(),按 zip 遍历规避末批 size=1 崩溃",
action="统计独立测试集总体准确率、10 类别各自准确率及单样本批次安全推理。",
expected=dict(above_30pct=True, all_samples_counted=True, batch1_safe=True),
actual=dict(above_30pct=overall_acc >= 0.30, all_samples_counted=sum(class_total) == len(test_ds), batch1_safe=tail_batch1_safe),
measurements=dict(overall_acc=overall_acc, per_class_acc=per_class_acc),
passed=c4_ok,
))
# 5. Save state_dict & reload with weights_only=True for identical prediction
with tempfile.TemporaryDirectory() as tmp:
ckpt = Path(tmp) / "cifar_net.pth"
torch.save(net.state_dict(), ckpt)
reloaded = Net()
reloaded.load_state_dict(torch.load(ckpt, map_location="cpu", weights_only=True))
reloaded.eval()
sample_imgs = torch.stack([test_ds[i][0] for i in range(4)])
with torch.inference_mode():
orig_logits = net(sample_imgs)
load_logits = reloaded(sample_imgs)
reload_diff = float((orig_logits - load_logits).abs().max().item())
pred_labels = [CLASSES[i] for i in load_logits.argmax(dim=1).tolist()]
c5_ok = reload_diff == 0.0 and len(pred_labels) == 4
cases.append(dict(
name="save_reload_and_predict",
inputs=dict(sample_count=4, weights_only=True),
prerequisites="保存 state_dict 后在 eval 模式下加载预测 4 张测试图",
action="确认重载后 logits 与原模型误差为 0.0 并输出类别名。",
expected=dict(logits_identical=True, predicted_4=True),
actual=dict(logits_identical=reload_diff == 0.0, predicted_4=len(pred_labels) == 4),
measurements=dict(sample_predictions=pred_labels),
passed=c5_ok,
))
# 6. Observed Matplotlib figure: training loss + per-class accuracy bar chart
if fig_dir is not None:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig_dir.mkdir(parents=True, exist_ok=True)
fig, axes = plt.subplots(1, 2, figsize=(9.6, 3.8), dpi=140)
axes[0].plot(range(1, len(epoch_losses) + 1), epoch_losses, marker="o", color="#174d79", linewidth=2)
axes[0].set_title(f"CNN Training Loss ({len(train_ds)} samples, 12 Epochs)", fontsize=10)
axes[0].set_xlabel("Epoch")
axes[0].set_ylabel("Cross-Entropy Loss")
axes[0].grid(True, alpha=0.3)
accs = [per_class_acc[c] * 100 for c in CLASSES]
axes[1].bar(CLASSES, accs, color="#2a7f62")
axes[1].axhline(overall_acc * 100, color="#ae511d", linestyle="--", label=f"Overall {overall_acc*100:.1f}%")
axes[1].set_title(f"Held-Out Per-Class Accuracy ({len(test_ds)} test images)", fontsize=10)
axes[1].set_ylabel("Accuracy (%)")
axes[1].set_ylim(0, 100)
axes[1].tick_params(axis="x", rotation=35, labelsize=8)
axes[1].legend(fontsize=8)
fig.tight_layout()
out_png = fig_dir / "cifar10-cnn-eval.png"
fig.savefig(out_png)
plt.close(fig)
figures["cifar10-cnn-eval.png"] = sha(out_png)
mpl_ver = matplotlib.__version__
else:
mpl_ver = None
cases.append(dict(
name="observed_cifar10_eval_plot",
inputs=dict(classes=10, epochs=12),
prerequisites="固定随机种子训练历史与 10 类别留出准确率",
action="绘制训练损失曲线与 10 类别准确率柱状图。",
expected=dict(epochs_plotted=12, classes_plotted=10),
actual=dict(epochs_plotted=len(epoch_losses), classes_plotted=len(per_class_acc)),
measurements=dict(figure_generated="cifar10-cnn-eval.png" in figures),
passed=len(epoch_losses) == 12 and len(per_class_acc) == 10,
))
payload = dict(
version=platform.python_version(),
torch=torch.__version__,
torchvision=torchvision.__version__,
pillow=PIL.__version__,
system=platform.system(),
cases=cases,
)
if mpl_ver:
payload["matplotlib"] = mpl_ver
payload["figures"] = figures
print(json.dumps(payload, ensure_ascii=False))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--cifar", type=Path, default=None)
parser.add_argument("--figures", type=Path, default=None)
args = parser.parse_args()
run_cases(args.cifar, args.figures)
本例需在 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。
入口文件:projects/pytorch-image-classification-lab/train-image-classifier.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
train-image-classifier.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a409.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a423.zip