蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 MNIST 卷积分类实验

PYTHONWindows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。train-mnist-cnn.py
train-mnist-cnn.py218 行
"""Measure a small convolutional digit classifier using a pinned local MNIST archive."""
import argparse
from hashlib import sha256
import json
import platform
from pathlib import Path

import numpy as np
from PIL import Image, __version__ as pillow_version
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils.data import DataLoader, TensorDataset
import torchvision
from torchvision import transforms


MNIST_SHA256 = "731c5ac602752760c8e48fbffcf8c3b850d9dc2a2aedcf2cc48468fc17b673d1"
TRAIN_COUNT = 6000
TEST_COUNT = 10000


class DigitCNN(nn.Module):
    def __init__(self):
        super().__init__()
        self.features = nn.Sequential(
            nn.Conv2d(1, 8, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
            nn.Conv2d(8, 16, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
        )
        self.classifier = nn.Sequential(nn.Flatten(1), nn.Linear(16 * 7 * 7, 32), nn.ReLU(), nn.Linear(32, 10))

    def forward(self, images):
        return self.classifier(self.features(images))


def record(cases, name, inputs, conditions, action, expected, actual, **measurements):
    assert actual == expected, (name, expected, actual)
    cases.append(dict(name=name, inputs=inputs, prerequisites=conditions, action=action,
                      expected=expected, actual=actual, passed=True, measurements=measurements))


def operator_checks(cases, model):
    grid = torch.arange(1., 10.).reshape(1, 1, 3, 3)
    kernel = torch.tensor([[[[1., 0.], [0., -1.]]]])
    filtered = F.conv2d(grid, kernel, bias=torch.tensor([.5]))
    record(cases, "convolution_activation", {"grid":grid[0, 0].tolist(), "kernel":kernel[0, 0].tolist(),"bias":.5},
           "Asymmetric filter, no padding, stride 1", "Check the top-left correlation and the ReLU branch",
           [[-3.5, -3.5], [-3.5, -3.5], [0., 0., 0., 4.]],
           [*filtered[0, 0].tolist(), F.relu(torch.tensor([-2., -1., 0., 4.])).tolist()])
    record(cases, "pooling_windows", grid[0, 0].tolist(), "2 by 2 windows and no padding",
           "Compare default stride 2, explicit stride 1 and average pooling",
           [[[[[5.]]]], [[[[5., 6.], [8., 9.]]]], [[[[3., 4.], [6., 7.]]]]],
           [F.max_pool2d(grid, 2).tolist(), F.max_pool2d(grid, 2, stride=1).tolist(),
            F.avg_pool2d(grid, 2, stride=1).tolist()])
    images = torch.zeros(2, 1, 28, 28)
    value = images
    shapes = []
    for layer in model.features:
        value = layer(value)
        if isinstance(layer, (nn.Conv2d, nn.MaxPool2d)):
            shapes.append(list(value.shape))
    logits = model.classifier(value)
    record(cases, "feature_shapes", list(images.shape), "Every convolution has padding 1 and stride 1",
           "Read feature shapes, flatten only sample axes, and compare probability and logit argmax",
           [[[2, 8, 28, 28], [2, 8, 14, 14], [2, 16, 14, 14], [2, 16, 7, 7]], [2, 784], [2, 10], True, True],
           [shapes, list(value.flatten(1).shape), list(logits.shape),
            torch.allclose(logits.softmax(1).sum(1), torch.ones(2)),
            torch.equal(logits.argmax(1), logits.softmax(1).argmax(1))])
    scores = torch.tensor([[0., 1., 2.], [2., 0., 1.]])
    labels = torch.tensor([2, 0])
    record(cases, "classification_and_regression_loss", {"logits":scores.tolist(),"class_ids":labels.tolist()},
           "Class IDs are int64; continuous targets use matching shapes",
           "Compare cross entropy with gathered log-softmax and calculate MSE on a separate pair of values",
           [True, 2.5],
           [torch.allclose(F.cross_entropy(scores, labels), -scores.log_softmax(1)[range(2), labels].mean()),
            F.mse_loss(torch.tensor([2., 5.]), torch.tensor([1., 3.])).item()])
    data = torch.arange(1., 9.).reshape(2, 1, 2, 2).requires_grad_()
    norm = nn.BatchNorm2d(1, momentum=1.)
    train = norm(data)
    eval_value = norm.eval()(data)
    drop = nn.Dropout(.25)
    lrn = nn.LocalResponseNorm(3)
    channels = torch.tensor([1., 2., 3.]).reshape(1, 3, 1, 1)
    parameter = torch.tensor([-.5, 2.], requires_grad=True)
    l1 = parameter.abs().sum()
    l2 = parameter.square().sum()
    record(cases, "regularization_and_modes", {"activation":list(data.shape), "weights":parameter.tolist()},
           "Configured BatchNorm, Dropout and LRN on deterministic data",
           "Inspect the running mean, eval behavior, channel normalization, gradients and explicit penalties",
           [True, 4.5, True, True, True, True, 2.5, 4.25],
           [abs(train.mean().item()) < 1e-6, norm.running_mean.item(), not torch.equal(train,eval_value),
            eval_value.requires_grad, torch.equal(drop.eval()(data),data),
            bool(torch.all(lrn(channels)<channels)), l1.item(), l2.item()])


def load_data(path, cases):
    payload_hash = sha256(path.read_bytes()).hexdigest()
    if payload_hash != MNIST_SHA256:
        raise ValueError("The MNIST archive does not match MNIST-DATA.txt.")
    transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((.5,), (.5,))])
    with np.load(path, allow_pickle=False) as data:
        raw_train, raw_test = data["x_train"], data["x_test"]
        train_selection = np.random.default_rng(42).choice(len(raw_train), size=TRAIN_COUNT, replace=False)
        training_raw, testing_raw = raw_train[train_selection], raw_test
        train_images = torch.from_numpy(training_raw).unsqueeze(1).float().div_(127.5).sub_(1)
        test_images = torch.from_numpy(testing_raw).unsqueeze(1).float().div_(127.5).sub_(1)
        train_labels = torch.from_numpy(data["y_train"][train_selection]).long()
        test_labels = torch.from_numpy(data["y_test"]).long()
        sample = transform(Image.fromarray(testing_raw[0]))
    record(cases, "offline_mnist_input", {"sha256":payload_hash,"train_count":TRAIN_COUNT,"test_count":TEST_COUNT},
           "Verified NPZ, original train/test splits, seed 42 for training selection",
           "Compare direct normalization with TorchVision ToTensor and Normalize; inspect split shapes",
           [[TRAIN_COUNT,1,28,28],[TEST_COUNT,1,28,28],True,True,True],
           [list(train_images.shape),list(test_images.shape),torch.allclose(sample,test_images[0],atol=2e-7),
            train_labels.dtype == test_labels.dtype == torch.int64,
            bool(train_images.min()>=-1 and train_images.max()<=1)])
    return TensorDataset(train_images, train_labels), TensorDataset(test_images, test_labels), testing_raw


def fit(model, training, cases):
    batches = DataLoader(training, batch_size=64, shuffle=True, generator=torch.Generator().manual_seed(99))
    optimizer = torch.optim.SGD(model.parameters(), lr=.08, momentum=.9)
    criterion = nn.CrossEntropyLoss()
    initial = next(model.parameters()).detach().clone()
    history = []
    cleared, has_gradient = False, False
    for _ in range(5):
        model.train()
        weighted_loss = 0.
        for images, labels in batches:
            optimizer.zero_grad(set_to_none=True)
            cleared = all(p.grad is None for p in model.parameters())
            outputs = model(images)
            loss = criterion(outputs, labels)
            loss.backward()
            has_gradient = bool(torch.count_nonzero(next(model.parameters()).grad))
            optimizer.step()
            weighted_loss += loss.item() * len(labels)
        history.append(weighted_loss / len(training))
    record(cases, "five_sgd_epochs", {"samples":len(training),"batch_size":64,"lr":.08,"momentum":.9},
           "PyTorch CPU, fixed model and shuffle seeds, final batch included",
           "Train with SGD and observe gradient cleanup, parameter change and per-sample mean loss",
           [5, True, True, True, True],
           [len(history), all(np.isfinite(history)), history[-1] < history[0], cleared and has_gradient,
            not torch.equal(initial, next(model.parameters()).detach())], loss=history)


def evaluate(model, testing, cases):
    batches = DataLoader(testing, batch_size=64, shuffle=False)
    model.eval()
    scores = []
    with torch.inference_mode():
        for images, _ in batches:
            scores.append(model(images))
    logits = torch.cat(scores)
    predictions = logits.argmax(dim=1)
    labels = testing.tensors[1]
    correct = int((predictions == labels).sum())
    record(cases, "full_test_accuracy", {"samples":len(testing),"batch_size":64},
           "Original test split in file order, inference mode after training",
           "Measure accuracy, ten scores per sample and absence of gradient tracking",
           [[TEST_COUNT,10],True,True,True],
           [list(logits.shape),not logits.requires_grad,not model.training,correct/TEST_COUNT >= .90],
           correct=correct, total=TEST_COUNT, accuracy=correct/TEST_COUNT)
    return predictions, labels


def plot_predictions(folder, images, labels, predictions, cases):
    import matplotlib
    matplotlib.use("Agg")
    from matplotlib import pyplot as plt

    folder.mkdir(parents=True, exist_ok=True)
    figure, axes = plt.subplots(1, 6, figsize=(10.8, 2.65), layout="constrained")
    figure.suptitle("MNIST / first 6 held-out images", color="#173b55", fontweight="bold")
    matched = []
    for index, panel in enumerate(axes):
        image = images[index]
        label, guess = int(labels[index]), int(predictions[index])
        drawing = panel.imshow(image, cmap="gray", vmin=0, vmax=255, interpolation="nearest")
        heading = f"Label {label} / Pred {guess}"
        panel.set_title(heading, color="#176147" if label == guess else "#a44520", fontsize=10)
        panel.axis("off")
        matched.append(panel.get_title() == heading and np.array_equal(drawing.get_array(), image))
    preview = folder/"mnist-six-predictions.png"
    figure.savefig(preview, dpi=125, facecolor="#f4f7f9")
    plt.close(figure)
    with Image.open(preview) as png:
        assert png.format == "PNG"
        width, height = png.size
    record(cases, "observed_prediction_figure", {"indices":list(range(6))},"Matplotlib Agg and full test predictions",
           "Check six image arrays, real labels, predicted labels, and PNG dimensions", [True]*6+[1350,331],
           matched+[width,height], labels=labels[:6].tolist(), predictions=predictions[:6].tolist())
    return matplotlib.__version__, {preview.name:sha256(preview.read_bytes()).hexdigest()}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--mnist", type=Path, required=True, help="path to checksum-verified mnist.npz")
    parser.add_argument("--figures", type=Path, default=Path("charts"))
    args = parser.parse_args()
    torch.set_num_threads(1)
    torch.manual_seed(42)
    cases = []
    model = DigitCNN()
    operator_checks(cases, model)
    training, testing, raw = load_data(args.mnist, cases)
    fit(model, training, cases)
    predictions, labels = evaluate(model, testing, cases)
    matplotlib_version, figures = plot_predictions(args.figures, raw, labels, predictions, cases)
    print(json.dumps(dict(version=platform.python_version(), system=platform.system(), torch=torch.__version__,
         torchvision=torchvision.__version__, pillow=pillow_version, numpy=np.__version__,
         matplotlib=matplotlib_version, cases=cases, figures=figures), allow_nan=False))


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-cnn-lab/train-mnist-cnn.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 train-mnist-cnn.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:PyTorch

课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a409.zip

下载课程关联工程包:PyTorch

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a414.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习