pytorch如何利用ResNet18进行手写数字识别
作者:爱听许嵩歌 发布时间:2022-02-07 04:07:26
标签:pytorch,ResNet18,手写数字,识别
利用ResNet18进行手写数字识别
先写resnet18.py
代码如下:
import torch
from torch import nn
from torch.nn import functional as F
class ResBlk(nn.Module):
"""
resnet block
"""
def __init__(self, ch_in, ch_out, stride=1):
"""
:param ch_in:
:param ch_out:
"""
super(ResBlk, self).__init__()
self.conv1 = nn.Conv2d(ch_in, ch_out, kernel_size=3, stride=stride, padding=1)
self.bn1 = nn.BatchNorm2d(ch_out)
self.conv2 = nn.Conv2d(ch_out, ch_out, kernel_size=3, stride=1, padding=1)
self.bn2 = nn.BatchNorm2d(ch_out)
self.extra = nn.Sequential()
if ch_out != ch_in:
# [b, ch_in, h, w] => [b, ch_out, h, w]
self.extra = nn.Sequential(
nn.Conv2d(ch_in, ch_out, kernel_size=1, stride=stride),
nn.BatchNorm2d(ch_out)
)
def forward(self, x):
"""
:param x: [b, ch, h, w]
:return:
"""
out = F.relu(self.bn1(self.conv1(x)))
out = self.bn2(self.conv2(out))
# short cut
# extra module:[b, ch_in, h, w] => [b, ch_out, h, w]
# element-wise add:
out = self.extra(x) + out
out = F.relu(out)
return out
class ResNet18(nn.Module):
def __init__(self):
super(ResNet18, self).__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(1, 64, kernel_size=3, stride=3, padding=0),
nn.BatchNorm2d(64)
)
# followed 4 blocks
# [b, 64, h, w] => [b, 128, h, w]
self.blk1 = ResBlk(64, 128, stride=2)
# [b, 128, h, w] => [b, 256, h, w]
self.blk2 = ResBlk(128, 256, stride=2)
# [b, 256, h, w] => [b, 512, h, w]
self.blk3 = ResBlk(256, 512, stride=2)
# [b, 512, h, w] => [b, 512, h, w]
self.blk4 = ResBlk(512, 512, stride=2)
self.outlayer = nn.Linear(512 * 1 * 1, 10)
def forward(self, x):
"""
:param x:
:return:
"""
# [b, 1, h, w] => [b, 64, h, w]
x = F.relu(self.conv1(x))
# [b, 64, h, w] => [b, 512, h, w]
x = self.blk1(x)
x = self.blk2(x)
x = self.blk3(x)
x = self.blk4(x)
# print(x.shape) # [b, 512, 1, 1]
# 意思就是不管之前的特征图尺寸为多少,只要设置为(1,1),那么最终特征图大小都为(1,1)
# [b, 512, h, w] => [b, 512, 1, 1]
x = F.adaptive_avg_pool2d(x, [1, 1])
x = x.view(x.size(0), -1)
x = self.outlayer(x)
return x
def main():
blk = ResBlk(1, 128, stride=4)
tmp = torch.randn(512, 1, 28, 28)
out = blk(tmp)
print('blk', out.shape)
model = ResNet18()
x = torch.randn(512, 1, 28, 28)
out = model(x)
print('resnet', out.shape)
print(model)
if __name__ == '__main__':
main()
再写绘图utils.py
代码如下
import torch
from matplotlib import pyplot as plt
device = torch.device('cuda')
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).cuda()
idx = label.view(-1, 1)
out.scatter_(dim=1, index=idx, value=1)
return out
最后是主函数mnist_train.py
代码如下:
import torch
from torch import nn
from torch.nn import functional as F
from torch import optim
from resnet18 import ResNet18
import torchvision
from matplotlib import pyplot as plt
from utils import plot_image, plot_curve, one_hot
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))
# x:[512, 1, 28, 28], y:[512]
print(x.shape, y.shape, x.min(), x.max())
plot_image(x, y, 'image sample')
device = torch.device('cuda')
net = ResNet18().to(device)
optimizer = optim.SGD(net.parameters(), lr=0.01, momentum=0.9)
train_loss = []
for epoch in range(5):
# 训练
net.train()
for batch_idx, (x, y) in enumerate(train_loader):
# x: [b, 1, 28, 28], y: [512]
# [b, 1, 28, 28] => [b, 10]
x, y = x.to(device), y.to(device)
out = net(x)
# [b, 10]
y_onehot = one_hot(y)
# loss = mse(out, y_onehot)
loss = F.mse_loss(out, y_onehot).to(device)
# 先给梯度清0
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]
# 测试
net.eval()
total_correct = 0
for x, y in test_loader:
x, y = x.cuda(), y.cuda()
out = net(x)
# out: [b, 10] => pred: [b]
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('test acc:', acc)
x, y = next(iter(test_loader))
x, y = x.cuda(), y.cuda()
out = net(x)
pred = out.argmax(dim=1)
x = x.cpu()
pred = pred.cpu()
plot_image(x, pred, 'test')
结果为:
4 90 0.009581390768289566
4 100 0.010348389856517315
4 110 0.01111914124339819
test acc: 0.9703
运行时注意把模型和参数放在GPU里,这样节省时间,此代码作为测试代码,仅供参考。
来源:https://blog.csdn.net/weixin_45092662/article/details/115177261
0
投稿
猜你喜欢
- 1. ASP与Access数据库连接: 代码如下:dim strConn dim conn strConn = "Provide
- 前言单例模式(Singleton Pattern),是一种软件设计模式,是类只能实例化一个对象,目的是便于外界的访问,节约系统资源,如果希望
- 前几天,我们Python猫交流学习群 里的 M 同学提了个问题。这个问题挺有意思,经初次讨论,我们认为它无解。然而,我认为它很有价值,应该继
- 前言:本篇博客继续学习BeautifulSoup,目标站点选取“溧阳摄影圈”,这一地方论坛。目标站点
- 实际工作经历中,免不了有时候需要连接数据库进行问题排查分析的场景,之前一直习惯通过 mysql -uxxx -hxxxx -P1234 ..
- 本次分享将讲述如何在Python中对多个list的对应元素求和,前提是每个list的长度一样。比如:a=[1,2,3], b=[2,3,4]
- Turtle库是Python内置的图形化模块,属于标准库之一,位于Python安装目录的lib文件夹下,常用函数有以下几种:画笔控制函数pe
- 一般情况下,导出超时可能都是以下三种情况:一、sql语句复杂,查询时间过长;二、处理查询后数据逻辑冗余;三、数据量过大导致响应超时。接下来分
- 本文实例讲述了JavaScript设计模式之原型模式。分享给大家供大家参考,具体如下:从设计模式的角度讲,原型模式是用于创建对象的一种模式,
- 1、打开Sqlserver,选择登录名下的账户右击点击属性2、右击点击属性查看强制过期是否被勾选上,如勾选上,会在一段时间后该账户不能正常使
- 本文实例为大家分享了js瀑布流加载效果,动态加载图片,供大家参考,具体内容如下鼠标滚动事件,当鼠标滚动到下边,动态加载图片。1. HTML代
- 我就废话不多说了,大家还是直接看代码吧!# -*- coding: utf-8 -*-"""Created o
- 所谓的CSV(逗号分隔值)格式是电子表格和数据库最常用的导入和导出格式。尝试使用CSV格式进行标准化描述之前已经使用了很多年。该csv模块r
- MYSQL常用命令1.导出整个数据库mysqldump -u 用户名 -p --default-character-set=latin1 数
- 前言:由程序去执行的操作不允许有任何误差,有些时候在测试的时候未出现问题,但是放到服务器上就会报错,而且打印的错误信息并不十分明确。这时,我
- pytorch中为什么要用 zero_grad() 将梯度清零调用backward()函数之前都要将梯度清零,因为如果梯度不清零,pytor
- Mysql数据库是一个多用户,多线程的关系型数据库,是一个客户机/服务器结构的应用程序。它是对个人用户和商业用户是免费的.Mysql数据库具
- 一、常见的匹配规则二、常见的匹配方法1、match()match()方法从字符串的起始位置开始匹配,该方法有两个参数,第一个是正则表达式,第
- 利用OpenCV练习读取图片的时候,图片总是一闪而过,不利于观察,这个时候需要利用到waitKey函数。waitKey函数:用来等待按键,当
- 前两篇文章对NumPy数组做了基本的介绍,本篇文章对NumPy数组进行较深入的探讨。首先介绍自定义类型的数组,接着数组的组合,最后介绍数组复