pytorch實現(xiàn)MNIST手寫體識別
本文實例為大家分享了pytorch實現(xiàn)MNIST手寫體識別的具體代碼,供大家參考,具體內(nèi)容如下
實驗環(huán)境
pytorch 1.4
Windows 10
python 3.7
cuda 10.1(我筆記本上沒有可以使用cuda的顯卡)
實驗過程
1. 確定我們要加載的庫
import torch import torch.nn as nn import torchvision #這里面直接加載MNIST數(shù)據(jù)的方法 import torchvision.transforms as transforms # 將數(shù)據(jù)轉(zhuǎn)為Tensor 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)行測試
train_set = torchvision.datasets.MNIST( root='./data', # 文件存儲位置 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],即圖片對應(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ù)測 loss = loss_fn(y_pred,labels) # 計算損失 optimizer.zero_grad() loss.backward() optimizer.step() n = e * i +1 if n % 100 == 0: print(n,'loss:',loss.item())
訓(xùn)練模型的loss部分截圖如下:
5. 測試模型
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],因為它返回了概率還有標(biāo)簽 total += labels.size(0) correct += (prediction == labels).sum().item() print("The accuracy of total {} images: {}%".format(total, 100 * correct/total))
實驗結(jié)果
最終實驗的正確率達(dá)到:98.22%
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python實現(xiàn)學(xué)生管理系統(tǒng)(面向?qū)ο蟀?
這篇文章主要為大家詳細(xì)介紹了Python實現(xiàn)面向?qū)ο蟀娴膶W(xué)生管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-06-06Django 如何使用日期時間選擇器規(guī)范用戶的時間輸入示例代碼詳解
這篇文章主要介紹了 Django 如何使用日期時間選擇器規(guī)范用戶的時間輸入,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05Python實現(xiàn)動態(tài)條形圖繪制的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何利用Python語言實現(xiàn)動態(tài)條形圖的繪制,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2022-08-08