pytorch深度学习实践_p9_多分类问题_pytorch手写实现数字辨识

Posted L_halley

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了pytorch深度学习实践_p9_多分类问题_pytorch手写实现数字辨识相关的知识,希望对你有一定的参考价值。

pytorch手写实现数字辨识

知识点补充

  • view()
  • 在PyTorch中view函数作用为重构张量的维度,相当于numpy中的resize()的功能
  • torch.nn.CrossEntropyLoss()
  • 求交叉熵,并且其中嵌套了log 和softmax 函数 所以i神经网络最后一层不用再用softmax激活
  • torch.max(input, dim)

输入

  • input是softmax函数输出的一个tensor
  • dim是max函数索引的维度0/1,0是每列的最大值,1是每行的最大值

输出

  • 函数会返回两个tensor,第一个tensor是每行的最大值;第二个tensor是每行最大值的索引。

1、准备数据集

transform = transforms.Compose([    #撰写转换器
    transforms.ToTensor(), #数据转为向量
    transforms.Normalize((0.1307,), (0.3801, )) #将像素值规格化在(0, 1)之间,前者为均值,后者为方差,这两个值是在图像处理上经过大量数据得到的普遍值
])

train_dataset = datasets.MNIST(
    root = '../dataset/minist',
    train = True,
    download = True,
    transform = transform
)

train_loader = DataLoader(train_dataset,
                          shuffle=True, #训练数据打乱保证随机性
                          batch_size=64)

test_dataset = datasets.MNIST(
    root = '../dataset/minist',
    train = False,
    download = True,
    transform = transform
)

test_loader = DataLoader(train_dataset,
                          shuffle=False,    #测试集不打算保证结果直观性
                          batch_size=64)

2、构建神经网络

class Net(torch.nn.Module):
    def __init__(self):
        super(Net,self).__init__()
        self.l1 = torch.nn.Linear(784, 512)
        self.l2 = torch.nn.Linear(512, 256)
        self.l3 = torch.nn.Linear(256, 128)
        self.l4 = torch.nn.Linear(128, 64)
        self.l5 = torch.nn.Linear(64, 10)

    def forward(self, x):
        x = x.view(-1, 784)     #将x转为N*784的向量
        x = F.relu(self.l1(x))
        x = F.relu(self.l2(x))
        x = F.relu(self.l3(x))
        x = F.relu(self.l4(x))

        return self.l5(x)       #最后一层不做softmax,因为等会调用的交叉熵函数包含了softmax的过程


model = Net()

3、定义loss和optimizer

criterion = torch.nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5) #momentum:相当于赋予梯度惯性帮助跳出local minimal

4、训练

def train(epoch):
    runing_loss = 0.0
    for batch_idx, data in enumerate(train_loader,0):
        inputs, target = data
        optimizer.zero_grad()

        outputs = model(inputs)
        loss = criterion(outputs, target)
        loss.backward()
        optimizer.step()
        runing_loss += loss.item()

        if batch_idx % 300 == 299:
            print('[%d, %5d] loss: %.3f' % (epoch + 1, batch_idx +1, runing_loss / 300))
            runing_loss = 0.0

5、测试

def test():
    correct = 0
    total = 0
    with torch.no_grad():
        for data in test_loader:
            images, labels = data
            outputs = model(images)
            _, predicted = torch.max(outputs.data, dim=1)
            total += labels.size(0)
            correct += (predicted == labels).sum().item()
    print('Accuracy on test set: %d %%' % (100 * correct / total))

完整代码

import torch
from torchvision import transforms
from torchvision import datasets
from torch.utils.data import DataLoader
import torch.nn.functional as F
import torch.optim as optim

# 1、准备数据集

transform = transforms.Compose([    #撰写转换器
    transforms.ToTensor(), #数据转为向量
    transforms.Normalize((0.1307,), (0.3801, )) #将像素值规格化在(0, 1)之间,前者为均值,后者为方差,这两个值是在图像处理上经过大量数据得到的普遍值
])

train_dataset = datasets.MNIST(
    root = '../dataset/minist',
    train = True,
    download = True,
    transform = transform
)

train_loader = DataLoader(train_dataset,
                          shuffle=True, #训练数据打乱保证随机性
                          batch_size=64)

test_dataset = datasets.MNIST(
    root = '../dataset/minist',
    train = False,
    download = True,
    transform = transform
)

test_loader = DataLoader(train_dataset,
                          shuffle=False,    #测试集不打算保证结果直观性
                          batch_size=64)

# 2、构建神经网络

class Net(torch.nn.Module):
    def __init__(self):
        super(Net,self).__init__()
        self.l1 = torch.nn.Linear(784, 512)
        self.l2 = torch.nn.Linear(512, 256)
        self.l3 = torch.nn.Linear(256, 128)
        self.l4 = torch.nn.Linear(128, 64)
        self.l5 = torch.nn.Linear(64, 10)

    def forward(self, x):
        x = x.view(-1, 784)     #将x转为N*784的向量
        x = F.relu(self.l1(x))
        x = F.relu(self.l2(x))
        x = F.relu(self.l3(x))
        x = F.relu(self.l4(x))

        return self.l5(x)       #最后一层不做softmax,因为等会调用的交叉熵函数包含了softmax的过程


model = Net()

# 3、定义loss和optimizer

criterion = torch.nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5) #momentum:相当于赋予梯度惯性帮助跳出local minimal



# 4、训练

def train(epoch):
    runing_loss = 0.0
    for batch_idx, data in enumerate(train_loader,0):
        inputs, target = data
        optimizer.zero_grad()

        outputs = model(inputs)
        loss = criterion(outputs, target)
        loss.backward()
        optimizer.step()
        runing_loss += loss.item()

        if batch_idx % 300 == 299:
            print('[%d, %5d] loss: %.3f' % (epoch + 1, batch_idx +1, runing_loss / 300))
            runing_loss = 0.0

# 5、测试

def test():
    correct = 0
    total = 0
    with torch.no_grad():
        for data in test_loader:
            images, labels = data
            outputs = model(images)
            _, predicted = torch.max(outputs.data, dim=1)
            total += labels.size(0)
            correct += (predicted == labels).sum().item()
    print('Accuracy on test set: %d %%' % (100 * correct / total))


if __name__ == '__main__':
    for epoch in range(10):
        train(epoch)
        test()

以上是关于pytorch深度学习实践_p9_多分类问题_pytorch手写实现数字辨识的主要内容,如果未能解决你的问题,请参考以下文章

6.2 PyTorch图像的多分类--手写字体识别

Pytorch学习--编程实战:猫和狗二分类

PyTorch学习6《PyTorch深度学习实践》——加载数据集(Dataset and DataLoader)

8.1 PyTorch模型迁移

8.1 PyTorch模型迁移

4.5 PyTorch批量梯度下降