基于pytorch实现手写数组识别

该博客介绍了如何使用PyTorch和MNIST数据集实现手写数字识别。首先,它涵盖了环境配置,接着是数据预处理和分批次处理。然后,构建了一个具有3层隐藏层的神经网络模型,并设置了优化器和损失函数。训练和测试模型后,还讨论了如何在PyTorch中保存和加载模型及其优化器。
摘要由CSDN通过智能技术生成

基于Pytorch中MNIST数据集实现手写数字识别

环境要求:python且安装torch、torchvision库

数据集准备

导入需要使用模块

  • torchvision中有本次使用的手写数字照片数据集
  • transforms将数据集照片进行格式化转换。如:照片转化为tensor格式、进行归一化处理
  • nn为torch模型板块、optim为模型优化板块、utils为torch工具板块
import torch
import torchvision
import torch.utils as utils
import torch.optim as optim
import torch.nn as nn
import torchvision.transforms as transforms

对数据进行处理以及分批次

  • 掉用torchvision.datasets.MNIST获取数据集
  • 将数据集按照transform进行格式化处理
  • 将数据集按照BATCH_SIZE大小进行分批次(shuffle=True,打乱随机)
BATCH_SIZE = 10
transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize(mean=0.1307,std=0.3081)
])
device = ("cuda:0" if torch.cuda.is_available() else "cpu") # 设置计算硬件
def dataload(train=True):
    MNIST_data = torchvision.datasets.MNIST("./DATA/",train = train ,download=True, transform=transform)
    train_dataloead = utils.data.DataLoader(dataset=MNIST_data,batch_size=BATCH_SIZE,shuffle=True)
    return train_dataloead
train_dataload = dataload()

构建模型

  • 继承nn.Module构建自己的识别模型
  • 搭建一个3层隐藏层,以及为前两层加了非线性激活函数
  • 由于数据集为2828图像,所以将数据集压缩成一个x.size(0),2828二维张量
class Model_MNIST(nn.Module):
    def __init__(self):
        super(Model_MNIST,self).__init__()
        self.fx1 = nn.Linear(28*28,392)
        self.fx2 = nn.Linear(392,98)
        self.fx3 = nn.Linear(98,10)
        self.relu = nn.ReLU()
    def 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是使用 NumPy 读取 MNIST 手写数字数据集并进行预处理的示例代码: ```python import numpy as np import torch from torch.utils.data import DataLoader, TensorDataset # 读取数据集 def load_data(path): with open(path, 'rb') as f: data = np.frombuffer(f.read(), np.uint8, offset=16) return data.reshape(-1, 28*28) # 加载数据集 train_data = load_data('mnist/train-images.idx3-ubyte') train_labels = load_data('mnist/train-labels.idx1-ubyte') test_data = load_data('mnist/t10k-images.idx3-ubyte') test_labels = load_data('mnist/t10k-labels.idx1-ubyte') # 预处理数据 train_data = train_data / 255.0 test_data = test_data / 255.0 train_data = torch.from_numpy(train_data).float() train_labels = torch.from_numpy(train_labels).long() test_data = torch.from_numpy(test_data).float() test_labels = torch.from_numpy(test_labels).long() # 构建数据集和数据加载器 train_dataset = TensorDataset(train_data, train_labels) test_dataset = TensorDataset(test_data, test_labels) train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True) test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False) ``` 在这个示例代码中,我们首先定义了一个 `load_data` 函数,用于读取 MNIST 数据集文件,并将数据转换为 NumPy 数组形式。然后,我们将数据集进行预处理,包括归一化和转换为 PyTorch 的 Tensor 对象。最后,我们使用 PyTorch 的 `TensorDataset` 和 `DataLoader` 类构建了训练集和测试集的数据集和数据加载器,方便后续进行模型训练和测试。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值