pytorch实现手写数字图片识别
作者:虾米不打烊 时间:2021-04-20 12:46:58
本文实例为大家分享了pytorch实现手写数字图片识别的具体代码,供大家参考,具体内容如下
数据集:MNIST数据集,代码中会自动下载,不用自己手动下载。数据集很小,不需要GPU设备,可以很好的体会到pytorch的魅力。
模型+训练+预测程序:
import torch
from torch import nn
from torch.nn import functional as F
from torch import optim
import torchvision
from matplotlib import pyplot as plt
from utils import plot_image, plot_curve, one_hot
# step1 load dataset
batch_size = 512
train_loader = torch.utils.data.DataLoader(
torchvision.datasets.MNIST('mnist_data', train=True, download=True,
transform=torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(
(0.1307,), (0.3081,)
)
])),
batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(
torchvision.datasets.MNIST('mnist_data/', train=False, download=True,
transform=torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(
(0.1307,), (0.3081,)
)
])),
batch_size=batch_size, shuffle=False)
x , y = next(iter(train_loader))
print(x.shape, y.shape, x.min(), x.max())
plot_image(x, y, "image_sample")
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(28*28, 256)
self.fc2 = nn.Linear(256, 64)
self.fc3 = nn.Linear(64, 10)
def forward(self, x):
# x: [b, 1, 28, 28]
# h1 = relu(xw1 + b1)
x = F.relu(self.fc1(x))
# h2 = relu(h1w2 + b2)
x = F.relu(self.fc2(x))
# h3 = h2w3 + b3
x = self.fc3(x)
return x
net = Net()
optimizer = optim.SGD(net.parameters(), lr=0.01, momentum=0.9)
train_loss = []
for epoch in range(3):
for batch_idx, (x, y) in enumerate(train_loader):
#加载进来的图片是一个四维的tensor,x: [b, 1, 28, 28], y:[512]
#但是我们网络的输入要是一个一维向量(也就是二维tensor),所以要进行展平操作
x = x.view(x.size(0), 28*28)
# [b, 10]
out = net(x)
y_onehot = one_hot(y)
# loss = mse(out, y_onehot)
loss = F.mse_loss(out, y_onehot)
optimizer.zero_grad()
loss.backward()
# w' = w - lr*grad
optimizer.step()
train_loss.append(loss.item())
if batch_idx % 10 == 0:
print(epoch, batch_idx, loss.item())
plot_curve(train_loss)
# we get optimal [w1, b1, w2, b2, w3, b3]
total_correct = 0
for x,y in test_loader:
x = x.view(x.size(0), 28*28)
out = net(x)
# out: [b, 10]
pred = out.argmax(dim=1)
correct = pred.eq(y).sum().float().item()
total_correct += correct
total_num = len(test_loader.dataset)
acc = total_correct/total_num
print("acc:", acc)
x, y = next(iter(test_loader))
out = net(x.view(x.size(0), 28*28))
pred = out.argmax(dim=1)
plot_image(x, pred, "test")
主程序中调用的函数(注意命名为utils):
import torch
from matplotlib import pyplot as plt
def plot_curve(data):
fig = plt.figure()
plt.plot(range(len(data)), data, color='blue')
plt.legend(['value'], loc='upper right')
plt.xlabel('step')
plt.ylabel('value')
plt.show()
def plot_image(img, label, name):
fig = plt.figure()
for i in range(6):
plt.subplot(2, 3, i + 1)
plt.tight_layout()
plt.imshow(img[i][0]*0.3081+0.1307, cmap='gray', interpolation='none')
plt.title("{}: {}".format(name, label[i].item()))
plt.xticks([])
plt.yticks([])
plt.show()
def one_hot(label, depth=10):
out = torch.zeros(label.size(0), depth)
idx = torch.LongTensor(label).view(-1, 1)
out.scatter_(dim=1, index=idx, value=1)
return out
打印出损失下降的曲线图:
训练3个epoch之后,在测试集上的精度就可以89%左右,可见模型的准确度还是很不错的。
输出六张测试集的图片以及预测结果:
六张图片的预测全部正确。
来源:https://blog.csdn.net/weixin_41423872/article/details/109451642
标签:pytorch,图片识别
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python实现提取音乐频谱的方法详解
2022-01-27 07:03:08
![](https://img.aspxhome.com/file/2023/2/72072_0s.jpg)
pyqt5打包成exe可执行文件的方法
2022-02-09 11:25:57
![](https://img.aspxhome.com/file/2023/7/87667_0s.png)
python中 @的含义以及基本使用方法
2022-12-24 04:58:48
asp base64 utf-8为了兼容asp.net的base64
2011-03-10 10:47:00
ZABBIX3.2使用python脚本实现监控报表的方法
2021-04-11 20:15:02
![](https://img.aspxhome.com/file/2023/0/79680_0s.jpg)
Django集成百度富文本编辑器uEditor攻略
2021-01-11 21:43:21
numpy中实现ndarray数组返回符合特定条件的索引方法
2023-04-21 06:21:53
![](https://img.aspxhome.com/file/2023/3/112973_0s.jpg)
centos下yum搭建安装linux+apache+mysql+php环境教程
2023-11-14 01:04:39
详解python的集合set的函数
2023-02-06 04:16:42
![](https://img.aspxhome.com/file/2023/7/103167_0s.png)
OpenCV半小时掌握基本操作之傅里叶变换
2022-03-27 22:25:47
![](https://img.aspxhome.com/file/2023/5/118315_0s.gif)
python画柱状图--不同颜色并显示数值的方法
2021-12-31 17:22:18
![](https://img.aspxhome.com/file/2023/6/121666_0s.jpg)
Python之ascii转中文的实现
2023-08-24 19:39:12
![](https://img.aspxhome.com/file/2023/0/62600_0s.png)
python中将阿拉伯数字转换成中文的实现代码
2021-09-30 05:45:25
Python可视化工具如何实现动态图表
2023-05-22 19:21:27
![](https://img.aspxhome.com/file/2023/0/81710_0s.gif)
Django多个app urls配置代码实例
2021-11-23 10:01:13
![](https://img.aspxhome.com/file/2023/6/100976_0s.png)
python 动态导入模块实现模块热更新的方法
2022-07-06 17:37:56
![](https://img.aspxhome.com/file/2023/1/111991_0s.jpg)
Python格式化css文件的方法
2021-02-14 11:38:34
使用pyhon绘图比较两个手机屏幕大小(实例代码)
2022-12-25 02:55:30
![](https://img.aspxhome.com/file/2023/2/78652_0s.png)
Python标准库06之子进程 (subprocess包) 详解
2021-05-24 02:00:25
PHP中phar包的使用教程
2023-11-09 19:55:52