PyTorch从入门到熟悉 · 第7/20篇

CNN与计算机视觉实战

从卷积运算原理到经典CNN架构演进,迁移学习策略与CIFAR-10完整分类实战

生成日期:2026年11月6日 · 面向大模型开发 · 返回目录

概述:卷积神经网络与计算机视觉

卷积神经网络(CNN)是计算机视觉领域的基石。与全连接网络不同,CNN通过卷积运算自动提取空间特征,具有参数共享和平移不变性两大优势。从LeNet的手写数字识别到ResNet的千类ImageNet分类,CNN架构不断演进,为后来的Vision Transformer奠定了基础。

本章将从卷积运算的数学原理出发,逐步讲解池化层、归一化层、经典架构演进,最后通过CIFAR-10完整实战将理论付诸实践。

卷积运算原理示意图 输入特征图 5×5 1 2 0 1 3 1 2 0 0 1 3 2 2 0 1 0 滑动窗口 卷积核 3×3 1 0 1 0 1 0 1 0 1 ⊗ 输出特征图 3×3 5 3 4 2 6 3 4 2 5 = stride=1, padding=0 可学习参数 输出 = (5-3)/1 + 1 = 3 输出尺寸公式: O = ⌊(W - K + 2P) / S⌋ + 1 W=输入宽度, K=卷积核大小, P=padding, S=stride

一、卷积层原理

卷积运算是CNN的核心操作。与全连接层不同,卷积层通过一个小的可学习卷积核(Kernel)在输入特征图上滑动,每次计算局部区域的加权和,从而提取局部特征。

1.1 卷积运算详解

对于二维卷积,卷积核在输入特征图上滑动,每个位置计算逐元素乘积之和加上偏置。卷积核的参数在所有位置共享,这大大减少了参数量并赋予模型平移不变性。

Python
import torch
import torch.nn as nn

# 手动实现二维卷积运算
def conv2d_manual(input, kernel, bias=0):
    """手动实现单通道卷积"""
    i_h, i_w = input.shape
    k_h, k_w = kernel.shape
    o_h, o_w = i_h - k_h + 1, i_w - k_w + 1

    output = torch.zeros(o_h, o_w)
    for i in range(o_h):
        for j in range(o_w):
            region = input[i:i+k_h, j:j+k_w]
            output[i, j] = (region * kernel).sum() + bias
    return output

# 示例
x = torch.tensor([[1., 2., 0., 1., 0.],
                   [3., 1., 2., 0., 1.],
                   [0., 1., 3., 2., 0.],
                   [2., 0., 1., 0., 3.],
                   [1., 2., 0., 1., 0.]])
k = torch.tensor([[1., 0., 1.],
                   [0., 1., 0.],
                   [1., 0., 1.]])

result = conv2d_manual(x, k)
print(f"卷积结果:\n{result}")

1.2 输出尺寸公式

卷积操作的输出尺寸由输入尺寸、卷积核大小、步长(stride)和填充(padding)共同决定:

Python
# 输出尺寸公式: O = floor((W - K + 2*P) / S) + 1
# W=输入宽度, K=卷积核大小, P=padding, S=stride

# 使用PyTorch验证
conv = nn.Conv2d(1, 1, kernel_size=3, stride=1, padding=0)
x = torch.randn(1, 1, 5, 5)
out = conv(x)
print(f"输入: {x.shape} -> 输出: {out.shape}")
# 输入: [1, 1, 5, 5] -> 输出: [1, 1, 3, 3]

# stride=2: 下采样
conv_s2 = nn.Conv2d(1, 1, kernel_size=3, stride=2, padding=1)
out_s2 = conv_s2(x)
print(f"stride=2: {x.shape} -> {out_s2.shape}")
# stride=2: [1, 1, 5, 5] -> [1, 1, 3, 3]

# padding='same': 保持尺寸不变
conv_same = nn.Conv2d(1, 1, kernel_size=3, stride=1, padding=1)
out_same = conv_same(x)
print(f"padding=1: {x.shape} -> {out_same.shape}")
# padding=1: [1, 1, 5, 5] -> [1, 1, 5, 5]

1.3 感受野

感受野(Receptive Field)是指输出特征图中一个像素对应输入图像的区域大小。随着网络加深,感受野逐层增大,使深层神经元能够"看到"更大范围的输入信息。

Python
# 计算多层网络的感受野
def compute_receptive_field(layers):
    """layers: [(kernel_size, stride), ...]"""
    rf = 1  # 初始感受野
    jump = 1  # 初始步长跳跃
    for k, s in layers:
        rf += (k - 1) * jump
        jump *= s
    return rf

# VGG前3层卷积(都是3x3, stride=1)
layers = [(3, 1), (3, 1), (3, 1)]
print(f"3层3x3卷积感受野: {compute_receptive_field(layers)}")
# 3层3x3卷积感受野: 7

# ResNet第一阶段:7x7卷积 + 3个3x3卷积
layers_resnet = [(7, 2), (3, 1), (3, 1), (3, 1)]
print(f"ResNet第一阶段感受野: {compute_receptive_field(layers_resnet)}")

1.4 stride、padding与dilation

stride控制卷积核滑动的步幅,大于1时实现下采样。padding在输入边缘补零,控制输出尺寸。dilation在卷积核元素间插入间隔,扩大感受野而不增加参数量。

Python
# dilation(空洞卷积):扩大感受野
conv_dilated = nn.Conv2d(1, 1, kernel_size=3, dilation=2, padding=2)
x = torch.randn(1, 1, 7, 7)
out = conv_dilated(x)
print(f"dilation=2: {x.shape} -> {out.shape}")
# 感受野从3扩大到5,但参数量不变

# groups(分组卷积):减少参数量
conv_grouped = nn.Conv2d(4, 4, kernel_size=3, groups=2)
# 参数量减半:4个输入通道分成2组,每组2通道
print(f"分组卷积参数量: {sum(p.numel() for p in conv_grouped.parameters())}")

二、nn.Conv2d参数详解

nn.Conv2d是PyTorch中最常用的卷积层,理解其每个参数至关重要。

2.1 参数全解

Python
conv = nn.Conv2d(
    in_channels=3,        # 输入通道数(RGB=3)
    out_channels=64,       # 输出通道数(卷积核数量)
    kernel_size=3,         # 卷积核大小(int或tuple)
    stride=1,             # 步长
    padding=1,            # 填充(int或tuple或'same'/'valid')
    dilation=1,           # 空洞率
    groups=1,             # 分组数
    bias=True,            # 是否使用偏置
    padding_mode='zeros'   # 'zeros'/'reflect'/'replicate'/'circular'
)

# 参数量计算
params = 3 * 64 * 3 * 3 + 64  # weight + bias
print(f"参数量: {params}")
print(f"实际参数量: {sum(p.numel() for p in conv.parameters())}")

2.2 1x1卷积的特殊用途

1x1卷积不进行空间特征提取,但可以实现通道降维/升维和跨通道信息融合,在Inception和ResNet的bottleneck中被广泛使用。

Python
# 1x1卷积:通道变换
conv_1x1 = nn.Conv2d(256, 64, kernel_size=1)
x = torch.randn(1, 256, 28, 28)
out = conv_1x1(x)
print(f"1x1卷积: {x.shape} -> {out.shape}")
# 256通道降维到64通道,空间尺寸不变

三、池化层

池化层(Pooling)对特征图进行下采样,减少计算量并增强特征的平移不变性。

3.1 MaxPool与AvgPool

Python
# 最大池化:取窗口内最大值
maxpool = nn.MaxPool2d(kernel_size=2, stride=2)
x = torch.randn(1, 1, 4, 4)
out = maxpool(x)
print(f"MaxPool: {x.shape} -> {out.shape}")
# [1, 1, 4, 4] -> [1, 1, 2, 2]

# 平均池化:取窗口内平均值
avgpool = nn.AvgPool2d(kernel_size=2, stride=2)
out_avg = avgpool(x)
print(f"AvgPool: {x.shape} -> {out_avg.shape}")

3.2 AdaptivePool与全局平均池化

自适应池化只需指定输出尺寸,自动计算stride和kernel_size。全局平均池化(GAP)将整个特征图压缩为单个值,在ResNet和GoogLeNet中用于替代全连接层。

Python
# 自适应平均池化:指定输出尺寸
adaptive_pool = nn.AdaptiveAvgPool2d(output_size=(1, 1))
x = torch.randn(1, 512, 7, 7)
out = adaptive_pool(x)
print(f"GAP: {x.shape} -> {out.shape}")
# [1, 512, 7, 7] -> [1, 512, 1, 1]  全局平均池化

# 自适应最大池化:输出固定5x5
adaptive_max = nn.AdaptiveMaxPool2d(output_size=(5, 5))
out_max = adaptive_max(x)
print(f"AdaptiveMax: {x.shape} -> {out_max.shape}")
# [1, 512, 7, 7] -> [1, 512, 5, 5]

四、归一化层对比

归一化层通过标准化激活值来加速训练并提高稳定性。不同的归一化方式在不同的场景下有各自的优势。

4.1 BatchNorm——批归一化

BatchNorm沿batch维度归一化,在CV中是标配。训练时使用当前batch的统计量,推理时使用累积的移动平均统计量。

Python
# BatchNorm2d:用于卷积层后
bn = nn.BatchNorm2d(64)  # 参数为通道数
x = torch.randn(32, 64, 28, 28)  # batch=32
out = bn(x)
print(f"BN: {x.shape} -> {out.shape}")

# 训练/推理模式切换
bn.train()  # 使用batch统计量
bn.eval()   # 使用移动平均统计量

# BatchNorm1d:用于全连接层后
bn1d = nn.BatchNorm1d(128)
x_fc = torch.randn(32, 128)
out_fc = bn1d(x_fc)

4.2 LayerNorm——层归一化

LayerNorm沿特征维度归一化,不依赖batch大小,在Transformer和RNN中常用。

Python
# LayerNorm:对每个样本独立归一化
ln = nn.LayerNorm(512)  # 参数为特征维度
x = torch.randn(32, 10, 512)
out = ln(x)
print(f"LN: {x.shape} -> {out.shape}")
# 每个样本的512维特征独立归一化

4.3 GroupNorm——组归一化

GroupNorm将通道分成若干组,在组内归一化。不依赖batch大小,适合小batch场景。

Python
# GroupNorm:将通道分成32组
gn = nn.GroupNorm(num_groups=32, num_channels=64)
x = torch.randn(4, 64, 28, 28)  # 小batch也能正常工作
out = gn(x)
print(f"GN: {x.shape} -> {out.shape}")

4.4 归一化方式对比

归一化方式归一化维度依赖batch典型场景
BatchNormbatch维度是CV(CNN)
LayerNorm特征维度否NLP(Transformer/RNN)
GroupNorm通道分组否小batch CV
InstanceNorm单样本通道否风格迁移
💡 BN推理模式

BatchNorm在训练时使用当前batch的均值和方差,推理时使用训练过程中累积的移动平均(running_mean和running_var)。推理前必须调用model.eval(),否则会使用错误的统计量导致性能下降。

五、经典CNN架构演进

从LeNet到EfficientNet,CNN架构经历了从浅到深、从简单到复杂的演进过程。每一次突破都解决了一个关键问题。

5.1 LeNet-5——开山之作

Python
class LeNet5(nn.Module):
    def __init__(self, num_classes=10):
        super().__init__()
        self.conv1 = nn.Conv2d(1, 6, kernel_size=5)
        self.pool1 = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(6, 16, kernel_size=5)
        self.pool2 = nn.MaxPool2d(2, 2)
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, num_classes)

    def forward(self, x):
        x = self.pool1(torch.relu(self.conv1(x)))
        x = self.pool2(torch.relu(self.conv2(x)))
        x = x.view(x.size(0), -1)
        x = torch.relu(self.fc1(x))
        x = torch.relu(self.fc2(x))
        x = self.fc3(x)
        return x

5.2 VGG——深度堆叠

VGG通过堆叠多个3x3小卷积核替代大卷积核,证明了深度对性能的重要性。两个3x3卷积的感受野等于一个5x5,但参数更少且非线性更强。

Python
# VGG块:多个3x3卷积 + 池化
def vgg_block(in_ch, out_ch, num_convs):
    layers = []
    for i in range(num_convs):
        layers.append(nn.Conv2d(in_ch if i == 0 else out_ch, out_ch, 3, padding=1))
        layers.append(nn.BatchNorm2d(out_ch))
        layers.append(nn.ReLU(inplace=True))
    layers.append(nn.MaxPool2d(2, 2))
    return nn.Sequential(*layers)

# VGG-16的前几个块
vgg_features = nn.Sequential(
    vgg_block(3, 64, 2),
    vgg_block(64, 128, 2),
    vgg_block(128, 256, 3),
    vgg_block(256, 512, 3),
    vgg_block(512, 512, 3),
)

5.3 ResNet——残差连接

ResNet通过残差连接(skip connection)解决了深度网络的梯度消失问题,使得训练上百层的网络成为可能。残差块学习的是输入与输出的差值(残差),而非完整的映射。

Python
class BasicBlock(nn.Module):
    def __init__(self, in_ch, out_ch, stride=1):
        super().__init__()
        self.conv1 = nn.Conv2d(in_ch, out_ch, 3, stride=stride, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(out_ch)
        self.conv2 = nn.Conv2d(out_ch, out_ch, 3, stride=1, padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(out_ch)

        # 如果维度不匹配,需要1x1卷积调整
        self.shortcut = nn.Sequential()
        if stride != 1 or in_ch != out_ch:
            self.shortcut = nn.Sequential(
                nn.Conv2d(in_ch, out_ch, 1, stride=stride, bias=False),
                nn.BatchNorm2d(out_ch)
            )

    def forward(self, x):
        out = torch.relu(self.bn1(self.conv1(x)))
        out = self.bn2(self.conv2(out))
        out += self.shortcut(x)  # 残差连接
        out = torch.relu(out)
        return out

5.4 DenseNet与EfficientNet

DenseNet通过密集连接让每层都能直接访问前面所有层的特征图,实现了特征复用。EfficientNet通过复合缩放策略同时优化深度、宽度和分辨率,在参数效率和精度间取得了更好的平衡。

Python
# 使用torchvision加载预训练模型
import torchvision.models as models

# 加载预训练ResNet
resnet18 = models.resnet18(pretrained=True)
resnet50 = models.resnet50(pretrained=True)

# 加载预训练EfficientNet
efficientnet = models.efficientnet_b0(pretrained=True)

# 查看模型结构
print(f"ResNet18参数量: {sum(p.numel() for p in resnet18.parameters()) / 1e6:.1f}M")
print(f"ResNet50参数量: {sum(p.numel() for p in resnet50.parameters()) / 1e6:.1f}M")
print(f"EffNet-B0参数量: {sum(p.numel() for p in efficientnet.parameters()) / 1e6:.1f}M")

5.5 架构演进对比

架构年份关键创新深度ImageNet精度
LeNet-51998卷积+池化5—
AlexNet2012ReLU+Dropout+GPU883.6%
VGG-162014小卷积核堆叠1692.0%
ResNet-502015残差连接5094.8%
DenseNet-1212017密集连接12195.0%
EfficientNet-B02019复合缩放—95.1%

六、迁移学习

迁移学习利用在大型数据集(如ImageNet)上预训练的模型,通过微调适配到新任务。在数据量有限时尤其有效。

6.1 冻结特征提取器

Python
# 加载预训练ResNet,冻结特征提取器
model = models.resnet18(pretrained=True)

# 冻结所有参数
for param in model.parameters():
    param.requires_grad = False

# 替换分类头(新分类头默认可训练)
num_features = model.fc.in_features
model.fc = nn.Linear(num_features, 10)  # 10类分类

# 只训练分类头参数
optimizer = optim.Adam(model.fc.parameters(), lr=1e-3)

6.2 微调与渐进式解冻

Python
# 渐进式解冻:先训练分类头,再逐步解冻深层
def progressive_unfreeze(model, epoch, unfreeze_schedule):
    """根据epoch逐步解冻层"""
    if epoch in unfreeze_schedule:
        layers_to_unfreeze = unfreeze_schedule[epoch]
        for name, param in model.named_parameters():
            for layer_name in layers_to_unfreeze:
                if layer_name in name:
                    param.requires_grad = True
                    print(f"Unfroze: {name}")

# 调度:epoch 5解冻layer4,epoch 10解冻layer3
schedule = {
    5: ['layer4'],
    10: ['layer3'],
}

# 不同层使用不同学习率
optimizer = optim.Adam([
    {'params': model.fc.parameters(), 'lr': 1e-3},      # 分类头:高学习率
    {'params': model.layer4.parameters(), 'lr': 1e-4},  # 深层:低学习率
    {'params': model.layer3.parameters(), 'lr': 1e-5},  # 浅层:更低学习率
])
⚠ 迁移学习注意事项

1. 确保输入数据的预处理与预训练模型一致(resize、normalize)。2. 冻结参数后仍需前向传播,只是不计算梯度。3. BatchNorm层在冻结时应设为eval模式,防止running statistics被更新。

七、CIFAR-10完整实战

将前面所有知识整合,完成一个CIFAR-10图像分类的完整流程。

7.1 数据加载与预处理

Python
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import DataLoader

# 数据预处理:数据增强 + 归一化
transform_train = transforms.Compose([
    transforms.RandomCrop(32, padding=4),
    transforms.RandomHorizontalFlip(),
    transforms.ToTensor(),
    transforms.Normalize((0.4914, 0.4822, 0.4465),
                         (0.2470, 0.2435, 0.2616)),
])

transform_test = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.4914, 0.4822, 0.4465),
                         (0.2470, 0.2435, 0.2616)),
])

trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
                                        download=True, transform=transform_train)
testset = torchvision.datasets.CIFAR10(root='./data', train=False,
                                       download=True, transform=transform_test)

train_loader = DataLoader(trainset, batch_size=128, shuffle=True, num_workers=4)
test_loader = DataLoader(testset, batch_size=128, shuffle=False, num_workers=4)

7.2 模型构建

Python
class CIFARNet(nn.Module):
    def __init__(self, num_classes=10):
        super().__init__()
        self.features = nn.Sequential(
            # Block 1
            nn.Conv2d(3, 32, 3, padding=1),
            nn.BatchNorm2d(32),
            nn.ReLU(inplace=True),
            nn.Conv2d(32, 32, 3, padding=1),
            nn.BatchNorm2d(32),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(2, 2),

            # Block 2
            nn.Conv2d(32, 64, 3, padding=1),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
            nn.Conv2d(64, 64, 3, padding=1),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(2, 2),

            # Block 3
            nn.Conv2d(64, 128, 3, padding=1),
            nn.BatchNorm2d(128),
            nn.ReLU(inplace=True),
            nn.Conv2d(128, 128, 3, padding=1),
            nn.BatchNorm2d(128),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(2, 2),
        )
        self.classifier = nn.Sequential(
            nn.Dropout(0.5),
            nn.Linear(128 * 4 * 4, 256),
            nn.ReLU(inplace=True),
            nn.Dropout(0.5),
            nn.Linear(256, num_classes),
        )

    def forward(self, x):
        x = self.features(x)
        x = x.view(x.size(0), -1)
        x = self.classifier(x)
        return x

model = CIFARNet()
print(f"参数量: {sum(p.numel() for p in model.parameters()) / 1e6:.2f}M")

7.3 训练与评估

Python
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = model.to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.AdamW(model.parameters(), lr=1e-3, weight_decay=5e-4)
scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=100)

best_acc = 0.0
for epoch in range(100):
    # 训练
    model.train()
    train_loss = 0.0
    for inputs, targets in train_loader:
        inputs, targets = inputs.to(device), targets.to(device)
        outputs = model(inputs)
        loss = criterion(outputs, targets)
        optimizer.zero_grad()
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        optimizer.step()
        train_loss += loss.item()

    # 评估
    model.eval()
    correct, total = 0, 0
    with torch.no_grad():
        for inputs, targets in test_loader:
            inputs, targets = inputs.to(device), targets.to(device)
            outputs = model(inputs)
            _, predicted = outputs.max(1)
            total += targets.size(0)
            correct += predicted.eq(targets).sum().item()

    test_acc = 100. * correct / total
    scheduler.step()

    if test_acc > best_acc:
        best_acc = test_acc
        torch.save(model.state_dict(), 'cifar10_best.pth')

    print(f"Epoch {epoch+1}: Loss={train_loss/len(train_loader):.4f}, Acc={test_acc:.2f}%")

print(f"最佳准确率: {best_acc:.2f}%")
🎯 CNN类比

把CNN想象成一个层层递进的侦探:第一层卷积核像是在看简单的线索(边缘、颜色块);中间层将这些线索组合成更复杂的证据(纹理、形状部件);深层则能识别完整的物体(车轮、猫脸)。池化层像是侦探在"概括"信息——不需要每个像素的细节,只需要关键特征的位置。

八、本章小结

下一章将进入序列建模领域,讲解RNN/LSTM/GRU及其在自然语言处理中的应用。