使用CNN完成对MNIST数据集的数字识别

import torch
import torch.nn as nn
import torch.utils.data as Data
import torchvision
import matplotlib.pyplot as plt

# Hyper Parameters 超参数
EPOCH = 1
BATCH_SIZE = 50
LR = 0.001
DOWNLOAD_MNIST = True

train_data = torchvision.datasets.MNIST(
    root='./mnist',
    train=True,
    transform=torchvision.transforms.ToTensor(),  # 像素值(0, 255) --> (0, 1)
    download=DOWNLOAD_MNIST
)

# plot one example
print(train_data.data.size())
print(train_data.targets.size())
plt.imshow(train_data.data[0], cmap='gray')
plt.title('%i' % train_data.targets[0])
plt.show()

在这里插入图片描述
在超参数中DOWNLOAD_MNIST = True语句在初次通过torchvision下载数据集的时候设置为True,在下载到根目录的mnist文件夹之后,改为False。

train=True为下载训练集,在为False的时候为下载测试集。

transform=torchvision.transforms.ToTensor()的目的是将每个像素点的值(0到255之间)压缩到0和1之间,并且转换为可以使用的tensor的形式。
完整代码:

import torch
import torch.nn as nn
import torch.utils.data as Data
import torchvision
import matplotlib.pyplot as plt

# Hyper Parameters 超参数
EPOCH = 1
BATCH_SIZE = 50
LR = 0.001
DOWNLOAD_MNIST = False

train_data = torchvision.datasets.MNIST(
    root='./mnist',
    train=True,
    transform=torchvision.transforms.ToTensor(),  # 像素值(0, 255) --> (0, 1)
    download=DOWNLOAD_MNIST
)

# plot one example
# print(train_data.data.size())  #  (60000, 28, 28)
# print(train_data.targets.size())  #  (60000)
# plt.imshow(train_data.data[0], cmap='gray')
# plt.title('%i' % train_data.targets[0])
# plt.show()

train_loader = Data.DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True, num_workers=0)

test_data = torchvision.datasets.MNIST(root='./mnist/', train=False)
test_x = torch.unsqueeze(test_data.data, dim=1).type(torch.FloatTensor)[:2000]/255.
test_y = test_data.targets[:2000]

class CNN(nn.Module):
    def __init__(self):
        super(CNN, self).__init__()
        self.conv1 = nn.Sequential(
            nn.Conv2d(    # (1, 28, 28)
                in_channels=1,
                out_channels=16,
                kernel_size=5,
                stride=1,
                padding=2  # if stride = 1, padding = (kernel_size-1)/2
            ),  # --> (16, 28, 28)
            nn.ReLU(),  # --> (16, 28, 28)
            nn.MaxPool2d(kernel_size=2)  # --> (16, 14, 14)
        )
        self.conv2 = nn.Sequential(    # (16, 14, 14)
            nn.Conv2d(16, 32, 5, 1, 2),  # --> (32, 14, 14)
            nn.ReLU(),    # --> (32, 14, 14)
            nn.MaxPool2d(2)  # --> (32, 7, 7)
        )
        self.out = nn.Linear(32*7*7, 10)

    def forward(self, x):
        x = self.conv1(x)
        x = self.conv2(x)  # (batch, 32, 7, 7)
        x = x.view(x.size(0), -1)  # (batch, 32*7*7)
        output = self.out(x)  # (batch, 10)
        return output

cnn = CNN()
print(cnn)  # 打印整个网络
optimizer = torch.optim.Adam(cnn.parameters(), lr=LR)  # 使用adam优化器
loss_func = nn.CrossEntropyLoss()  # 损失函数使用交叉熵误差

# training and testing
for epoch in range(EPOCH):
    for step, (b_x, b_y) in enumerate(train_loader):  # 以1200个batch的方式传入(batch=50)
        output = cnn(b_x)
        loss = loss_func(output, b_y)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if step % 50 == 0:
            test_output = cnn(test_x)
            pred_y = torch.max(test_output, 1)[1].data.squeeze()
            accuracy = (pred_y == test_y).sum().item() / test_y.size(0)
            print('epoch: ', epoch, '| train loss: %.4f' % loss.data.item(), '| test accuracy: %.2f' % accuracy)


# 使用训练好的参数进行十个测试数据的预测
test_output = cnn(test_x[:10])
pred_y = torch.max(test_output, 1)[1].data.squeeze()
print(pred_y, 'prediction number')
print(test_y[:10], 'real number')

运行结果:

CNN(
  (conv1): Sequential(
    (0): Conv2d(1, 16, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))
    (1): ReLU()
    (2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (conv2): Sequential(
    (0): Conv2d(16, 32, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))
    (1): ReLU()
    (2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (out): Linear(in_features=1568, out_features=10, bias=True)
)
epoch:  0 | train loss: 2.3022 | test accuracy: 0.11
epoch:  0 | train loss: 0.5351 | test accuracy: 0.85
epoch:  0 | train loss: 0.5173 | test accuracy: 0.90
epoch:  0 | train loss: 0.2470 | test accuracy: 0.91
epoch:  0 | train loss: 0.1218 | test accuracy: 0.93
epoch:  0 | train loss: 0.0732 | test accuracy: 0.94
epoch:  0 | train loss: 0.1647 | test accuracy: 0.96
epoch:  0 | train loss: 0.1772 | test accuracy: 0.96
epoch:  0 | train loss: 0.0584 | test accuracy: 0.96
epoch:  0 | train loss: 0.0753 | test accuracy: 0.95
epoch:  0 | train loss: 0.1045 | test accuracy: 0.97
epoch:  0 | train loss: 0.0886 | test accuracy: 0.97
epoch:  0 | train loss: 0.1247 | test accuracy: 0.97
epoch:  0 | train loss: 0.1307 | test accuracy: 0.97
epoch:  0 | train loss: 0.1348 | test accuracy: 0.97
epoch:  0 | train loss: 0.0319 | test accuracy: 0.97
epoch:  0 | train loss: 0.0219 | test accuracy: 0.98
epoch:  0 | train loss: 0.0282 | test accuracy: 0.98
epoch:  0 | train loss: 0.1397 | test accuracy: 0.98
epoch:  0 | train loss: 0.0434 | test accuracy: 0.98
epoch:  0 | train loss: 0.0904 | test accuracy: 0.97
epoch:  0 | train loss: 0.1232 | test accuracy: 0.97
epoch:  0 | train loss: 0.0268 | test accuracy: 0.98
epoch:  0 | train loss: 0.1843 | test accuracy: 0.98
tensor([7, 2, 1, 0, 4, 1, 4, 9, 5, 9]) prediction number
tensor([7, 2, 1, 0, 4, 1, 4, 9, 5, 9]) real number

由于训练和测试过程只执行了一个epoch,所以epoch一直为0。

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值