365天深度学习训练营-第P1周:实现mnist手写数字识别

文章目录

我的环境:

  • 语言环境:Python 3.7.13
  • 编译器:jupyter notebook
  • 深度学习环境:
  • torch==1.12.1+cu113、cuda==11.3.1
  • torchvision==0.13.1+cu113、cuda==11.3.1

一、前期工作

1. 设置 GPU

import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import torchvision

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

device
device(type='cuda')

2. 导入数据

train_ds = torchvision.datasets.MNIST('data',
                                      train=True,
                                      transform=torchvision.transforms.ToTensor(),
                                      download=True)

test_ds  = torchvision.datasets.MNIST('data',
                                      train=False,
                                      transform=torchvision.transforms.ToTensor(),
                                      download=True)
batch_size = 32

train_dl = torch.utils.data.DataLoader(train_ds,
                                       batch_size=batch_size,
                                       shuffle=True)

test_dl  = torch.utils.data.DataLoader(test_ds,
                                       batch_size=batch_size)

imgs, labels = next(iter(train_dl))
imgs.shape
torch.Size([32, 1, 28, 28])

3. 数据可视化

import numpy as np

plt.figure(figsize=(20, 5))
for i, imgs in enumerate(imgs[:20]):

    npimg = np.squeeze(imgs.numpy())

    plt.subplot(2, 10, i+1)
    plt.imshow(npimg, cmap=plt.cm.binary)
    plt.axis('off')

365天深度学习训练营-第P1周:实现mnist手写数字识别

二、构建简单的CNN网络

使用 image_dataset_from_directory 方法将磁盘中的数据加载到 tf.data.Dataset 中

import torch.nn.functional as F

num_classes = 10

class Model(nn.Module):
     def __init__(self):
        super().__init__()

        self.conv1 = nn.Conv2d(1, 32, kernel_size=3)
        self.pool1 = nn.MaxPool2d(2)
        self.conv2 = nn.Conv2d(32, 64, kernel_size=3)
        self.pool2 = nn.MaxPool2d(2)

        self.fc1 = nn.Linear(1600, 64)
        self.fc2 = nn.Linear(64, num_classes)

     def forward(self, x):
        x = self.pool1(F.relu(self.conv1(x)))
        x = self.pool2(F.relu(self.conv2(x)))

        x = torch.flatten(x, start_dim=1)

        x = F.relu(self.fc1(x))
        x = self.fc2(x)

        return x
from torchinfo import summary

model = Model().to(device)

summary(model)
=================================================================
Layer (type:depth-idx)                   Param
=================================================================
Model                                    --
├─Conv2d: 1-1                            320
├─MaxPool2d: 1-2                         --
├─Conv2d: 1-3                            18,496
├─MaxPool2d: 1-4                         --
├─Linear: 1-5                            102,464
├─Linear: 1-6                            650
=================================================================
Total params: 121,930
Trainable params: 121,930
Non-trainable params: 0
=================================================================

三、训练模型

1. 设置超参数

loss_fn    = nn.CrossEntropyLoss()
learn_rate = 1e-2
opt        = torch.optim.SGD(model.parameters(),lr=learn_rate)

2. 编写训练函数


def train(dataloader, model, loss_fn, optimizer):
    size = len(dataloader.dataset)
    num_batches = len(dataloader)

    train_loss, train_acc = 0, 0

    for X, y in dataloader:
        X, y = X.to(device), y.to(device)

        pred = model(X)
        loss = loss_fn(pred, y)

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        train_acc  += (pred.argmax(1) == y).type(torch.float).sum().item()
        train_loss += loss.item()

    train_acc  /= size
    train_loss /= num_batches

    return train_acc, train_loss

3. 编写测试函数

def test (dataloader, model, loss_fn):
    size        = len(dataloader.dataset)
    num_batches = len(dataloader)
    test_loss, test_acc = 0, 0

    with torch.no_grad():
        for imgs, target in dataloader:
            imgs, target = imgs.to(device), target.to(device)

            target_pred = model(imgs)
            loss        = loss_fn(target_pred, target)

            test_loss += loss.item()
            test_acc  += (target_pred.argmax(1) == target).type(torch.float).sum().item()

    test_acc  /= size
    test_loss /= num_batches

    return test_acc, test_loss

4. 正式训练

epochs     = 5
train_loss = []
train_acc  = []
test_loss  = []
test_acc   = []

for epoch in range(epochs):
    model.train()
    epoch_train_acc, epoch_train_loss = train(train_dl, model, loss_fn, opt)

    model.eval()
    epoch_test_acc, epoch_test_loss = test(test_dl, model, loss_fn)

    train_acc.append(epoch_train_acc)
    train_loss.append(epoch_train_loss)
    test_acc.append(epoch_test_acc)
    test_loss.append(epoch_test_loss)

    template = ('Epoch:{:2d}, Train_acc:{:.1f}%, Train_loss:{:.3f}, Test_acc:{:.1f}%,Test_loss:{:.3f}')
    print(template.format(epoch+1, epoch_train_acc*100, epoch_train_loss, epoch_test_acc*100, epoch_test_loss))
print('Done')
Epoch: 1, Train_acc:77.6%, Train_loss:0.744, Test_acc:91.1%,Test_loss:0.284
Epoch: 2, Train_acc:94.1%, Train_loss:0.196, Test_acc:96.2%,Test_loss:0.128
Epoch: 3, Train_acc:96.2%, Train_loss:0.123, Test_acc:97.5%,Test_loss:0.089
Epoch: 4, Train_acc:97.1%, Train_loss:0.094, Test_acc:97.4%,Test_loss:0.078
Epoch: 5, Train_acc:97.5%, Train_loss:0.078, Test_acc:98.0%,Test_loss:0.062
Done

四、结果可视化

import matplotlib.pyplot as plt

import warnings
warnings.filterwarnings("ignore")
plt.rcParams['font.sans-serif']    = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams['figure.dpi']         = 100

epochs_range = range(epochs)

plt.figure(figsize=(12, 3))
plt.subplot(1, 2, 1)

plt.plot(epochs_range, train_acc, label='Training Accuracy')
plt.plot(epochs_range, test_acc, label='Test Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')

plt.subplot(1, 2, 2)
plt.plot(epochs_range, train_loss, label='Training Loss')
plt.plot(epochs_range, test_loss, label='Test Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()

365天深度学习训练营-第P1周:实现mnist手写数字识别

五、用自己制作的图片进行预测

365天深度学习训练营-第P1周:实现mnist手写数字识别
for i in range(10):
    img_path = 'imgs/no' + str(i) + '.png'
    img = Image.open(img_path)
    img = img.convert('L')
    img = data_transform(img)
    img = torch.unsqueeze(img, dim=0)
    img = img.to(device)

    model.eval()
    with torch.no_grad():
        output = model(img)
        print(output.argmax(1).item())

预测结果:

0
1
2
3
4
5
6
7
8
9

Original: https://blog.csdn.net/lele_ne/article/details/127801624
Author: lele_ne
Title: 365天深度学习训练营-第P1周:实现mnist手写数字识别

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/660902/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球