手写数字识别实战

步骤:

1.加载图片
2.建立模型
3.训练
4.预测

辅助函数,建立utils.py文件方便调用

from matplotlib import pyplot as plt
import torch
# 下降曲线绘制
def plot_curve(data):
    fig=plt.figure()
    plt.plot(range(len(data)),data,color='blue')
    plt.legend(['value'],loc='upper right')
    plt.xlabel('step')
    plt.ylabel('value')
    plt.show()

# 图片识别
def plot_image(img,label,name):

    fig=plt.figure()
    for i in range(6):
        plt.subplot(2,3,i+1)
        plt.tight_layout()
        plt.imshow(img[i][0] * 0.3081 + 0.1307, cmap='gray', interpolation='none')
        plt.title("{}:{}".format(name,label[i].item()))
        plt.xticks([])
        plt.yticks([])
    plt.show()

# 实现one_hot的编码
def one_hot(label,depth=10):
    out=torch.zeros(label.size(0),depth)
    idx=torch.LongStorage(label).view(-1,1)
    out.scatter_(dim=1,index=idx,value=1)
    return out

通过
1.加载图片
2.建立模型
3.训练
4.预测
编写代码

import torch
from bdong.utils import plot_image
import torch
from torch import nn
from torch.nn import functional as F
from torch import optim
import torchvision
from torch.nn.functional import one_hot
from utils import plot_curve,plot_image

# 并行处理图片大大节省计算时间,一次处理图片的数量
batch_size = 512
#step.1加载数据集load datas
# step1. load dataset
# 加载数据集,train表示测试还是训练,download为True表示没有这个数据会去网上去下载
# torchvision.transforms.ToTensor()数据转化
# torchvision.transforms.Normalize((0.1307,), (0.3081,))均匀分布在0附近
# shuffle=True随机打散
train_loader = torch.utils.data.DataLoader(
    torchvision.datasets.MNIST('mnist_data', train=True, download=True,
                               transform=torchvision.transforms.Compose([
                                   torchvision.transforms.ToTensor(),
                                   torchvision.transforms.Normalize(
                                       (0.1307,), (0.3081,))
                               ])),
    batch_size=batch_size, shuffle=True)

test_loader = torch.utils.data.DataLoader(
    torchvision.datasets.MNIST('mnist_data/', train=False, download=True,
                               transform=torchvision.transforms.Compose([
                                   torchvision.transforms.ToTensor(),
                                   torchvision.transforms.Normalize(
                                       (0.1307,), (0.3081,))
                               ])),
    batch_size=batch_size, shuffle=False)

x, y = next(iter(train_loader))
print(x.shape, y.shape, x.min(), x.max())
plot_image(x, y, 'image sample')


# Step2.
# 构建网络

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.fc1 = nn.Linear(28 * 28, 256)
        self.fc2 = nn.Linear(256, 64)
        self.fc3 = nn.Linear(64, 10)

    def forward(self, x):
        # img : [batch,1,28,28]
        # x : [batch,784]
        # h1 = relu(xw1 + b1)
        x = F.relu(self.fc1(x))
        # h2 = relu(h1w2 + b2)
        x = F.relu(self.fc2(x))
        # h3 = h2w3 + b3
        x = self.fc3(x)

        return x


# step3.
# 训练训练样本

net = Net()

# [w1,b1,w2,b2,w3,b3]
optimizer = optim.SGD(net.parameters(), lr=0.01, momentum=0.9)

train_loss = []
for epoch in range(3):
    for batch_idx, (x, y) in enumerate(train_loader):
        # x : [batch,1,28,28] y:[batch]
        # flatten [batch,1,28,28] - > [batch,feature]
        # x : [batch,784]
        x = x.view(x.size(0), 28 * 28)
        out = net(x)

        # one-hot
        y_onehot = one_hot(y,10)
        y_onehot=y_onehot.float()

        # loss : mse(out,y_onehot)
        loss = F.mse_loss(out, y_onehot)

        # 清零梯度
        optimizer.zero_grad()

        # 计算梯度
        loss.backward()

        # 更新梯度
        # w' = w - lr * grad
        optimizer.step()

        train_loss.append(loss.item())

        if batch_idx % 10 == 0:
            print(f"epoch:{epoch} step:{batch_idx} loss:{loss.item()}")

plot_curve(train_loss)
# we get optimal [w1,b1,w2,b2,w3,b3]

# Step4.
# 测试集验证
total_correct=0
for x,y in test_loader:
    x=x.view(x.size(0),28*28)
    out=net(x)
    # out[b,10]=>pred:[b]
    pred = out.argmax(dim=1)
    correct =pred.eq(y).sum().float().item()
    total_correct+=correct

total_num=len(test_loader.dataset)
acc=total_correct/total_num
print('test acc:',acc)

# 拿到一个test中的图片
x,y=next(iter(test_loader))
out=net(x.view(x.size(0),28*28))
pred=out.argmax(dim=1)
plot_image(x,pred,'test')

在这里插入图片描述
在这里插入图片描述

更全参考链接(显示每步结果)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值