基于Pytorch深度学习神经网络MNIST手写数字识别系统源码(带界面和手写画板)

 第一步:准备数据

mnist开源数据集

第二步:搭建模型

我们这里搭建了一个LeNet5网络

参考代码如下:

import torch
from torch import nn


class Reshape(nn.Module):
    def forward(self, x):
        return x.view(-1, 1, 28, 28)


class LeNet5(nn.Module):
    def __init__(self):
        super(LeNet5, self).__init__()
        self.net = nn.Sequential(
            Reshape(),

            # CONV1, ReLU1, POOL1
            nn.Conv2d(in_channels=1, out_channels=6, kernel_size=5, padding=2),
            # nn.Conv2d(in_channels=1, out_channels=6, kernel_size=5),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2),

            # CONV2, ReLU2, POOL2
            nn.Conv2d(in_channels=6, out_channels=16, kernel_size=5),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2),
            nn.Flatten(),

            # FC1
            nn.Linear(in_features=16 * 5 * 5, out_features=120),
            nn.ReLU(),

            # FC2
            nn.Linear(in_features=120, out_features=84),
            nn.ReLU(),

            # FC3
            nn.Linear(in_features=84, out_features=10)
        )
        # 添加softmax层
        self.softmax = nn.Softmax()

    def forward(self, x):
        logits = self.net(x)
        # 将logits转为概率
        prob = self.softmax(logits)
        return prob


if __name__ == '__main__':
	model = LeNet5()
	X = torch.rand(size=(256, 1, 28, 28), dtype=torch.float32)
	for layer in model.net:
	    X = layer(X)
	    print(layer.__class__.__name__, '\toutput shape: \t', X.shape)
	X = torch.rand(size=(1, 1, 28, 28), dtype=torch.float32)
	print(model(X))

第三步:训练代码

import torch
from torch import nn
from torchvision import datasets
from torchvision.transforms import ToTensor
from torch.utils.data import DataLoader

from model import LeNet5


# DATASET
train_data = datasets.MNIST(
	root='./data',
	train=False,
	download=True,
	transform=ToTensor()
)

test_data = datasets.MNIST(
	root='./data',
	train=False,
	download=True,
	transform=ToTensor()
)


# PREPROCESS
batch_size = 256
train_dataloader = DataLoader(dataset=train_data, batch_size=batch_size)
test_dataloader = DataLoader(dataset=test_data, batch_size=batch_size)
for X, y in train_dataloader:
	print(X.shape)		# torch.Size([256, 1, 28, 28])
	print(y.shape)		# torch.Size([256])
	break


# MODEL
device = 'cuda' if torch.cuda.is_available() else 'cpu'
model = LeNet5().to(device)


# TRAIN MODEL
loss_func = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(params=model.parameters())

def train(dataloader, model, loss_func, optimizer, epoch):
	model.train()
	data_size = len(dataloader.dataset)
	for batch, (X, y) in enumerate(dataloader):
		X, y = X.to(device), y.to(device)

		y_hat = model(X)
		loss = loss_func(y_hat, y)

		optimizer.zero_grad()
		loss.backward()
		optimizer.step()

	loss, current = loss.item(), batch * len(X)
	print(f'EPOCH{epoch+1}\tloss: {loss:>7f}', end='\t')


# Test model
def test(dataloader, model, loss_fn):
	size = len(dataloader.dataset)
	num_batches = len(dataloader)
	model.eval()
	test_loss, correct = 0, 0
	with torch.no_grad():
		for X, y in dataloader:
			X, y = X.to(device), y.to(device)
			pred = model(X)
			test_loss += loss_fn(pred, y).item()
			correct += (pred.argmax(1) == y).type(torch.float).sum().item()
	test_loss /= num_batches
	correct /= size
	print(f'Test Error: Accuracy: {(100 * correct):>0.1f}%, Average loss: {test_loss:>8f}\n')


if __name__ == '__main__':
	epoches = 80
	for epoch in range(epoches):
		train(train_dataloader, model, loss_func, optimizer, epoch)
		test(test_dataloader, model, loss_func)

	# Save models
	torch.save(model.state_dict(), 'model.pth')
	print('Saved PyTorch LeNet5 State to model.pth')

第四步:统计训练过程

EPOCH1	loss: 1.908403	Test Error: Accuracy: 58.3%, Average loss: 1.943602

EPOCH2	loss: 1.776060	Test Error: Accuracy: 72.2%, Average loss: 1.750917

EPOCH3	loss: 1.717706	Test Error: Accuracy: 73.6%, Average loss: 1.730332

EPOCH4	loss: 1.719344	Test Error: Accuracy: 76.0%, Average loss: 1.703456

EPOCH5	loss: 1.659312	Test Error: Accuracy: 76.6%, Average loss: 1.694500

EPOCH6	loss: 1.647946	Test Error: Accuracy: 76.9%, Average loss: 1.691286

EPOCH7	loss: 1.653712	Test Error: Accuracy: 77.0%, Average loss: 1.690819

EPOCH8	loss: 1.653270	Test Error: Accuracy: 76.8%, Average loss: 1.692459

EPOCH9	loss: 1.649021	Test Error: Accuracy: 77.5%, Average loss: 1.686158

EPOCH10	loss: 1.648204	Test Error: Accuracy: 78.3%, Average loss: 1.678802

EPOCH11	loss: 1.647159	Test Error: Accuracy: 78.4%, Average loss: 1.676133

EPOCH12	loss: 1.647390	Test Error: Accuracy: 78.6%, Average loss: 1.674455

EPOCH13	loss: 1.646807	Test Error: Accuracy: 78.4%, Average loss: 1.675752

EPOCH14	loss: 1.630824	Test Error: Accuracy: 79.1%, Average loss: 1.668470

EPOCH15	loss: 1.524222	Test Error: Accuracy: 86.3%, Average loss: 1.599240

EPOCH16	loss: 1.524022	Test Error: Accuracy: 86.7%, Average loss: 1.594947

EPOCH17	loss: 1.524296	Test Error: Accuracy: 87.1%, Average loss: 1.588946

EPOCH18	loss: 1.523599	Test Error: Accuracy: 87.3%, Average loss: 1.588275

EPOCH19	loss: 1.523655	Test Error: Accuracy: 87.5%, Average loss: 1.586576

EPOCH20	loss: 1.523659	Test Error: Accuracy: 88.2%, Average loss: 1.579286

EPOCH21	loss: 1.523733	Test Error: Accuracy: 87.9%, Average loss: 1.582472

EPOCH22	loss: 1.523748	Test Error: Accuracy: 88.2%, Average loss: 1.578699

EPOCH23	loss: 1.523788	Test Error: Accuracy: 88.0%, Average loss: 1.579700

EPOCH24	loss: 1.523708	Test Error: Accuracy: 88.1%, Average loss: 1.579758

EPOCH25	loss: 1.523683	Test Error: Accuracy: 88.4%, Average loss: 1.575913

EPOCH26	loss: 1.523646	Test Error: Accuracy: 88.7%, Average loss: 1.572831

EPOCH27	loss: 1.523654	Test Error: Accuracy: 88.9%, Average loss: 1.570528

EPOCH28	loss: 1.523642	Test Error: Accuracy: 89.0%, Average loss: 1.570223

EPOCH29	loss: 1.523663	Test Error: Accuracy: 89.0%, Average loss: 1.570385

EPOCH30	loss: 1.523658	Test Error: Accuracy: 88.9%, Average loss: 1.571195

EPOCH31	loss: 1.523653	Test Error: Accuracy: 88.4%, Average loss: 1.575981

EPOCH32	loss: 1.523653	Test Error: Accuracy: 89.0%, Average loss: 1.570087

EPOCH33	loss: 1.523642	Test Error: Accuracy: 88.9%, Average loss: 1.571018

EPOCH34	loss: 1.523649	Test Error: Accuracy: 89.0%, Average loss: 1.570439

EPOCH35	loss: 1.523629	Test Error: Accuracy: 90.4%, Average loss: 1.555473

EPOCH36	loss: 1.461187	Test Error: Accuracy: 97.1%, Average loss: 1.491042

EPOCH37	loss: 1.461230	Test Error: Accuracy: 97.7%, Average loss: 1.485049

EPOCH38	loss: 1.461184	Test Error: Accuracy: 97.7%, Average loss: 1.485653

EPOCH39	loss: 1.461156	Test Error: Accuracy: 98.2%, Average loss: 1.479966

EPOCH40	loss: 1.461335	Test Error: Accuracy: 98.2%, Average loss: 1.479197

EPOCH41	loss: 1.461152	Test Error: Accuracy: 98.7%, Average loss: 1.475477

EPOCH42	loss: 1.461153	Test Error: Accuracy: 98.7%, Average loss: 1.475124

EPOCH43	loss: 1.461153	Test Error: Accuracy: 98.9%, Average loss: 1.472885

EPOCH44	loss: 1.461151	Test Error: Accuracy: 99.1%, Average loss: 1.470957

EPOCH45	loss: 1.461156	Test Error: Accuracy: 99.1%, Average loss: 1.471141

EPOCH46	loss: 1.461152	Test Error: Accuracy: 99.1%, Average loss: 1.470793

EPOCH47	loss: 1.461151	Test Error: Accuracy: 98.8%, Average loss: 1.474548

EPOCH48	loss: 1.461151	Test Error: Accuracy: 99.1%, Average loss: 1.470666

EPOCH49	loss: 1.461151	Test Error: Accuracy: 99.1%, Average loss: 1.471546

EPOCH50	loss: 1.461151	Test Error: Accuracy: 99.0%, Average loss: 1.471407

EPOCH51	loss: 1.461151	Test Error: Accuracy: 98.8%, Average loss: 1.473795

EPOCH52	loss: 1.461164	Test Error: Accuracy: 98.2%, Average loss: 1.480009

EPOCH53	loss: 1.461151	Test Error: Accuracy: 99.2%, Average loss: 1.469931

EPOCH54	loss: 1.461152	Test Error: Accuracy: 99.2%, Average loss: 1.469916

EPOCH55	loss: 1.461151	Test Error: Accuracy: 98.9%, Average loss: 1.472574

EPOCH56	loss: 1.461151	Test Error: Accuracy: 98.6%, Average loss: 1.476035

EPOCH57	loss: 1.461151	Test Error: Accuracy: 98.2%, Average loss: 1.478933

EPOCH58	loss: 1.461150	Test Error: Accuracy: 99.4%, Average loss: 1.468186

EPOCH59	loss: 1.461151	Test Error: Accuracy: 99.4%, Average loss: 1.467602

EPOCH60	loss: 1.461151	Test Error: Accuracy: 99.1%, Average loss: 1.471206

EPOCH61	loss: 1.461151	Test Error: Accuracy: 98.8%, Average loss: 1.473356

EPOCH62	loss: 1.461151	Test Error: Accuracy: 99.2%, Average loss: 1.470242

EPOCH63	loss: 1.461150	Test Error: Accuracy: 99.1%, Average loss: 1.470826

EPOCH64	loss: 1.461151	Test Error: Accuracy: 98.7%, Average loss: 1.474476

EPOCH65	loss: 1.461150	Test Error: Accuracy: 99.3%, Average loss: 1.469116

EPOCH66	loss: 1.461150	Test Error: Accuracy: 99.4%, Average loss: 1.467823

EPOCH67	loss: 1.461150	Test Error: Accuracy: 99.5%, Average loss: 1.466486

EPOCH68	loss: 1.461152	Test Error: Accuracy: 99.3%, Average loss: 1.468688

EPOCH69	loss: 1.461150	Test Error: Accuracy: 99.5%, Average loss: 1.466256

EPOCH70	loss: 1.461150	Test Error: Accuracy: 99.5%, Average loss: 1.466588

EPOCH71	loss: 1.461150	Test Error: Accuracy: 99.6%, Average loss: 1.465280

EPOCH72	loss: 1.461150	Test Error: Accuracy: 99.4%, Average loss: 1.467110

EPOCH73	loss: 1.461151	Test Error: Accuracy: 99.6%, Average loss: 1.465245

EPOCH74	loss: 1.461150	Test Error: Accuracy: 99.5%, Average loss: 1.466551

EPOCH75	loss: 1.461150	Test Error: Accuracy: 99.5%, Average loss: 1.466001

EPOCH76	loss: 1.461150	Test Error: Accuracy: 99.3%, Average loss: 1.468074

EPOCH77	loss: 1.461151	Test Error: Accuracy: 99.6%, Average loss: 1.465709

EPOCH78	loss: 1.461150	Test Error: Accuracy: 99.5%, Average loss: 1.466567

EPOCH79	loss: 1.461150	Test Error: Accuracy: 99.6%, Average loss: 1.464922

EPOCH80	loss: 1.461150	Test Error: Accuracy: 99.6%, Average loss: 1.465109

第五步:搭建GUI界面

第六步:整个工程的内容

有训练代码和训练好的模型以及训练过程,提供数据,提供GUI界面代码,主要使用方法可以参考里面的“文档说明_必看.docx”

 代码的下载路径(新窗口打开链接)基于Pytorch深度学习神经网络MNIST手写数字识别系统源码(带界面和手写画板)

有问题可以私信或者留言,有问必答

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/630136.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【传知代码】VRT: 关于视频修复的模型(论文复现)

前言:随着数字媒体技术的普及,制作和传播视频内容变得日益普遍。但是,视频中由于多种因素,例如传输、存储和录制设备等,经常出现质量上的问题,如图像模糊、噪声干扰和低清晰度等。这类问题对用户的体验和观…

数学建模——农村公交与异构无人机协同配送优化

目录 1.题目 2.问题1 1. 问题建模 输入数据 ​编辑 2. 算法选择 3.数据导入 3.模型构建 1. 距离计算 2. 优化模型 具体步骤 进一步优化 1. 重新定义问题 2. 变量定义 3. 优化目标 具体步骤 再进一步优化 具体实现步骤 1. 计算距离矩阵 2. 变量定义 3. 约束…

NVM安装及VUE创建项目的N种方式

VUE 参考官网:https://cli.vuejs.org/zh/guide/ 目录 NVM安装 1.卸载node.js 2.安装nvm ​编辑​ 3.配置 4.使用nvm安装node.js 5.nvm常用命令 创建VUE项目 1.使用vue init 创建vue2(不推荐) 2.使用vue create创建vue2和3&#xff…

(保姆级教程傻瓜式操作)树莓派--基于opencv实现人脸识别

前言 因为当时没有边实验边记录,所以这篇文章可能存在疏漏。不过很多地方我推荐了我参考过的博客或者视频,希望尽可能地解答您的疑惑,如果您仍有不懂的地方,欢迎评论,如果我知道答案,我会很乐意为您解答。 …

C++错题集(持续更新ing)

Day 1 一、选择题 解析: 在数字不会溢出的前提下,对于正数和负数,有: 1)左移n位,相当于操作数乘以2的n次方; 2)右移n位,相当于操作数除以2的n次方。 解析&#xff1a…

基于51单片机的自动浇花器电路

一、系统概述 自动浇水灌溉系统设计方案,以AT89C51单片机为控制核心,采用模块化的设计方法。 组成部分为:5V供电模块、土壤湿度传感器模块、ADC0832模数转换模块、水泵控制模块、按键输入模块、LCD显示模块和声光报警模块,结构如…

51单片机超声波测距_液位检测_温度检测原理图PCB仿真代码

目录 实物图: PCB ​原理图​ 仿真图 ​编辑 程序 资料下载地址:51单片机超声波测距-液位检测-温度检测原理图PCB仿真代码 主控为stc89c52,通过ds18b20进行温度采集,超声波测距,距离不可以超过1m,通过按键可以设…

做简单易用的GIS资源管理软件

在室外资源管理领域,采用基于GIS的解决方案已成为主流趋势,旨在实现资源的高效利用和管理。GIS技术结合资源对象的规划、定位和监控,为企业提供全面的管理方案,从而优化资源使用、提高运营效率和降低成本。 然而,许多资…

shell脚本实现linux系统自动化配置免密互信

目录 背景脚本功能脚本内容及使用方法 1.背景 进行linux自动化运维时需要先配置免密,但某些特定场景下,做了互信的节点需要取消免密,若集群庞大节点数量多时,节点两两之间做互信操作非常麻烦,比如有五个节点&#x…

计网面试干货---带你梳理常考的面试题

顾得泉:个人主页 个人专栏:《Linux操作系统》 《C从入门到精通》 《LeedCode刷题》 键盘敲烂,年薪百万! 一、HTTP和HTTPS的区别 1.安全性:HTTPS通过SSL/TLS协议对数据进行加密处理,有效防止数据在传输过…

人工智能项目,如何解决大模型的数据私有化

这个问题是最近走访百家企业,客户问的最多的问题。人工智能是对数据集中后,再利用的智能化手段,ChatGPT还在持续的投入,汇集数据、训练模型,微软也不过是做了一个办公客户端的智能工具,那么行业应运之时&am…

写后端项目时上传文件接口使用阿里云oss-规范写法

文章目录 开通对象存储服务密钥管理点击头像点击密钥管理创建新密钥AccessKey 写在yml配置文件中相关配置1.pom依赖2.全局配置类3.AliOssUtil 工具类3.AliOssProperties类,用于读取yml文件中写入的密钥4.controller层,用于写传输文件的接口 开通对象存储…

《Python编程从入门到实践》day29

# 昨日知识点回顾 修改折线图文字和线条粗细 矫正图形 使用内置格式 # 今日知识点学习 15.2.4 使用scatter()绘制散点图并设置样式 import matplotlib.pyplot as plt import matplotlib matplotlib.use(TkAgg)plt.style.use(seaborn-v0_8) # 使用内置格式 fig, ax plt.subpl…

荣耀MagicBook X 14 Pro锐龙版 2023 集显(FRI-H76)笔记本电脑原装出厂Windows11系统工厂模式安装包下载,带F10智能还原

恢复开箱状态预装OEM系统,适用型号:HONOR荣耀FRI-H76、FRI-H56 链接:https://pan.baidu.com/s/1Lcg45byotu5kDDSBs3FStA?pwdl30r 提取码:l30r 华为荣耀原装WIN11系统工厂安装包,含F10一键恢复功能、系统自带所有驱…

蓝桥杯-外卖店优先级(简单写法)

“饱了么”外卖系统中维护着 N 家外卖店,编号 1∼N。 每家外卖店都有一个优先级,初始时 (0 时刻) 优先级都为 0。 每经过 1 个时间单位,如果外卖店没有订单,则优先级会减少 1,最低减到 0;而如果外卖店有订…

四、基于Stage模型的应用架构设计

前面我们了解了如何构建鸿蒙应用以及开发了第一个页面,这只是简单的demo;那么如何去设计,从0到1搭建一个真正的应用呢 一、基本概念 1、Stage模型基本概念 Stage模型概念图 AbilityStage:是一个Module级别的组件容器&#xff0…

「AIGC」Python实现tokens算法

本文主要介绍通过python实现tokens统计,避免重复调用openai等官方api,开源节流。 一、设计思路 初始化tokenizer使用tokenizer将文本转换为tokens计算token的数量二、业务场景 2.1 首次加载依赖 2.2 执行业务逻辑 三、核心代码 from transformers import AutoTokenizer imp…

基于网络爬虫技术的网络新闻分析(二)

目录 2 系统需求分析 2.1 系统需求概述 2.2 系统需求分析 2.2.1 系统功能要求 2.2.2 系统IPO图 2.2 系统非功能性需求分析 3 系统概要设计 3.1 设计约束 3.1.1 需求约束 3.1.2 设计策略 3.1.3 技术实现 3.3 模块结构 3.3.1 模块结构图 3.3.2 系统层次图 3.3.3…

与禹老师学前端vue3学习汇总

24.5.15: 创建Vue3工程 1.确定自己电脑有没有nodejs环境,在cmd中输入node,如果出现Node.js的版本号说明已经有这个环境了,否则搜索Node.js安装 2.先在D盘创建一个文件夹Vue3_Study,然后在这个空文件夹中右键选择终端…

汇聚荣:拼多多长期没有流量如何提高?

在电商的海洋中,拼多多以其独特的团购模式吸引了众多消费者的目光。然而,随着市场竞争的加剧和消费者需求的多样化,一些商家发现自家店铺的流量持续低迷,销售业绩难以突破。面对这样的挑战,如何有效提升拼多多店铺的客…