Skip to content

CNN 卷积神经网络

CNN 通过局部感知权重共享,大幅减少参数量,是图像处理的标配。

flowchart LR
A[输入图像<br/>32×32×3] --> B[卷积层<br/>提取特征]
B --> C[池化层<br/>下采样]
C --> D[卷积层<br/>深层特征]
D --> E[池化层]
E --> F[全连接层<br/>分类]

卷积核在图像上滑动,每个位置做点积:

import torch.nn as nn
# 输入 3 通道,输出 16 通道,3×3 卷积核
conv = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, padding=1)
import torch
image = torch.randn(1, 3, 32, 32) # 一张 RGB 图片
output = conv(image)
print(f"输出: {output.shape}") # (1, 16, 32, 32)
pool = nn.MaxPool2d(kernel_size=2, stride=2)
pooled = pool(output)
print(f"池化后: {pooled.shape}") # (1, 16, 16, 16) — 尺寸减半
class LeNet(nn.Module):
def __init__(self):
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(1, 6, 5), nn.ReLU(),
nn.MaxPool2d(2),
nn.Conv2d(6, 16, 5), nn.ReLU(),
nn.MaxPool2d(2),
)
self.classifier = nn.Sequential(
nn.Linear(16*4*4, 120), nn.ReLU(),
nn.Linear(120, 84), nn.ReLU(),
nn.Linear(84, 10),
)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
return self.classifier(x)
架构年份核心贡献
LeNet1998卷积+池化+全连接
AlexNet2012ReLU+Dropout+GPU
ResNet2015残差连接,可训练 152 层