PyTorch實現(xiàn)MNIST數(shù)據(jù)集手寫數(shù)字識別詳情
前言:
本篇文章基于卷積神經(jīng)網(wǎng)絡CNN,使用PyTorch實現(xiàn)MNIST數(shù)據(jù)集手寫數(shù)字識別。
一、PyTorch是什么?
PyTorch 是一個 Torch7 團隊開源的 Python 優(yōu)先的深度學習框架,提供兩個高級功能:
- 強大的 GPU 加速 Tensor 計算(類似 numpy)
- 構(gòu)建基于 tape 的自動升級系統(tǒng)上的深度神經(jīng)網(wǎng)絡
你可以重用你喜歡的 python 包,如 numpy、scipy 和 Cython ,在需要時擴展 PyTorch。
二、程序示例
下面案例可供運行參考
1.引入必要庫
import torchvision import torch from torch.utils.data import DataLoader import torch.nn.functional as F
2.下載數(shù)據(jù)集
這里設置download=True,將會自動下載數(shù)據(jù)集,并存儲在./data文件夾。
train_data = torchvision.datasets.MNIST(root="./data",train=True,transform=torchvision.transforms.ToTensor(),download=True) test_data = torchvision.datasets.MNIST(root="./data",train=False,transform=torchvision.transforms.ToTensor(),download=True)
3.加載數(shù)據(jù)集
batch_size=32表示每一個batch中包含32張手寫數(shù)字圖片,shuffle=True表示打亂測試集(data和target仍一一對應)
train_loader = DataLoader(train_data,batch_size=32,shuffle=True) test_loader = DataLoader(test_data,batch_size=32,shuffle=False)
4.搭建CNN模型并實例化
class Net(torch.nn.Module): def __init__(self): super(Net,self).__init__() self.con1 = torch.nn.Conv2d(1,10,kernel_size=5) self.con2 = torch.nn.Conv2d(10,20,kernel_size=5) self.pooling = torch.nn.MaxPool2d(2) self.fc = torch.nn.Linear(320,10) def forward(self,x): batch_size = x.size(0) x = F.relu(self.pooling(self.con1(x))) x = F.relu(self.pooling(self.con2(x))) x = x.view(batch_size,-1) x = self.fc(x) return x #模型實例化 model = Net()
5.交叉熵損失函數(shù)損失函數(shù)及SGD算法優(yōu)化器
lossfun = torch.nn.CrossEntropyLoss() opt = torch.optim.SGD(model.parameters(),lr=0.01,momentum=0.5)
6.訓練函數(shù)
def train(epoch): running_loss = 0.0 for i,(inputs,targets) in enumerate(train_loader,0): # inputs,targets = inputs.to(device),targets.to(device) opt.zero_grad() outputs = model(inputs) loss = lossfun(outputs,targets) loss.backward() opt.step() running_loss += loss.item() if i % 300 == 299: print('[%d,%d] loss:%.3f' % (epoch+1,i+1,running_loss/300)) running_loss = 0.0
7.測試函數(shù)
def test(): total = 0 correct = 0 with torch.no_grad(): for (inputs,targets) in test_loader: # inputs, targets = inputs.to(device), targets.to(device) outputs = model(inputs) _,predicted = torch.max(outputs.data,dim=1) total += targets.size(0) correct += (predicted == targets).sum().item() print(100*correct/total)
8.運行
if __name__ == '__main__': for epoch in range(20): train(epoch) test()
三、總結(jié)
到此這篇關(guān)于PyTorch實現(xiàn)MNIST數(shù)據(jù)集手寫數(shù)字識別詳情的文章就介紹到這了,更多相關(guān)PyTorch MNIST 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python數(shù)據(jù)庫如何連接SQLite詳解
這篇文章主要介紹了Python實現(xiàn)連接SQLite數(shù)據(jù)庫的方法,在Python數(shù)據(jù)庫編程中有著廣泛的應用,需要的朋友可以參考下,希望能給你帶來幫助2021-08-08關(guān)于Python八大排序?qū)崿F(xiàn)方法(冒泡排序、快速排序等)
這篇文章主要介紹了關(guān)于Python八大排序?qū)崿F(xiàn)方法,主要有基數(shù)排序、歸并排序、堆排序、簡單選擇排序、直接插入排序、希爾排序、快速排序、冒泡排序等,需要的朋友可以參考下2023-03-03在CMD窗口中調(diào)用python函數(shù)的實現(xiàn)
本文主要介紹了在CMD窗口中調(diào)用python函數(shù)的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-07-07