超詳細(xì)PyTorch實(shí)現(xiàn)手寫數(shù)字識(shí)別器的示例代碼
前言
深度學(xué)習(xí)中有很多玩具數(shù)據(jù),mnist
就是其中一個(gè),一個(gè)人能否入門深度學(xué)習(xí)往往就是以能否玩轉(zhuǎn)mnist
數(shù)據(jù)來判斷的,在前面很多基礎(chǔ)介紹后我們就可以來實(shí)現(xiàn)一個(gè)簡(jiǎn)單的手寫數(shù)字識(shí)別的網(wǎng)絡(luò)了
數(shù)據(jù)的處理
我們使用pytorch自帶的包進(jìn)行數(shù)據(jù)的預(yù)處理
import torch import torchvision import torchvision.transforms as transforms import numpy as np import matplotlib.pyplot as plt transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5), (0.5)) ]) trainset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size=32, shuffle=True,num_workers=2)
注釋
:transforms.Normalize
用于數(shù)據(jù)的標(biāo)準(zhǔn)化,具體實(shí)現(xiàn)
mean
:均值 總和后除個(gè)數(shù)
std
:方差 每個(gè)元素減去均值再平方再除個(gè)數(shù)
norm_data = (tensor - mean) / std
這里就直接將圖片標(biāo)準(zhǔn)化到了-1到1的范圍,標(biāo)準(zhǔn)化的原因就是因?yàn)槿绻硞€(gè)數(shù)在數(shù)據(jù)中很大很大,就導(dǎo)致其權(quán)重較大,從而影響到其他數(shù)據(jù),而本身我們的數(shù)據(jù)都是平等的,所以標(biāo)準(zhǔn)化后將數(shù)據(jù)分布到-1到1的范圍,使得所有數(shù)據(jù)都不會(huì)有太大的權(quán)重導(dǎo)致網(wǎng)絡(luò)出現(xiàn)巨大的波動(dòng)
trainloader
現(xiàn)在是一個(gè)可迭代的對(duì)象,那么我們可以使用for
循環(huán)進(jìn)行遍歷了,由于是使用yield返回的數(shù)據(jù),為了節(jié)約內(nèi)存
觀察一下數(shù)據(jù)
def imshow(img): img = img / 2 + 0.5 # unnormalize npimg = img.numpy() plt.imshow(np.transpose(npimg, (1, 2, 0))) plt.show() # torchvision.utils.make_grid 將圖片進(jìn)行拼接 imshow(torchvision.utils.make_grid(iter(trainloader).next()[0]))
構(gòu)建網(wǎng)絡(luò)
from torch import nn import torch.nn.functional as F class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(in_channels=1, out_channels=28, kernel_size=5) # 14 self.pool = nn.MaxPool2d(kernel_size=2, stride=2) # 無參數(shù)學(xué)習(xí)因此無需設(shè)置兩個(gè) self.conv2 = nn.Conv2d(in_channels=28, out_channels=28*2, kernel_size=5) # 7 self.fc1 = nn.Linear(in_features=28*2*4*4, out_features=1024) self.fc2 = nn.Linear(in_features=1024, out_features=10) def forward(self, inputs): x = self.pool(F.relu(self.conv1(inputs))) x = self.pool(F.relu(self.conv2(x))) x = x.view(inputs.size()[0],-1) x = F.relu(self.fc1(x)) return self.fc2(x)
下面是卷積的動(dòng)態(tài)演示
in_channels
:為輸入通道數(shù) 彩色圖片有3個(gè)通道 黑白有1個(gè)通道
out_channels
:輸出通道數(shù)
kernel_size
:卷積核的大小
stride
:卷積的步長(zhǎng)
padding
:外邊距大小
輸出的size計(jì)算公式
- h = (h - kernel_size + 2*padding)/stride + 1
- w = (w - kernel_size + 2*padding)/stride + 1
MaxPool2d
:是沒有參數(shù)進(jìn)行運(yùn)算的
實(shí)例化網(wǎng)絡(luò)優(yōu)化器,并且使用GPU進(jìn)行訓(xùn)練
net = Net() opt = torch.optim.Adam(params=net.parameters(), lr=0.001) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") net.to(device)
Net( (conv1): Conv2d(1, 28, kernel_size=(5, 5), stride=(1, 1)) (pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False) (conv2): Conv2d(28, 56, kernel_size=(5, 5), stride=(1, 1)) (fc1): Linear(in_features=896, out_features=1024, bias=True) (fc2): Linear(in_features=1024, out_features=10, bias=True) )
訓(xùn)練主要代碼
for epoch in range(50): for images, labels in trainloader: images = images.to(device) labels = labels.to(device) pre_label = net(images) loss = F.cross_entropy(input=pre_label, target=labels).mean() pre_label = torch.argmax(pre_label, dim=1) acc = (pre_label==labels).sum()/torch.tensor(labels.size()[0], dtype=torch.float32) net.zero_grad() loss.backward() opt.step() print(acc.detach().cpu().numpy(), loss.detach().cpu().numpy())
F.cross_entropy
交叉熵函數(shù)
源碼中已經(jīng)幫助我們實(shí)現(xiàn)了softmax
因此不需要自己進(jìn)行softmax
操作了
torch.argmax
計(jì)算最大數(shù)所在索引值
acc = (pre_label==labels).sum()/torch.tensor(labels.size()[0], dtype=torch.float32) # pre_label==labels 相同維度進(jìn)行比較相同返回True不同的返回False,True為1 False為0, 即可獲取到相等的個(gè)數(shù),再除總個(gè)數(shù),就得到了Accuracy準(zhǔn)確度了
預(yù)測(cè)
testset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform) testloader = torch.utils.data.DataLoader(testset, batch_size=128, shuffle=True,num_workers=2) images, labels = iter(testloader).next() images = images.to(device) labels = labels.to(device) with torch.no_grad(): pre_label = net(images) pre_label = torch.argmax(pre_label, dim=1) acc = (pre_label==labels).sum()/torch.tensor(labels.size()[0], dtype=torch.float32) print(acc)
總結(jié)
本節(jié)我們了解了標(biāo)準(zhǔn)化數(shù)據(jù)·
、卷積的原理
、簡(jiǎn)答的構(gòu)建了一個(gè)網(wǎng)絡(luò)
,并讓它去識(shí)別手寫體,也是對(duì)前面章節(jié)的總匯了
到此這篇關(guān)于超詳細(xì)PyTorch實(shí)現(xiàn)手寫數(shù)字識(shí)別器的示例代碼的文章就介紹到這了,更多相關(guān)PyTorch 手寫數(shù)字識(shí)別器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python OpenCV 彩色與灰度圖像的轉(zhuǎn)換實(shí)現(xiàn)
為了加快處理速度在圖像處理算法中,往往需要把彩色圖像轉(zhuǎn)換為灰度圖像,本文主要介紹了Python OpenCV 彩色與灰度圖像的轉(zhuǎn)換實(shí)現(xiàn),感興趣的可以了解一下2021-06-06查看TensorFlow checkpoint文件中的變量名和對(duì)應(yīng)值方法
今天小編就為大家分享一篇查看TensorFlow checkpoint文件中的變量名和對(duì)應(yīng)值方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-06-06python數(shù)據(jù)分析之將爬取的數(shù)據(jù)保存為csv格式
Python內(nèi)置了CSV模塊,可直接通過該模塊實(shí)現(xiàn)csv文件的讀寫操作,在web應(yīng)用中導(dǎo)出數(shù)據(jù)是比較常見操作,下面這篇文章主要給大家介紹了關(guān)于python數(shù)據(jù)分析之將爬取的數(shù)據(jù)保存為csv格式的相關(guān)資料,需要的朋友可以參考下2022-06-06Python 文件操作技巧(File operation) 實(shí)例代碼分析
python遍歷文件夾和文件 perl分割路徑和文件名2008-08-08python高溫預(yù)警數(shù)據(jù)獲取實(shí)例
這篇文章主要為大家介紹了利用python獲取高溫?cái)?shù)據(jù)進(jìn)行高溫預(yù)警的防護(hù)措施,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07