当前位置:网站首页>Handwritten character recognition
Handwritten character recognition
2022-07-29 09:05:00 【Salty salty】
import numpy as np
import torch
from torchvision.datasets import mnist # Import pytorch Built in mnist data
from torch import nn
from torch.autograd import Variable
Download datasets
train_set=mnist.MNIST('./data',train=True,download=True)
test_set=mnist.MNIST('./data',train=False,download=True)
a_data,a_lable=train_set[0] # Show the first data
a_data
![]()
a_lable
![]()
# The data read in earlier is pil Cut view in Library , Convert it to numpy array
a_data=np.array(a_data,dtype='float32')
print(a_data.shape)
![]()
print(a_data)

def data_tf(x):
x=np.array(x,dtype='float32')/255
x=(x-0.5)/0.5
x=x.reshape((-1,))
x=torch.from_numpy(x)
return x
train_set=mnist.MNIST('./data',train=True,transform=data_tf,download=True)
test_set=mnist.MNIST('./data',train=False,transform=data_tf,download=True)
a,a_lable=train_set[0]
print(a.shape)
print(a_lable)
from torch.utils.data import DataLoader
train_data=DataLoader(train_set,batch_size=64,shuffle=True)
test_data=DataLoader(test_set,batch_size=128,shuffle=False)
a,a_lable=next(iter(train_data))# use iter Convert array to lterator,next Will continue to return to the next element
print(a.shape)
print(a_lable.shape)
# Use Sequential Definition 4 Layer neural networks
net=nn.Sequential(
nn.Linear(784,400),
nn.ReLU(),
nn.Linear(400,200),
nn.ReLU(),
nn.Linear(200,100),
nn.ReLU(),
nn.Linear(100,10)
)
criterion=nn.CrossEntropyLoss()
optimizer=torch.optim.SGD(net.parameters(),1e-1)
losses=[]
acces=[]
eval_losses=[]
eval_acces=[]
for e in range(20):
train_loss=0
train_acc=0
net.train()
for im,lable in train_data:
im=Variable(im)
lable=Variable(lable)
out=net(im)
loss=criterion(out,lable)
optimizer.zero_grad()
loss.backward()
train_loss+=loss.item()
_,pred=out.max(1)
num_correct=(pred==lable).sum().item() # Statistical labels and the correctness of labels
acc=num_correct/im.shape[0]
train_acc+=acc
losses.append(train_loss/len(train_data))
acces.append(train_acc/len(train_data))
eval_loss=0
eval_acc=0
net.eval()
for im, lable in test_data:
im=Variable(im)
lable=Variable(lable)
out=net(im)
loss=criterion(out,lable)
eval_loss+=loss.item()
_,pred=out.max(1)
num_correct=(pred==lable).sum().item()
acc=num_correct/im.shape[0]
eval_acc+=acc
eval_losses.append(eval_loss/len(test_data))
eval_acces.append(eval_acc/len(test_data))
print('epoch: {}, Train Loss: {:.6f}, Train Acc: {:.6f}, Eval Loss: {:.6f}, EvalAcc: {:.6f}'.format(e, train_loss / len(train_data), train_acc / len(train_data),
eval_loss / len(test_data), eval_acc / len(test_data)))
We can draw it train loss,train acc,test loss,test acc Graph

边栏推荐
- 四元数与其在Unity中的简单应用
- GBase 8s数据库有哪些备份恢复方式
- 用户身份标识与账号体系实践
- Sublime text create page
- Cloud security daily 220712: the IBM integration bus integration solution has found a vulnerability in the execution of arbitrary code, which needs to be upgraded as soon as possible
- Common query optimization technology of data Lake - "deepnova developer community"
- Notes on network principles (five layer network)
- AI is at the forefront | focusing on natural language processing, machine learning and other fields; From Fudan University, Institute of automation, Chinese Academy of Sciences and other teams
- Multiple knapsack, simplicity and binary optimization
- How does alternates achieve high-performance publish and subscribe?
猜你喜欢

Excellent Allegro skill recommendation

2022电工(初级)考题模拟考试平台操作

2022年R2移动式压力容器充装考题模拟考试平台操作

Leetcode question brushing (6)

Demonstration and solution of dirty reading, unrepeatable reading and unreal reading

【Unity入门计划】C#与Unity-了解类和对象

How does alternates achieve high-performance publish and subscribe?

Sword finger offer 26. substructure of tree

2022.7.9 quick view of papers

2022年P气瓶充装考试模拟100题模拟考试平台操作
随机推荐
Sword finger offer 32 - ii Print binary tree II from top to bottom
2022年R2移动式压力容器充装考题模拟考试平台操作
[C language] DataGridView binding data
File upload and expansion
GBase 8s数据库有哪些备份恢复方式
(视频+图文)机器学习入门系列-第2章 线性回归
Design of distributed (cluster) file system
[unity entry program] C # and unity - understand classes and objects
Complete knapsack problem from simplicity to ultimate
Excellent Allegro skill recommendation
Unity3d learning notes (I)
Asp graduation project - based on C # +asp Design and implementation of enterprise investment value analysis system based on. Net + sqlserver (graduation thesis + program source code) -- enterprise in
用户身份标识与账号体系实践
Intel将逐步结束Optane存储业务 未来不再开发新产品
文件上传及拓展
MySQL error summary
Curl -v | JQ
Flowable 高级篇
Cloud security daily 220712: the IBM integration bus integration solution has found a vulnerability in the execution of arbitrary code, which needs to be upgraded as soon as possible
201803-3 CCF URL映射 满分题解