欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

pytorch實(shí)現(xiàn)MNIST手寫(xiě)體識(shí)別

 更新時(shí)間:2020年02月14日 10:36:27   作者:fufu_good  
這篇文章主要為大家詳細(xì)介紹了pytorch實(shí)現(xiàn)MNIST手寫(xiě)體識(shí)別,使用全連接神經(jīng)網(wǎng)絡(luò),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了pytorch實(shí)現(xiàn)MNIST手寫(xiě)體識(shí)別的具體代碼,供大家參考,具體內(nèi)容如下

實(shí)驗(yàn)環(huán)境

pytorch 1.4
Windows 10
python 3.7
cuda 10.1(我筆記本上沒(méi)有可以使用cuda的顯卡)

實(shí)驗(yàn)過(guò)程

1. 確定我們要加載的庫(kù)

import torch
import torch.nn as nn
import torchvision #這里面直接加載MNIST數(shù)據(jù)的方法
import torchvision.transforms as transforms # 將數(shù)據(jù)轉(zhuǎn)為T(mén)ensor
import torch.optim as optim 
import torch.utils.data.dataloader as dataloader

2. 加載數(shù)據(jù)

這里使用所有數(shù)據(jù)進(jìn)行訓(xùn)練,再使用所有數(shù)據(jù)進(jìn)行測(cè)試

train_set = torchvision.datasets.MNIST(
 root='./data', # 文件存儲(chǔ)位置
 train=True,
 transform=transforms.ToTensor(),
 download=True
)

train_dataloader = dataloader.DataLoader(dataset=train_set,shuffle=False,batch_size=100)# dataset可以省

'''
dataloader返回(images,labels)
其中,
images維度:[batch_size,1,28,28]
labels:[batch_size],即圖片對(duì)應(yīng)的
'''

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

test_dataloader = dataloader.DataLoader(test_set,batch_size=100,shuffle=False) # dataset可以省

3. 定義神經(jīng)網(wǎng)絡(luò)模型

這里使用全神經(jīng)網(wǎng)絡(luò)作為模型

class NeuralNet(nn.Module):
 def __init__(self,in_num,h_num,out_num):
 super(NeuralNet,self).__init__()
 self.ln1 = nn.Linear(in_num,h_num)
 self.ln2 = nn.Linear(h_num,out_num)
 self.relu = nn.ReLU()
 
 def forward(self,x):
 return self.ln2(self.relu(self.ln1(x)))

4. 模型訓(xùn)練

in_num = 784 # 輸入維度
h_num = 500 # 隱藏層維度
out_num = 10 # 輸出維度
epochs = 30 # 迭代次數(shù)
learning_rate = 0.001
USE_CUDA = torch.cuda.is_available() # 定義是否可以使用cuda

model = NeuralNet(in_num,h_num,out_num) # 初始化模型
optimizer = optim.Adam(model.parameters(),lr=learning_rate) # 使用Adam
loss_fn = nn.CrossEntropyLoss() # 損失函數(shù)

for e in range(epochs):
 for i,data in enumerate(train_dataloader):
 (images,labels) = data
 images = images.reshape(-1,28*28) # [batch_size,784]
 if USE_CUDA:
  images = images.cuda() # 使用cuda
  labels = labels.cuda() # 使用cuda
  
 y_pred = model(images) # 預(yù)測(cè)
 loss = loss_fn(y_pred,labels) # 計(jì)算損失
 
 optimizer.zero_grad()
 loss.backward()
 optimizer.step()
 
 n = e * i +1
 if n % 100 == 0:
  print(n,'loss:',loss.item())

訓(xùn)練模型的loss部分截圖如下:

5. 測(cè)試模型

with torch.no_grad():
 total = 0
 correct = 0
 for (images,labels) in test_dataloader:
 images = images.reshape(-1,28*28)
 if USE_CUDA:
  images = images.cuda()
  labels = labels.cuda()
  
 result = model(images)
 prediction = torch.max(result, 1)[1] # 這里需要有[1],因?yàn)樗祷亓烁怕蔬€有標(biāo)簽
 total += labels.size(0)
 correct += (prediction == labels).sum().item()
 
 print("The accuracy of total {} images: {}%".format(total, 100 * correct/total))

實(shí)驗(yàn)結(jié)果

最終實(shí)驗(yàn)的正確率達(dá)到:98.22%

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論