1. LeNet-5 结构回顾

LeNet-5 是由 Yann LeCun 在 1998 年提出的,用于解决手写数字识别问题。其结构如下:

  • Input: 32x32 图像
  • C1: 卷积层 (6@28x28)
  • S2: 池化层 (6@14x14)
  • C3: 卷积层 (16@10x10)
  • S4: 池化层 (16@5x5)
  • C5/F6/Output: 全连接层

2. PyTorch 代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import torch.nn as nn
import torch.nn.functional as F

class LeNet5(nn.Module):
def __init__(self):
super(LeNet5, self).__init__()
self.conv1 = nn.Conv2d(1, 6, 5) # 1 input channel, 6 output, 5x5 kernel
self.pool1 = nn.AvgPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.pool2 = nn.AvgPool2d(2, 2)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)

def forward(self, x):
x = self.pool1(F.relu(self.conv1(x)))
x = self.pool2(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x

3. 训练要点

  1. 损失函数: CrossEntropyLoss
  2. 优化器: Adam or SGD
  3. 数据预处理: 归一化到 [-0.1, 1.175] (LeNet 原始建议)

本文为 [课程] 系列 Demo 实战文章。