|
''' |
|
LeNet5 in PyTorch |
|
|
|
LeNet5是由Yann LeCun等人在1998年提出的一个经典卷积神经网络模型。 |
|
主要用于手写数字识别,具有以下特点: |
|
1. 使用卷积层提取特征 |
|
2. 使用平均池化层降低特征维度 |
|
3. 使用全连接层进行分类 |
|
4. 网络结构简单,参数量少 |
|
|
|
网络架构: |
|
5x5 conv, 6 2x2 pool 5x5 conv, 16 2x2 pool FC 120 FC 84 FC 10 |
|
input(32x32x3) -> [conv1+relu+pool] --------> 28x28x6 -----> 14x14x6 -----> 10x10x16 -----> 5x5x16 -> 120 -> 84 -> 10 |
|
stride 1 stride 2 stride 1 stride 2 |
|
|
|
参考论文: |
|
[1] Y. LeCun, L. Bottou, Y. Bengio, and P. Haffner, "Gradient-based learning applied to document recognition," |
|
Proceedings of the IEEE, vol. 86, no. 11, pp. 2278-2324, Nov. 1998. |
|
''' |
|
|
|
import torch |
|
import torch.nn as nn |
|
import torch.nn.functional as F |
|
|
|
|
|
class ConvBlock(nn.Module): |
|
"""卷积块模块 |
|
|
|
包含: 卷积层 -> ReLU -> 最大池化层 |
|
|
|
Args: |
|
in_channels (int): 输入通道数 |
|
out_channels (int): 输出通道数 |
|
kernel_size (int): 卷积核大小 |
|
stride (int): 卷积步长 |
|
padding (int): 填充大小 |
|
""" |
|
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0): |
|
super(ConvBlock, self).__init__() |
|
self.conv = nn.Conv2d( |
|
in_channels=in_channels, |
|
out_channels=out_channels, |
|
kernel_size=kernel_size, |
|
stride=stride, |
|
padding=padding |
|
) |
|
self.relu = nn.ReLU(inplace=True) |
|
self.pool = nn.MaxPool2d(kernel_size=2, stride=2) |
|
|
|
def forward(self, x): |
|
"""前向传播 |
|
|
|
Args: |
|
x (torch.Tensor): 输入特征图 |
|
|
|
Returns: |
|
torch.Tensor: 输出特征图 |
|
""" |
|
x = self.conv(x) |
|
x = self.relu(x) |
|
x = self.pool(x) |
|
return x |
|
|
|
|
|
class LeNet5(nn.Module): |
|
'''LeNet5网络模型 |
|
|
|
网络结构: |
|
1. 卷积层1: 3通道输入,6个5x5卷积核,步长1 |
|
2. 最大池化层1: 2x2窗口,步长2 |
|
3. 卷积层2: 6通道输入,16个5x5卷积核,步长1 |
|
4. 最大池化层2: 2x2窗口,步长2 |
|
5. 全连接层1: 400->120 |
|
6. 全连接层2: 120->84 |
|
7. 全连接层3: 84->num_classes |
|
|
|
Args: |
|
num_classes (int): 分类数量,默认为10 |
|
init_weights (bool): 是否初始化权重,默认为True |
|
''' |
|
def __init__(self, num_classes=10, init_weights=True): |
|
super(LeNet5, self).__init__() |
|
|
|
|
|
self.conv1 = ConvBlock( |
|
in_channels=3, |
|
out_channels=6, |
|
kernel_size=5, |
|
stride=1 |
|
) |
|
|
|
|
|
self.conv2 = ConvBlock( |
|
in_channels=6, |
|
out_channels=16, |
|
kernel_size=5, |
|
stride=1 |
|
) |
|
|
|
|
|
self.classifier = nn.Sequential( |
|
nn.Linear(5*5*16, 120), |
|
nn.ReLU(inplace=True), |
|
nn.Linear(120, 84), |
|
nn.ReLU(inplace=True), |
|
nn.Linear(84, num_classes) |
|
) |
|
|
|
|
|
if init_weights: |
|
self._initialize_weights() |
|
|
|
def forward(self, x): |
|
'''前向传播 |
|
|
|
Args: |
|
x (torch.Tensor): 输入图像张量,[N,3,32,32] |
|
|
|
Returns: |
|
torch.Tensor: 输出预测张量,[N,num_classes] |
|
''' |
|
|
|
x = self.conv1(x) |
|
x = self.conv2(x) |
|
|
|
|
|
x = torch.flatten(x, 1) |
|
x = self.classifier(x) |
|
return x |
|
|
|
def _initialize_weights(self): |
|
'''初始化模型权重 |
|
|
|
采用kaiming初始化方法: |
|
- 卷积层权重采用kaiming_normal_初始化 |
|
- 线性层权重采用normal_初始化 |
|
- 所有偏置项初始化为0 |
|
''' |
|
for m in self.modules(): |
|
if isinstance(m, nn.Conv2d): |
|
|
|
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') |
|
if m.bias is not None: |
|
nn.init.zeros_(m.bias) |
|
elif isinstance(m, nn.Linear): |
|
|
|
nn.init.normal_(m.weight, 0, 0.01) |
|
nn.init.zeros_(m.bias) |
|
|
|
|
|
def test(): |
|
"""测试函数 |
|
|
|
创建模型并进行前向传播测试,打印模型结构和参数信息 |
|
""" |
|
|
|
net = LeNet5() |
|
print('Model Structure:') |
|
print(net) |
|
|
|
|
|
x = torch.randn(2,3,32,32) |
|
y = net(x) |
|
print('\nInput Shape:', x.shape) |
|
print('Output Shape:', y.shape) |
|
|
|
|
|
from torchinfo import summary |
|
device = 'cuda' if torch.cuda.is_available() else 'cpu' |
|
net = net.to(device) |
|
summary(net, (2,3,32,32)) |
|
|
|
|
|
if __name__ == '__main__': |
|
test() |
|
|