前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >「深度学习一遍过」必修20:基于AlexNet的MNIST手写数字识别

「深度学习一遍过」必修20:基于AlexNet的MNIST手写数字识别

作者头像
荣仔_最靓的仔
发布2022-01-10 13:58:24
1.7K0
发布2022-01-10 13:58:24
举报

本专栏用于记录关于深度学习的笔记,不光方便自己复习与查阅,同时也希望能给您解决一些关于深度学习的相关问题,并提供一些微不足道的人工神经网络模型设计思路。 专栏地址:「深度学习一遍过」必修篇

目录

项目 GitHub 地址

项目心得

项目代码

项目 GitHub 地址

Classic_model_examples/2012_AlexNet_MNIST at main · zhao302014/Classic_model_examples · GitHub

https://github.com/zhao302014/Classic_model_examples/tree/main/2012_AlexNet_MNIST

项目心得

  • 2012 年——AlexNet:这是 2012 年 ImageNet 竞赛冠军获得者 Hinton 和他的学生 Alex Krizhevsky 设计的。该项目自己搭建了 AlexNet 网络并在 MNIST 手写数字识别项目中得到了应用。(注:MNIST 手写数字识别数据集是单通道的,在该项目中用 numpy 库将图片依次转换为 3 通道在进行处理)

项目代码

Image result for alexnet
Image result for alexnet

net.py

代码语言:javascript
复制
#!/usr/bin/python
# -*- coding:utf-8 -*-
# ------------------------------------------------- #
#      作者:赵泽荣
#      时间:2021年9月9日(农历八月初三)
#      个人站点:1.https://zhao302014.github.io/
#              2.https://blog.csdn.net/IT_charge/
#      个人GitHub地址:https://github.com/zhao302014
# ------------------------------------------------- #
import torch
from torch import nn
import torch.nn.functional as F

# --------------------------------------------------------------------------------- #
#  自己搭建一个 AlexNet 模型结构
#   · 提出时间:2012 年
#   · 比起 LeNet-5 具有更深的网络结构
#   · 使用 Dropout 抑制过拟合
#   · 使用 Relu 替换 LeNet-5 的 sigmoid 的作为激活函数
#   · 当年论文中提到使用多 GPU 进行训练,但现如今随着硬件性能提升,该代码使用单 GPU 进行训练
#   · 基准 AlexNet 截止到下述代码的 f8 层;由于本实例是手写数字识别(10分类问题),故再后续了一层全连接层
# --------------------------------------------------------------------------------- #
class MyAlexNet(nn.Module):
    def __init__(self):
        super(MyAlexNet, self).__init__()
        self.c1 = nn.Conv2d(in_channels=3, out_channels=48, kernel_size=11, stride=4, padding=2)    # (224 - 11 + 2*2) / 4 + 1 = 55
        self.ReLU = nn.ReLU()
        self.c2 = nn.Conv2d(in_channels=48, out_channels=128, kernel_size=5, stride=1, padding=2)   # (55 - 5 + 2*2) / 1 + 1 = 55
        self.s2 = nn.MaxPool2d(2)
        self.c3 = nn.Conv2d(in_channels=128, out_channels=192, kernel_size=3, stride=1, padding=1)  # (27 - 3 + 2*1) / 1 + 1 = 27
        self.s3 = nn.MaxPool2d(2)
        self.c4 = nn.Conv2d(in_channels=192, out_channels=192, kernel_size=3, stride=1, padding=1)  # (13 - 3 + 2*1) / 1 + 1 = 13
        self.c5 = nn.Conv2d(in_channels=192, out_channels=128, kernel_size=3, stride=1, padding=1)  # (13 - 3 + 2*1) / 1 + 1 = 13
        self.s5 = nn.MaxPool2d(kernel_size=3, stride=2)
        self.flatten = nn.Flatten()
        self.f6 = nn.Linear(4608, 2048)
        self.f7 = nn.Linear(2048, 2048)
        self.f8 = nn.Linear(2048, 1000)
        # 为满足该实例另加 ↓
        self.f9 = nn.Linear(1000, 10)

    def forward(self, x):                   # 输入shape: torch.Size([1, 3, 224, 224])
        x = self.ReLU(self.c1(x))           # shape: torch.Size([1, 48, 55, 55])
        x = self.ReLU(self.c2(x))           # shape: torch.Size([1, 128, 55, 55])
        x = self.s2(x)                      # shape: torch.Size([1, 128, 27, 27])
        x = self.ReLU(self.c3(x))           # shape: torch.Size([1, 192, 27, 27])
        x = self.s3(x)                      # shape: torch.Size([1, 192, 13, 13])
        x = self.ReLU(self.c4(x))           # shape: torch.Size([1, 192, 13, 13])
        x = self.ReLU(self.c5(x))           # shape: torch.Size([1, 128, 13, 13])
        x = self.s5(x)                      # shape: torch.Size([1, 128, 6, 6])
        x = self.flatten(x)                 # shape: torch.Size([1, 4608])
        x = self.f6(x)                      # shape: torch.Size([1, 2048])
        x = F.dropout(x, p=0.5)             # shape: torch.Size([1, 2048])
        x = self.f7(x)                      # shape: torch.Size([1, 2048])
        x = F.dropout(x, p=0.5)             # shape: torch.Size([1, 2048])
        x = self.f8(x)                      # shape: torch.Size([1, 1000])
        x = F.dropout(x, p=0.5)             # shape: torch.Size([1, 1000])
        # 为满足该实例另加 ↓(仍然使用 dropout 防止过拟合)
        x = self.f9(x)                      # shape: torch.Size([1, 10])
        x = F.dropout(x, p=0.5)             # shape: torch.Size([1, 10])
        return x


if __name__ == '__main__':
    x = torch.rand([1, 3, 224, 224])
    model = MyAlexNet()
    y = model(x)

train.py

代码语言:javascript
复制
#!/usr/bin/python
# -*- coding:utf-8 -*-
# ------------------------------------------------- #
#      作者:赵泽荣
#      时间:2021年9月9日(农历八月初三)
#      个人站点:1.https://zhao302014.github.io/
#              2.https://blog.csdn.net/IT_charge/
#      个人GitHub地址:https://github.com/zhao302014
# ------------------------------------------------- #
import torch
from torch import nn
from net import MyAlexNet
import numpy as np
from torch.optim import lr_scheduler
from torchvision import datasets, transforms

data_transform = transforms.Compose([
    transforms.Scale(224),    # 缩放图像大小为 224*224
    transforms.ToTensor()     # 仅对数据做转换为 tensor 格式操作
])

# 加载训练数据集
train_dataset = datasets.MNIST(root='./data', train=True, transform=data_transform, download=True)
# 给训练集创建一个数据集加载器
train_dataloader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=16, shuffle=True)
# 加载测试数据集
test_dataset = datasets.MNIST(root='./data', train=False, transform=data_transform, download=True)
# 给测试集创建一个数据集加载器
test_dataloader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=16, shuffle=True)

# 如果显卡可用,则用显卡进行训练
device = "cuda" if torch.cuda.is_available() else 'cpu'

# 调用 net 里定义的模型,如果 GPU 可用则将模型转到 GPU
model = MyAlexNet().to(device)

# 定义损失函数(交叉熵损失)
loss_fn = nn.CrossEntropyLoss()
# 定义优化器(SGD:随机梯度下降)
optimizer = torch.optim.SGD(model.parameters(), lr=1e-3, momentum=0.9)
# 学习率每隔 10 个 epoch 变为原来的 0.1
lr_scheduler = lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.1)

# 定义训练函数
def train(dataloader, model, loss_fn, optimizer):
    loss, current, n = 0.0, 0.0, 0
    for batch, (X, y) in enumerate(dataloader):
        # 单通道转为三通道
        X = np.array(X)
        X = X.transpose((1, 0, 2, 3))             # array 转置
        image = np.concatenate((X, X, X), axis=0)
        image = image.transpose((1, 0, 2, 3))     # array 转置回来
        image = torch.tensor(image)               # 将 numpy 数据格式转为 tensor
        # 前向传播
        image, y = image.to(device), y.to(device)
        output = model(image)
        cur_loss = loss_fn(output, y)
        _, pred = torch.max(output, axis=1)
        cur_acc = torch.sum(y == pred) / output.shape[0]
        # 反向传播
        optimizer.zero_grad()
        cur_loss.backward()
        optimizer.step()
        loss += cur_loss.item()
        current += cur_acc.item()
        n = n + 1
    print('train_loss:' + str(loss / n))
    print('train_acc:' + str(current / n))

# 定义测试函数
def test(dataloader, model, loss_fn):
    # 将模型转换为验证模式
    model.eval()
    loss, current, n = 0.0, 0.0, 0
    # 非训练,推理期用到(测试时模型参数不用更新,所以 no_grad)
    with torch.no_grad():
        for batch, (X, y) in enumerate(dataloader):
            # 单通道转为三通道
            X = np.array(X)
            X = X.transpose((1, 0, 2, 3))  # array 转置
            image = np.concatenate((X, X, X), axis=0)
            image = image.transpose((1, 0, 2, 3))  # array 转置回来
            image = torch.tensor(image)  # 将 numpy 数据格式转为 tensor
            image, y = image.to(device), y.to(device)
            output = model(image)
            cur_loss = loss_fn(output, y)
            _, pred = torch.max(output, axis=1)
            cur_acc = torch.sum(y == pred) / output.shape[0]
            loss += cur_loss.item()
            current += cur_acc.item()
            n = n + 1
        print('test_loss:' + str(loss / n))
        print('test_acc:' + str(current / n))

# 开始训练
epoch = 100
for t in range(epoch):
    lr_scheduler.step()
    print(f"Epoch {t + 1}\n----------------------")
    train(train_dataloader, model, loss_fn, optimizer)
    test(test_dataloader, model, loss_fn)
    torch.save(model.state_dict(), "save_model/{}model.pth".format(t))    # 模型保存
print("Done!")

test.py

代码语言:javascript
复制
#!/usr/bin/python
# -*- coding:utf-8 -*-
# ------------------------------------------------- #
#      作者:赵泽荣
#      时间:2021年9月9日(农历八月初三)
#      个人站点:1.https://zhao302014.github.io/
#              2.https://blog.csdn.net/IT_charge/
#      个人GitHub地址:https://github.com/zhao302014
# ------------------------------------------------- #
import torch
from net import MyAlexNet
import numpy as np
from torch.autograd import Variable
from torchvision import datasets, transforms
from torchvision.transforms import ToPILImage

data_transform = transforms.Compose([
    transforms.Scale(224),     # 缩放图像大小为 224*224
    transforms.ToTensor()      # 仅对数据做转换为 tensor 格式操作
])

# 加载训练数据集
train_dataset = datasets.MNIST(root='./data', train=True, transform=data_transform, download=True)
# 给训练集创建一个数据集加载器
train_dataloader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=16, shuffle=True)
# 加载测试数据集
test_dataset = datasets.MNIST(root='./data', train=False, transform=data_transform, download=True)
# 给测试集创建一个数据集加载器
test_dataloader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=16, shuffle=True)

# 如果显卡可用,则用显卡进行训练
device = "cuda" if torch.cuda.is_available() else 'cpu'

# 调用 net 里定义的模型,如果 GPU 可用则将模型转到 GPU
model = MyAlexNet().to(device)
# 加载 train.py 里训练好的模型
model.load_state_dict(torch.load("./save_model/99model.pth"))

# 获取预测结果
classes = [
    "0",
    "1",
    "2",
    "3",
    "4",
    "5",
    "6",
    "7",
    "8",
    "9",
]

# 把 tensor 转成 Image,方便可视化
show = ToPILImage()
# 进入验证阶段
model.eval()
# 对 test_dataset 里 10000 张手写数字图片进行推理
for i in range(len(test_dataset)):
    x, y = test_dataset[i][0], test_dataset[i][1]
    # tensor格式数据可视化
    show(x).show()
    # 扩展张量维度为 4 维
    x = Variable(torch.unsqueeze(x, dim=0).float(), requires_grad=False).to(device)
    # 单通道转为三通道
    x = x.cpu()
    x = np.array(x)
    x = x.transpose((1, 0, 2, 3))          # array 转置
    x = np.concatenate((x, x, x), axis=0)
    x = x.transpose((1, 0, 2, 3))      # array 转置回来
    x = torch.tensor(x).to(device)   # 将 numpy 数据格式转为 tensor,并转回 cuda 格式
    with torch.no_grad():
        pred = model(x)
        # 得到预测类别中最高的那一类,再把最高的这一类对应classes中的哪一个标签
        predicted, actual = classes[torch.argmax(pred[0])], classes[y]
        # 最终输出预测值与真实值
        print(f'Predicted: "{predicted}", Actual: "{actual}"')
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-09-09 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 项目 GitHub 地址
  • 项目心得
  • 项目代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档