蓝色天空网mbsky.com · 知识 · 实践 · 创造PyTorch · 本地阅读预览
教程 / AI / 智能开发 / PyTorch

PyTorch 卷积神经网络

从手算卷积窗口入手,训练数字分类模型并在独立 MNIST 测试集上核对预测。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

从图像到类别分数

卷积神经网络适合处理图像等网格数据。图像分类要给整张图分配类别,检测还需定位对象,分割则可为像素或对象分配标签。多层卷积与池化能逐步扩大感受野,组合边缘、纹理与形状。

PyTorch 的二维图像批次按 [N,C,H,W] 排列。N 是张数,C 是通道数,H 和 W 是高和宽。灰度 MNIST 只有一个通道,RGB 通常有三个通道。

前半部分生成空间特征图。对数字分类,每张图的末级特征按通道和空间轴展平,保留批次维度,送入全连接层得到十个分数。用于回归时也可将头部改为连续值输出。

例如三个类的概率分别是 0.20、0.10、0.70,最大项对应第三类。模型通常直接给出 logits。推断时按类轴计算 softmax 可得到和为 1 的分布,按相同轴取最大值下标即可做分类。分布的数值不能单独保证概率经过校准。

核、步幅与池化窗口

Conv2d 实际使用互相关。把未翻转的核系数与每个窗口逐项相乘,累加输入通道的贡献,再加该输出通道的偏置。同一组权重随窗口滑动,每个输出通道生成一张特征图。本站用左上系数 1、右下 −1 的 2×2 核,在左上窗口算得 1−5+0.5=−3.5。

ReLU 把负值置零,非负值保持原值。实测 [−2,−1,0,4] 变为 [0,0,0,4]。这个非线性步骤让多层模型可以组合更复杂的特征。

最大池化保留窗口最大值,平均池化对窗口求平均。用 1 至 9 排成 3×3 网格,2×2 最大池化的默认步幅是 2,只得到 5。步幅改为 1 得到两行 [5,6] 和 [8,9];同样窗口的平均值是 [3,4] 和 [6,7]。池化没有需要训练的核参数,空间缩小可能减少后续计算和全连接参数。

LRN 按相邻通道响应调整激活,BatchNorm2d 训练时用每通道批统计,默认评估时用累计统计。Dropout 在训练时随机遮盖,评估时直接传递。L1 和 L2 可分别为权重绝对值之和或平方和添加惩罚。它们都可独立选用,正则化效果需用留出数据评估。

准备数据并记录模型形状

实验使用校验过的 MNIST 本地档案,从原始训练划分固定抽取 6,000 张,保留全部 10,000 张测试图。像素转 float32 后缩放到 [−1,1]。程序用 TorchVision 的 ToTensor 与 Normalize 对照一张样本,标签保持 int64。使用 torchvision.datasets.MNIST 时,train 参数选择划分,download=False 可读取已准备好的缓存。

第一层把 [N,1,28,28] 变成 [N,8,28,28],池化得到 [N,8,14,14]。第二层输出 [N,16,14,14],再池化成 [N,16,7,7]。两卷积都是 3×3、步幅 1、补零 1。Flatten(1) 得 [N,784],随后通过 32 单元的隐层和 10 单元的分类层。

输入、两次池化和分类分数的实际批次形状。
本站 CPU 实验逐层读取的批次形状,N 表示批量大小。

训练五轮并验证整份测试划分

多类分类用 CrossEntropyLoss 接收 logits 和整数类别,内部计算稳定的对数概率。实数回归常用同形预测和目标计算平方差均值。本站分别核对两者,连续值 [2,5] 对 [1,3] 的均方误差为 2.5。

优化器按梯度更新参数,SGD 可累积动量,Adam 和 RMSprop 可自适应调整步幅。本站用 SGD、学习率 0.08、动量 0.9。每个批次清旧梯度,前向后计算损失,反向,再更新。训练集打乱五轮,按各批次样本数加权计算轮均损失,末批也纳入。五轮实际损失约为 1.00390、0.19554、0.13452、0.09045、0.06721。

测试保持原顺序。model.eval() 切换模块模式,torch.inference_mode() 单独停用梯度记录。沿十类维度直接取 logits 最大项,正确数除以样本数。本站在 10,000 张测试图中判对 9,597 张,准确率 95.97%。轮次、数据量、划分、结构和种子变化都会影响这个结果。

下图按测试顺序显示前六幅原始灰度图,每格标明真实标签和模型预测。本次六张都是 7、2、1、0、4、1,六个预测与标签一致。全部样本的准确率以测试循环统计为准。

六张测试手写数字的灰度图及实测标签,依次为 7、2、1、0、4、1。
本站绘制的第一批测试图,Label 为真实标签,Pred 为模型预测。

处理数据初始化与证书报错

历史下载日志中的 CERTIFICATE_VERIFY_FAILED 表示 Python 无法建立可信证书链。对于 python.org 的 macOS 安装包,可按对应版本的 Python 文件夹打开 Install Certificates.command,再在同一解释器验证。其他安装方式按发行方指南配置 CA。本章实验通过校验本地档案运行,保留 TLS 校验。

卷积及分类的常用参数

组件本章选用值作用与形状
Conv2dkernel_size=3,stride=1,padding=1通道数由 in_channels 和 out_channels 决定。两层各保留输入高宽。
MaxPool2dkernel_size=2,默认 stride=2在每通道取窗口最大值。宽高 28→14→7。
Flattenstart_dim=1只合并通道和空间轴,批次仍在第 0 轴。
CrossEntropyLoss默认 reduction='mean'输入形状 [N,10],类别标签形状 [N]。输出是标量损失。
SGDlr=0.08,momentum=0.9每次反向后调用 step,更新参数并保留独立动量状态。

运行 MNIST 卷积分类实验

python · 阅读源码
"""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()
预期结果 · 待实际运行核验
  • 用 6,000 张训练图训练五轮,以全部 10,000 张测试图核对准确率并输出真实预测图。
运行 MNIST 卷积分类实验

所需环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。

当前源码 SHA256:e241673805f1faf96497e73eb22eb409bc5d0aa27d8834bb41bc657c18fea002

下载本站示例源码

本地运行

解压后按 README 选择对应构建并运行脚本。

下载PyTorch 卷积神经网络实验

所需环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。

ZIP SHA256:3f348aef6439ae8a9010d3d01f1e63b176d4f59ba2eede7db560241dae2154bf

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

对一张灰度图做批推断,为什么常用 reshape(1,1,28,28)?

展开参考解答

前两个长度为 1 的轴分别表示批次和灰度通道。

规范与官方依据