PyTorch 实现 Vggnet图像分类
本实验主要介绍了如何在昇腾上,使用pytorch对经典的Vggnet模型在公开的CIFAR10数据集进行分类训练的实战讲解。内容包括Vggnet模型创新点介绍、Vggnet网络架构剖析与Vgg网络模型代码实战分析等等。
本实验的目录结构安排如下所示:
- Vggnet网络模型创新点介绍
- Vggnet的网络架构剖析
- Vggnet网络模型代码实现分析
- Vggnet网络用于cifar数据集分类实战
Vggnet网络模型创新点介绍
- vgg采用小卷积核堆叠来达到大卷积核的方式,与大卷积核达到相同效果的同时产生的参数更小。
- 相比于alexnet的池化层采用size=3的池化核,vgg池化层采用size=2的池化核,能够更有效地提取特征。
- 有11、13、16与19层四种可选层数的网络结构,Vgg网络的层数更深。
Vggnet的网络架构剖析
VGGNet的网络结构由多个卷积层和池化层组成,最后接三个全连接层经softmax输出。VGGNet有多个变种,包括VGG11、VGG13、VGG16和VGG19,数字代表网络的层数,分别对应图中从左到右的A(A_LRN)、B、C(D)与E。
本次实验以实现VGG11网络为例进行介绍,其包含8个卷积层和5个池化层,其配置如下:输入层为224x224x3的彩色图像;经过多个3x3的卷积核和ReLU激活函数;最大池化层使用2x2的窗口和步长为2;最后是三个全连接层,分别包含4096、4096和1000个神经元,最后一个全连接层使用softmax激活函数。
注意本文实现的任务是cifir 10分类任务,因此后续三个全连接层不是4096与1000,而是改成了512与10。
VGGNet的创新点和影响主要体现在其深度和网络结构的创新上,VGGNet是首批将图像分类错误率降到10%以内的模型之一,证明了增加网络的深度能够显著提升性能。此外,VGGNet在2014年的ILSVRC竞赛中取得了优异成绩,推动了深度卷积网络在计算机视觉领域的发展。
Vggnet网络代码实现分析
通过对VGG系列整体架构的分析发现,网络差异模块在图中均已用红框标出;从图中分析不难发现差异点在于每一个框内卷积层数不等,但是每一块中卷积层的卷积核与通道数均是相等的。
基于此,代码实现可以通过定义一个'blockVGG'函数,通过入参'covLayerNum'来构建组件不同卷积块。
import torch
import torch.nn as nn
def blockVGG(covLayerNum, inputChannel, outputChannel, kernelSize):
layer = nn.Sequential()
layer.add_module('conv2D1', nn.Conv2d(inputChannel, outputChannel, kernelSize, padding=1))
layer.add_module('relu-1', nn.ReLU())
layer.add_module('Dropout0', nn.Dropout(0.5))
for i in range(covLayerNum - 1):
layer.add_module('conv2D{}'.format(i), nn.Conv2d(outputChannel, outputChannel, kernelSize, padding=1))
layer.add_module('relu{}'.format(i), nn.ReLU())
layer.add_module('Dropout{}'.format(i + 1), nn.Dropout(0.5)) # Dropout to solve over-fit problem
layer.add_module('max-pool', nn.MaxPool2d(2, 2))
return layer
在blockVGG基础模块已经定义好的基础上,结合VGG模型网络图,我们可以定义一个VGG11网络,总共定义了5个'blockVGG'块分别用'layer1~5'表示。需要注意的是在论文的全连接层中定义的是三层,而'layer6'中这里全连接层中只定义了两层,这是因为在送入到网络全连接层以前经过了'view',该操作相当于将卷积层的输入进行了resize操作,该操作减少了参数量的同时又能够使网络可以适配任意size的图形输入,但是这样操作可能会带来精度的损失(用户可以根据实际实验情况,动态修改验证效果,这里不作进一步的讨论)。
class VGG11(nn.Module):
def __init__(self):
super().__init__()
self.layer1 = blockVGG(1, 3, 64, 3)
self.layer2 = blockVGG(1, 64, 128, 3)
self.layer3 = blockVGG(2, 128, 256, 3)
self.layer4 = blockVGG(2, 256, 512, 3)
self.layer5 = blockVGG(2, 512, 512, 3)
self.layer6 = nn.Sequential(
nn.Linear(512, 100),
nn.ReLU(),
nn.Linear(100, 10),
)
def forward(self, x: torch.Tensor):
# 执行卷积神经网络部分
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.layer5(x)
# 执行全连接部分
x = x.view(x.shape[0], -1)
x = self.layer6(x)
return x
Vggnet网络用于cifir数据集分类实战
基于上述搭建好的网络模型,我们现在就可以正式来使用该模型开始训练cifir数据集。
导入昇腾npu相关库transfer_to_npu、该模块可以使能模型自动迁移至昇腾上。
import torch_npu
from torch_npu.contrib import transfer_to_npu
torchvision模块中集成了一些当今比较流行的数据集、模型架构和用于计算机视觉的常见图像转换功能,torchvision模块中含有本次实验所需要的CIFAR数据集,因此导入该模块用于数据集的下载。tqdm是用于训练过程中训练进度条,便于我们能够清晰的看到整个训练过程。
import torchvision
import torchvision.transforms as transforms
from tqdm import tqdm
数据集预处理功能定义: 对图像数据集进行不同程度的变化,包括裁剪、翻转等方式增加数据的多样性,防止过拟合现象的出现,以增强模型的泛化能力。
调用了torchvision中的transform库中的compose方法,使用裁剪(RandomCrop)、翻转(RandomHorizontalFlip)等组合成tensor形式后并对tensor进行正则化(Normalize)。
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
cifar数据集共有60000张彩色图像,这些图像是32*32,分为10个类,每类6000张图。有50000张用于训练,构成了5个训练批,每一批10000张图;另外10000用于测试,单独构成一批。测试批的数据里,取自10类中的每一类,每一类随机取1000张。抽剩下的就随机排列组成了训练批。注意一个训练批中的各类图像并不一定数量相同,总的来看训练批,每一类都有5000张图。
数据集加载: torchvision中集成了一些通用的开源数据集,其中也包含cifar,此处通过torchvision函数加载cifar数据集到工作目录上的指定路径,如果已经下载好了,会直接校验通过,不会二次进行下载。
trainset = torchvision.datasets.CIFAR10(
root='/home/ma-user/work/resnet50Experiments/dataset/cifar-10-batches-py', train=True, download=True, transform=transform_train)
trainloader = torch.utils.data.DataLoader(
trainset, batch_size=128, shuffle=True)
testset = torchvision.datasets.CIFAR10(
root='/home/ma-user/work/resnet50Experiments/dataset/cifar-10-batches-py', train=False, download=True, transform=transform_test)
testloader = torch.utils.data.DataLoader(
testset, batch_size=100, shuffle=False)
classes = ('plane', 'car', 'bird', 'cat', 'deer',
'dog', 'frog', 'horse', 'ship', 'truck')
训练模块: 根据传入的迭代次数'epoch'开始训练网络模型,这里需要在model开始前加入'net.train()',使用随机梯度下降算法是将梯度值初始化为0('zero_grad()'),计算梯度、通过梯度下降算法更新模型参数的值以及统计每次训练后的loss值(每隔100次打印一次)。
def train(epoch):
net.train()
train_loss = 0.0
epoch_loss = 0.0
for batch_idx, (inputs, targets) in enumerate(tqdm(trainloader, 0)):
inputs, targets = inputs.to(device), targets.to(device)
optimizer.zero_grad()
outputs = net(inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
lr_scheduler.step()
train_loss += loss.item()
epoch_loss += loss.item()
if batch_idx % 100 == 99: # 每100次迭代打印一次损失
print(f'[Epoch {epoch + 1}, Iteration {batch_idx + 1}] loss: {train_loss / 100:.3f}')
train_loss = 0.0
return epoch_loss / len(trainloader)
测试模块: 每训练一轮将会对最新得到的训练模型效果进行测试,使用的是数据集准备时期划分得到的测试集,每类约为1000张。
def test():
net.eval()
test_loss = 0
correct = 0
total = 0
with torch.no_grad():
for batch_idx, (inputs, targets) in enumerate(tqdm(testloader)):
inputs, targets = inputs.to(device), targets.to(device)
outputs = net(inputs)
loss = criterion(outputs, targets)
test_loss += loss.item()
_, predicted = outputs.max(1)
total += targets.size(0)
correct += predicted.eq(targets).sum().item()
return 100 * correct / total
主功能调用模块: 该模块用于开启模型在指定数据集(cifar)上训练,其中定义了硬件设备为昇腾npu(device = 'npu'),定义了损失函数为交叉熵损失'CrossEntropyLoss()',梯度下降优化算法为SGD并同时指定了学习率等参数。
import torch.optim as optim
device = 'npu'
net = VGG11()
net = net.to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=1.0, weight_decay=5e-4)
lr_scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer,0.1,steps_per_epoch=len(trainloader),
epochs=150,div_factor=25,final_div_factor=10000,pct_start=0.3)
训练与测试的次数为60次,这里用户可以根据需要自行选择设置更高或更低,每个epoch的测试准确率都会被打印出来,如果不需要将代码注释掉即可。
for epoch in range(60):
epoch_loss = train(epoch)
test_accuray = test()
print(f'\nTest accuracy for AlexNet at epoch {epoch + 1}: {test_accuray:.2f}%')
print(f'Epoch loss for AlexNet at epoch {epoch + 1}: {epoch_loss:.3f}')
Reference
[1] Simonyan K, Zisserman A. Very deep convolutional networks for large-scale image recognition[J]. arXiv preprint arXiv:1409.1556, 2014.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。