PyTorch實(shí)現(xiàn)MNIST數(shù)據(jù)集手寫數(shù)字識(shí)別詳情
前言:
本篇文章基于卷積神經(jīng)網(wǎng)絡(luò)CNN,使用PyTorch實(shí)現(xiàn)MNIST數(shù)據(jù)集手寫數(shù)字識(shí)別。
一、PyTorch是什么?
PyTorch 是一個(gè) Torch7 團(tuán)隊(duì)開源的 Python 優(yōu)先的深度學(xué)習(xí)框架,提供兩個(gè)高級(jí)功能:
- 強(qiáng)大的 GPU 加速 Tensor 計(jì)算(類似 numpy)
- 構(gòu)建基于 tape 的自動(dòng)升級(jí)系統(tǒng)上的深度神經(jīng)網(wǎng)絡(luò)
你可以重用你喜歡的 python 包,如 numpy、scipy 和 Cython ,在需要時(shí)擴(kuò)展 PyTorch。
二、程序示例
下面案例可供運(yùn)行參考
1.引入必要庫(kù)
import torchvision import torch from torch.utils.data import DataLoader import torch.nn.functional as F
2.下載數(shù)據(jù)集
這里設(shè)置download=True,將會(huì)自動(dòng)下載數(shù)據(jù)集,并存儲(chǔ)在./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表示每一個(gè)batch中包含32張手寫數(shù)字圖片,shuffle=True表示打亂測(cè)試集(data和target仍一一對(duì)應(yīng))
train_loader = DataLoader(train_data,batch_size=32,shuffle=True) test_loader = DataLoader(test_data,batch_size=32,shuffle=False)
4.搭建CNN模型并實(shí)例化
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 #模型實(shí)例化 model = Net()
5.交叉熵?fù)p失函數(shù)損失函數(shù)及SGD算法優(yōu)化器
lossfun = torch.nn.CrossEntropyLoss() opt = torch.optim.SGD(model.parameters(),lr=0.01,momentum=0.5)
6.訓(xùn)練函數(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.測(cè)試函數(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.運(yùn)行
if __name__ == '__main__': for epoch in range(20): train(epoch) test()
三、總結(jié)
到此這篇關(guān)于PyTorch實(shí)現(xiàn)MNIST數(shù)據(jù)集手寫數(shù)字識(shí)別詳情的文章就介紹到這了,更多相關(guān)PyTorch MNIST 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python數(shù)據(jù)庫(kù)如何連接SQLite詳解
這篇文章主要介紹了Python實(shí)現(xiàn)連接SQLite數(shù)據(jù)庫(kù)的方法,在Python數(shù)據(jù)庫(kù)編程中有著廣泛的應(yīng)用,需要的朋友可以參考下,希望能給你帶來(lái)幫助2021-08-08關(guān)于Python八大排序?qū)崿F(xiàn)方法(冒泡排序、快速排序等)
這篇文章主要介紹了關(guān)于Python八大排序?qū)崿F(xiàn)方法,主要有基數(shù)排序、歸并排序、堆排序、簡(jiǎn)單選擇排序、直接插入排序、希爾排序、快速排序、冒泡排序等,需要的朋友可以參考下2023-03-03在CMD窗口中調(diào)用python函數(shù)的實(shí)現(xiàn)
本文主要介紹了在CMD窗口中調(diào)用python函數(shù)的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07教你用Python腳本快速為iOS10生成圖標(biāo)和截屏
這篇文章主要介紹了教你用Python快速為iOS10生成圖標(biāo)和截屏的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-09-09Python 實(shí)現(xiàn)兩個(gè)列表里元素對(duì)應(yīng)相乘的方法
今天小編就為大家分享一篇Python 實(shí)現(xiàn)兩個(gè)列表里元素對(duì)應(yīng)相乘的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-11-11