1. 内容来源
2. Pytorch实现
2.1 模型构建
AlexNet网络结构图(本文输入224*224,图中大小均需减一)如下:
总结网络结构如下:
- 卷积层1(输入1通道,输出96通道,11*11卷积核,4步长,1填充)-- 激活层1(ReLU)--最大池化层1(3*3核,2步长)
- 卷积层2(输入96通道,输出256通道,5*5卷积核,1步长,2填充)-- 激活层2(ReLU)--最大池化层2(3*3核,2步长)
- 卷积层3(输入256通道,输出384通道,3*3卷积核,1步长,1填充)-- 激活层3(ReLU)
- 卷积层4(输入384通道,输出384通道,3*3卷积核,1步长,1填充)-- 激活层4(ReLU)
- 卷积层5(输入384通道,输出256通道,3*3卷积核,1步长,1填充)-- 激活层5(ReLU)--最大池化层3(3*3核,2步长)
- 展开成单维向量
- 线性层1(输入6400维,输出4096维)-- 激活层6(ReLU)--Dropout层1(50%丢弃率)
- 线性层2(输入5096维,输出4096维)-- 激活层7(ReLU)--Dropout层2(50%丢弃率)
- 输出层(输入4096维,输出10维)
代码实现:
import torch
from torch import nn
from d2l import torch as d2l
net = nn.Sequential(
nn.Conv2d(1, 96, kernel_size=11, stride=4, padding=1), nn.ReLU(),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(96, 256, kernel_size=5, padding=2), nn.ReLU(),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(256, 384, kernel_size=3, padding=1), nn.ReLU(),
nn.Conv2d(384, 384, kernel_size=3, padding=1), nn.ReLU(),
nn.Conv2d(384, 256, kernel_size=3, padding=1), nn.ReLU(),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Flatten(),
nn.Linear(6400, 4096), nn.ReLU(), nn.Dropout(p=0.5),
nn.Linear(4096, 4096), nn.ReLU(), nn.Dropout(p=0.5),
nn.Linear(4096, 10)
)
维度打印:
Conv2d output shape : torch.Size([1, 96, 54, 54])
ReLU output shape : torch.Size([1, 96, 54, 54])
MaxPool2d output shape : torch.Size([1, 96, 26, 26])
Conv2d output shape : torch.Size([1, 256, 26, 26])
ReLU output shape : torch.Size([1, 256, 26, 26])
MaxPool2d output shape : torch.Size([1, 256, 12, 12])
Conv2d output shape : torch.Size([1, 384, 12, 12])
ReLU output shape : torch.Size([1, 384, 12, 12])
Conv2d output shape : torch.Size([1, 384, 12, 12])
ReLU output shape : torch.Size([1, 384, 12, 12])
Conv2d output shape : torch.Size([1, 256, 12, 12])
ReLU output shape : torch.Size([1, 256, 12, 12])
MaxPool2d output shape : torch.Size([1, 256, 5, 5])
Flatten output shape : torch.Size([1, 6400])
Linear output shape : torch.Size([1, 4096])
ReLU output shape : torch.Size([1, 4096])
Dropout output shape : torch.Size([1, 4096])
Linear output shape : torch.Size([1, 4096])
ReLU output shape : torch.Size([1, 4096])
Dropout output shape : torch.Size([1, 4096])
Linear output shape : torch.Size([1, 10])
2.2 模型训练
#Data
batch_size = 128
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size, resize=224)
#Train
lr, num_epochs = 0.01, 10
d2l.train_ch6(net, train_iter, test_iter, num_epochs, lr, d2l.try_gpu())
其中,为了与本系列中LeNet等模型进行性能对比,采用的Fashion Mnist数据集样本大小为28*28,本模型输入为224*224,需要拉伸(仅用于测试该网络,特征信息不会增加)
结果: