写点什么

PyTorch 实现 Alexnet 图像分类

  • 2025-05-27
    上海
  • 本文字数:6342 字

    阅读完需:约 21 分钟

PyTorch 实现 Alexnet 图像分类

本文主要介绍了如何在昇腾上,使用 pytorch 对经典的 Alexnet 小模型在公开的 CIFAR10 数据集进行分类训练的实战讲解。内容包括 Alexnet 网络模型创新点介绍Alexnet 的网络架构剖析网络模型代码实战分析等等


本实验的目录结构安排如下所示:


  • Alexnet 网络模型创新点介绍

  • Alexnet 的网络架构剖析

  • 网络模型代码实战分析

Alexnet 网络模型创新点介绍

  • 使用 ReLU 作为 CNN 的激活函数,并验证其效果在较深的网络超过了 Sigmoid,成功解决了 Sigmoid 在网络较深时的梯度弥散问题。虽然 ReLU 激活函数在很久之前就被提出了,但是直到 AlexNet 的出现才将其发扬光大。

  • 训练时使用 Dropout 随机忽略一部分神经元,以避免模型过拟合。Dropout 虽有单独的论文论述,但是 AlexNet 将其实用化,通过实践证实了它的效果。在 AlexNet 中主要是最后几个全连接层使用了 Dropout。

  • 在 CNN 中使用重叠的最大池化。此前 CNN 中普遍使用平均池化,AlexNet 全部使用最大池化,避免平均池化的模糊化效果。并且 AlexNet 中提出让步长比池化核的尺寸小,这样池化层的输出之间会有重叠和覆盖,提升了特征的丰富性。

  • 提出了 LRN 层,对局部神经元的活动创建竞争机制,使得其中响应比较大的值变得相对更大,并抑制其他反馈较小的神经元,增强了模型的泛化能力。

  • 在训练过程中使用数据增强的方式扩充数据集,并增加泛化能力,该方法在后续多个分类模型中被复用。

Alexnet 的网络架构剖析


AlexNet 网络是由 Geoffrey 和他的学生 Alex 提出,并在 2012 年的 ILSVRC 竞赛中获得了第一名。整个网络共有 8 层结构,前 5 层为卷积层,后三层为全连接层,该网络是当时最深的卷积神经网络模型。


需要注意的是论文中给的输入是 224*224,而本实验训练的是 cifir 数据集,其图片大小为 32x32,因此在实际的训练过程中会将输入图片 resize 到 32x32,所以这里图片的输入 size 应为 32x32,图中给的 size 是按照 224 计算,因此在推算过程中需要将 224 改成 32 得到 cifar 数据集训练过程中的每一层实际输出大小。

Alexnet 网络代码实现分析

网络总共分为两大组成部分:5 个卷积层(池化)与 3 个全连接层。前两层卷积层与最后一层卷积层后接有池化层来对提取的特征图进行降维,后面连续接 3 个卷积层再对特征进行提取后再通过一个池化层对特征图进行降维。降维后通过'nn.Flatten'把一个数据拉成一维向量适配后面第二部分的全连接层。


后面三个全连接层用于分类,分别是将输出从'nn.Flatten'的输出减少至 9216、4608,最终到 10 也就是本实验要求的 cifar 数据集 10 分类任务中每一类别的预测概率。AlexNetModel 中'__init'函数中定义了网络模型需要的卷积层(conv1 到 conv5),中间穿插使用 pool 操作(max_pool1 到 max_pool5)对特征图进行降维。在'forward'函数中定义了整个网络前向传播过程,该前向传播过程与网络定义结构相对应,但是输入 size 对应维本文实验数据集中的 32x32 而不是 224x224.


import torchimport torch.nn as nn
class AlexNetModel(nn.Module): def __init__(self, **kwargs): super(AlexNetModel, self).__init__(**kwargs) # input:3x32x32, output:64*15*15 self.conv1 = nn.Sequential( nn.Conv2d(3, 64, kernel_size=4, stride=2), nn.ReLU(True) )
# input:64*15*15, output: 64*14*14 self.max_pool1 = nn.MaxPool2d(kernel_size=2, stride=1)
# input: 64*14*14 output:256*14*14 self.conv2 = nn.Sequential( nn.Conv2d(64, 256, kernel_size=3, padding=1), nn.ReLU(True) )
# input:256*14*14, output:256*7*7 self.max_pool2 = nn.MaxPool2d(kernel_size=2, stride=2)
# input:256*7*7, output:384*7*7 self.conv3 = nn.Sequential( nn.Conv2d(256, 384, kernel_size=3, padding=1), nn.ReLU(True) )
# input:384*7*7, output:384*7*7 self.conv4 = nn.Sequential( nn.Conv2d(384, 384, kernel_size=3, padding=1), # 384*7*7 nn.ReLU(True) )
# input:384*7*7, output:256*7*7 self.conv5 = nn.Sequential( nn.Conv2d(384, 256, kernel_size=3, padding=1), # 256*7*7 nn.ReLU(True) )
# input:256*7*7, output:256*6*6 self.max_pool3 = nn.MaxPool2d(kernel_size=2, stride=1)
# input:256*6*6, output:9216 self.flaten1 = nn.Flatten()
# input:9216, output:4608 self.fc1 = nn.Sequential( nn.Linear(9216, 4608), nn.ReLU(True), nn.Dropout(p=0.5) )
# input:4608, output:4608 self.fc2 = nn.Sequential( nn.Linear(4608, 4608), nn.ReLU(True), nn.Dropout(p=0.5) ) # input:4608, output:10 self.fc3 = nn.Linear(4608, 10) # 定义模型的前向计算,如何根据输入x计算返回所需要的模型输出 def forward(self, x): x = self.conv1(x) x = self.max_pool1(x) x = self.conv2(x) x = self.max_pool2(x) x = self.conv3(x) x = self.conv4(x) x = self.conv5(x) x = self.max_pool3(x) x = self.flaten1(x) x = self.fc1(x) x = self.fc2(x) x = self.fc3(x) return x
复制代码


将 Alexnet 网络模型打印出来可以看到,前面 conv1~5 是 5 个卷积层,卷积层后接入一个 flaten 层将高维的特征图进行降维以便于后续的三个全连接层进行连接。


print( AlexNetModel())
复制代码


AlexNetModel(  (conv1): Sequential(    (0): Conv2d(3, 64, kernel_size=(4, 4), stride=(2, 2))    (1): ReLU(inplace=True)  )  (max_pool1): MaxPool2d(kernel_size=2, stride=1, padding=0, dilation=1, ceil_mode=False)  (conv2): Sequential(    (0): Conv2d(64, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))    (1): ReLU(inplace=True)  )  (max_pool2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)  (conv3): Sequential(    (0): Conv2d(256, 384, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))    (1): ReLU(inplace=True)  )  (conv4): Sequential(    (0): Conv2d(384, 384, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))    (1): ReLU(inplace=True)  )  (conv5): Sequential(    (0): Conv2d(384, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))    (1): ReLU(inplace=True)  )  (max_pool3): MaxPool2d(kernel_size=2, stride=1, padding=0, dilation=1, ceil_mode=False)  (flaten1): Flatten(start_dim=1, end_dim=-1)  (fc1): Sequential(    (0): Linear(in_features=9216, out_features=4608, bias=True)    (1): ReLU(inplace=True)    (2): Dropout(p=0.5, inplace=False)  )  (fc2): Sequential(    (0): Linear(in_features=4608, out_features=4608, bias=True)    (1): ReLU(inplace=True)    (2): Dropout(p=0.5, inplace=False)  )  (fc3): Linear(in_features=4608, out_features=10, bias=True))
复制代码

Alexnet 网络用于 cifir 数据集分类实战

基于上述搭建好的网络模型,我们现在就可以正式来使用该模型开始训练 cifar 数据集。


导入昇腾 npu 相关库 transfer_to_npu、该模块可以使能模型自动迁移至昇腾上。


import torch_npu
复制代码


/home/pengyongrong/miniconda3/envs/AscendCExperiments/lib/python3.9/site-packages/torch_npu/dynamo/__init__.py:18: UserWarning: Register eager implementation for the 'npu' backend of dynamo, as torch_npu was not compiled with torchair.  warnings.warn(
复制代码


from torch_npu.contrib import transfer_to_npu
复制代码


torchvision 模块中集成了一些当今比较流行的数据集、模型架构和用于计算机视觉的常见图像转换功能,torchvision 模块中含有本次实验所需要的 CIFAR 数据集,因此导入该模块用于数据集的下载。tqdm 是用于训练过程中训练进度条,便于我们能够清晰的看到整个训练过程。


import torchvisionimport torchvision.transforms as transformsfrom 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/pengyongrong/workspace/cifarDatasat/', train=True, download=True, transform=transform_train)trainloader = torch.utils.data.DataLoader(    trainset, batch_size=128, shuffle=True)testset = torchvision.datasets.CIFAR10(    root='/home/pengyongrong/workspace/cifarDatasat/', train=False, download=True, transform=transform_test)testloader = torch.utils.data.DataLoader(    testset, batch_size=100, shuffle=False)
复制代码


Files already downloaded and verifiedFiles already downloaded and verified
复制代码


训练模块: 根据传入的迭代次数'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 optimdevice = 'npu'net = AlexNetModel()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)
复制代码
训练与测试的次数为 5 次,这里用户可以根据需要自行选择设置更高或更低,每个 epoch 的测试准确率都会被打印出来,如果不需要将代码注释掉即可。
for epoch in range(5):    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}')
复制代码


 26%|███████████████████▎                                                       | 101/391 [00:10<00:30,  9.56it/s]
[Epoch 1, Iteration 100] loss: 1.577[Epoch 1, Iteration 200] loss: 1.505[Epoch 1, Iteration 300] loss: 1.459
Test accuracy for AlexNet at epoch 1: 53.27%Epoch loss for AlexNet at epoch 1: 1.482[Epoch 2, Iteration 100] loss: 1.381[Epoch 2, Iteration 200] loss: 1.315

77%|█████████████████████████████████████████████████████████▋ | 301/391 [00:30<00:09, 9.92it/s]
[Epoch 2, Iteration 300] loss: 1.256Test accuracy for AlexNet at epoch 2: 59.23%Epoch loss for AlexNet at epoch 2: 1.296
[Epoch 3, Iteration 100] loss: 1.165[Epoch 3, Iteration 200] loss: 1.122[Epoch 3, Iteration 300] loss: 1.060Test accuracy for AlexNet at epoch 3: 64.63%Epoch loss for AlexNet at epoch 3: 1.097
[Epoch 4, Iteration 100] loss: 1.008[Epoch 4, Iteration 200] loss: 1.028[Epoch 4, Iteration 300] loss: 0.96Test accuracy for AlexNet at epoch 4: 70.41%Epoch loss for AlexNet at epoch 4: 0.984
[Epoch 5, Iteration 100] loss: 0.900[Epoch 5, Iteration 200] loss: 0.879[Epoch 5, Iteration 300] loss: 0.849Test accuracy for AlexNet at epoch 5: 71.80%Epoch loss for AlexNet at epoch 5: 0.877
复制代码



Reference

[1] Krizhevsky A, Sutskever I, Hinton G E. Imagenet classification with deep convolutional neural networks[J]. Advances in neural information processing systems, 2012, 25.


用户头像

还未添加个人签名 2024-12-19 加入

还未添加个人简介

评论

发布
暂无评论
PyTorch 实现 Alexnet图像分类_永荣带你玩转昇腾_InfoQ写作社区