PyTorch手写数字数据集进行多分类

作者:心?升明月 时间:2022-10-18 22:29:23 

一、实现过程

本文对经典手写数字数据集进行多分类,损失函数采用交叉熵,激活函数采用ReLU,优化器采用带有动量的mini-batchSGD算法。

所有代码如下:

0、导包

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

1、准备数据

batch_size = 64
transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.1307,),(0.3081,))
])

# 训练集
train_dataset = datasets.MNIST(root='G:/datasets/mnist',train=True,download=False,transform=transform)
train_loader = DataLoader(train_dataset,shuffle=True,batch_size=batch_size)
# 测试集
test_dataset = datasets.MNIST(root='G:/datasets/mnist',train=False,download=False,transform=transform)
test_loader = DataLoader(test_dataset,shuffle=False,batch_size=batch_size)

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 = 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)
model = Net()
# 模型加载到GPU上
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model.to(device)

3、构造损失函数和优化器

criterion = torch.nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(),lr=0.01,momentum=0.5)

4、训练和测试

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

        # forward+backward+update
        outputs = model(inputs.to(device))
        loss = criterion(outputs, target.to(device))
        loss.backward()
        optimizer.step()

        running_loss += loss.item()
        if batch_idx % 300 == 299:
            print('[%d,%d] loss: %.3f' % (epoch + 1, batch_idx + 1, running_loss / 300))
            running_loss = 0.0
def test():
    correct = 0
    total = 0
    with torch.no_grad():
        for data in test_loader:
            images, labels = data
            outputs = model(images.to(device))
            _, predicted = torch.max(outputs.data, dim=1)
            total += labels.size(0)
            correct += (predicted.cpu() == labels).sum().item()
    print('Accuracy on test set: %d %%' % (100 * correct / total))

for epoch in range(10):
    train(epoch)
    test()

运行结果如下:

[1,300] loss: 2.166
[1,600] loss: 0.797
[1,900] loss: 0.405
Accuracy on test set: 90 %
[2,300] loss: 0.303
[2,600] loss: 0.252
[2,900] loss: 0.218
Accuracy on test set: 94 %
[3,300] loss: 0.178
[3,600] loss: 0.168
[3,900] loss: 0.142
Accuracy on test set: 95 %
[4,300] loss: 0.129
[4,600] loss: 0.119
[4,900] loss: 0.110
Accuracy on test set: 96 %
[5,300] loss: 0.094
[5,600] loss: 0.092
[5,900] loss: 0.091
Accuracy on test set: 96 %
[6,300] loss: 0.077
[6,600] loss: 0.070
[6,900] loss: 0.075
Accuracy on test set: 97 %
[7,300] loss: 0.061
[7,600] loss: 0.058
[7,900] loss: 0.058
Accuracy on test set: 97 %
[8,300] loss: 0.043
[8,600] loss: 0.051
[8,900] loss: 0.050
Accuracy on test set: 97 %
[9,300] loss: 0.041
[9,600] loss: 0.038
[9,900] loss: 0.043
Accuracy on test set: 97 %
[10,300] loss: 0.030
[10,600] loss: 0.032
[10,900] loss: 0.033
Accuracy on test set: 97 %

二、参考文献

  • [1] https://www.bilibili.com/video/BV1Y7411d7Ys?p=9

来源:https://blog.csdn.net/weixin_43821559/article/details/123337335

标签:PyTorch,数字,数据集,多分类
0
投稿

猜你喜欢

  • Vuex实现购物车小功能

    2024-05-21 10:29:07
  • Python设计模式结构型享元模式

    2023-12-19 13:57:40
  • pygame游戏之旅 调用按钮实现游戏开始功能

    2023-04-19 06:36:44
  • python实现简单socket程序在两台电脑之间传输消息的方法

    2021-04-25 21:14:26
  • php截取字符串函数分享

    2023-11-14 10:53:21
  • 开发保留标准的浏览器功能的AJAX应用

    2008-02-03 14:03:00
  • 详解Python做一个名片管理系统

    2021-03-17 05:56:17
  • Python标准库os库的常用功能解析

    2021-03-06 12:32:51
  • go语言日志记录库简单使用方法实例分析

    2024-05-02 16:25:40
  • HTML与CSS在Flash中的应用

    2008-01-23 19:13:00
  • Python 调用API发送邮件

    2021-08-26 04:20:22
  • python计算圆周长、面积、球体体积并画出圆

    2022-08-15 06:19:59
  • SQL Server 对表的主键设计问题及解决办法

    2010-06-07 13:29:00
  • SVN与Git版本控制的优缺点差异全面分析

    2023-12-18 13:39:02
  • Javascirpt打造“互动指针”特效

    2013-08-06 07:37:52
  • 对django2.0 关联表的必填on_delete参数的含义解析

    2023-04-01 22:59:28
  • Python+Django+MySQL实现基于Web版的增删改查的示例代码

    2023-11-20 02:09:06
  • nodejs+express最简易的连接数据库的方法

    2024-01-24 21:15:24
  • ASP实现多域名同一空间的处理实例

    2008-10-29 09:46:00
  • python中的format是什么意思,format怎么用

    2022-07-31 08:51:45
  • asp之家 网络编程 m.aspxhome.com