PyTorch实现MNIST数据集手写数字识别详情
作者:长浔 时间:2021-08-03 17:30:36
前言:
本篇文章基于卷积神经网络CNN,使用PyTorch实现MNIST数据集手写数字识别。
一、PyTorch是什么?
PyTorch 是一个 Torch7 团队开源的 Python 优先的深度学习框架,提供两个高级功能:
强大的 GPU 加速 Tensor 计算(类似 numpy)
构建基于 tape 的自动升级系统上的深度神经网络
你可以重用你喜欢的 python 包,如 numpy、scipy 和 Cython ,在需要时扩展 PyTorch。
二、程序示例
下面案例可供运行参考
1.引入必要库
import torchvision
import torch
from torch.utils.data import DataLoader
import torch.nn.functional as F
2.下载数据集
这里设置download=True,将会自动下载数据集,并存储在./data文件夹。
train_data = torchvision.datasets.MNIST(root="./data",train=True,transform=torchvision.transforms.ToTensor(),download=True)
test_data = torchvision.datasets.MNIST(root="./data",train=False,transform=torchvision.transforms.ToTensor(),download=True)
3.加载数据集
batch_size=32表示每一个batch中包含32张手写数字图片,shuffle=True表示打乱测试集(data和target仍一一对应)
train_loader = DataLoader(train_data,batch_size=32,shuffle=True)
test_loader = DataLoader(test_data,batch_size=32,shuffle=False)
4.搭建CNN模型并实例化
class Net(torch.nn.Module):
def __init__(self):
super(Net,self).__init__()
self.con1 = torch.nn.Conv2d(1,10,kernel_size=5)
self.con2 = torch.nn.Conv2d(10,20,kernel_size=5)
self.pooling = torch.nn.MaxPool2d(2)
self.fc = torch.nn.Linear(320,10)
def forward(self,x):
batch_size = x.size(0)
x = F.relu(self.pooling(self.con1(x)))
x = F.relu(self.pooling(self.con2(x)))
x = x.view(batch_size,-1)
x = self.fc(x)
return x
#模型实例化
model = Net()
5.交叉熵损失函数损失函数及SGD算法优化器
lossfun = torch.nn.CrossEntropyLoss()
opt = torch.optim.SGD(model.parameters(),lr=0.01,momentum=0.5)
6.训练函数
def train(epoch):
running_loss = 0.0
for i,(inputs,targets) in enumerate(train_loader,0):
# inputs,targets = inputs.to(device),targets.to(device)
opt.zero_grad()
outputs = model(inputs)
loss = lossfun(outputs,targets)
loss.backward()
opt.step()
running_loss += loss.item()
if i % 300 == 299:
print('[%d,%d] loss:%.3f' % (epoch+1,i+1,running_loss/300))
running_loss = 0.0
7.测试函数
def test():
total = 0
correct = 0
with torch.no_grad():
for (inputs,targets) in test_loader:
# inputs, targets = inputs.to(device), targets.to(device)
outputs = model(inputs)
_,predicted = torch.max(outputs.data,dim=1)
total += targets.size(0)
correct += (predicted == targets).sum().item()
print(100*correct/total)
8.运行
if __name__ == '__main__':
for epoch in range(20):
train(epoch)
test()
三、总结
来源:https://blog.csdn.net/qq_41664447/article/details/126698428
标签:PyTorch,MNIST,数据集,数字,识别
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python学习之路安装pycharm的教程详解
2021-11-15 23:07:51
![](https://img.aspxhome.com/file/2023/7/75267_0s.jpg)
Python中的并发编程asyncio库入门使用
2021-02-13 05:03:52
Tensorflow加载Vgg预训练模型操作
2023-10-13 10:56:23
![](https://img.aspxhome.com/file/2023/5/80795_0s.jpg)
Python多线程与同步机制浅析
2021-10-31 03:22:51
asp无限级分类
2007-09-16 18:06:00
C#中使用SendMessage
2023-07-14 19:12:37
JavaScript实现点击按钮复制指定区域文本(推荐)
2023-08-22 17:36:30
寻找Dreamweaver鲜为人知的小秘诀
2008-04-28 12:10:00
如何在ASP里面创建GUID
2008-01-08 19:13:00
Python基于递归实现电话号码映射功能示例
2023-11-15 09:38:39
OpenCV-Python实现图像梯度与Sobel滤波器
2021-04-07 05:23:20
![](https://img.aspxhome.com/file/2023/5/82535_0s.png)
Python PaddlePaddle机器学习之求解线性模型
2023-04-19 08:35:14
MySQL数据库的其它安全问题
2008-12-23 15:40:00
oracle数据排序后获取前几行数据的写法(rownum、fetch方式)
2023-07-02 01:15:09
![](https://img.aspxhome.com/file/2023/2/63372_0s.jpg)
使用Django启动命令行及执行脚本的方法
2022-03-08 22:10:16
如何用python爬取微博热搜数据并保存
2021-10-21 14:13:38
![](https://img.aspxhome.com/file/2023/6/72956_0s.png)
再说淘宝的评价和信用机制
2008-07-10 12:43:00
sqlserver 存储过程带事务 拼接id 返回值
2012-11-30 20:06:39
javascript调试之DOM断点调试法使用技巧分享
2023-09-24 12:24:18
SQL Server数据库搭建农村信息化的方案
2009-01-23 14:16:00
![](https://img.aspxhome.com/file/UploadPic/20091/2009131151251116.jpg)