婷婷综合国产,91蜜桃婷婷狠狠久久综合9色 ,九九九九九精品,国产综合av

主頁(yè) > 知識(shí)庫(kù) > 超詳細(xì)PyTorch實(shí)現(xiàn)手寫(xiě)數(shù)字識(shí)別器的示例代碼

超詳細(xì)PyTorch實(shí)現(xiàn)手寫(xiě)數(shù)字識(shí)別器的示例代碼

熱門(mén)標(biāo)簽:原裝電話機(jī)器人 西藏智能外呼系統(tǒng)五星服務(wù) 千陽(yáng)自動(dòng)外呼系統(tǒng) 平頂山外呼系統(tǒng)免費(fèi) 清遠(yuǎn)360地圖標(biāo)注方法 400電話申請(qǐng)服務(wù)商選什么 工廠智能電話機(jī)器人 在哪里辦理400電話號(hào)碼 江蘇客服外呼系統(tǒng)廠家

前言

深度學(xué)習(xí)中有很多玩具數(shù)據(jù),mnist就是其中一個(gè),一個(gè)人能否入門(mén)深度學(xué)習(xí)往往就是以能否玩轉(zhuǎn)mnist數(shù)據(jù)來(lái)判斷的,在前面很多基礎(chǔ)介紹后我們就可以來(lái)實(shí)現(xiàn)一個(gè)簡(jiǎn)單的手寫(xiě)數(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) # 無(wú)參數(shù)學(xué)習(xí)因此無(wú)需設(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:是沒(méi)有參數(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í)別手寫(xiě)體,也是對(duì)前面章節(jié)的總匯了

到此這篇關(guān)于超詳細(xì)PyTorch實(shí)現(xiàn)手寫(xiě)數(shù)字識(shí)別器的示例代碼的文章就介紹到這了,更多相關(guān)PyTorch 手寫(xiě)數(shù)字識(shí)別器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • pytorch 利用lstm做mnist手寫(xiě)數(shù)字識(shí)別分類的實(shí)例
  • 詳解PyTorch手寫(xiě)數(shù)字識(shí)別(MNIST數(shù)據(jù)集)
  • PyTorch CNN實(shí)戰(zhàn)之MNIST手寫(xiě)數(shù)字識(shí)別示例
  • Pytorch實(shí)現(xiàn)圖像識(shí)別之?dāng)?shù)字識(shí)別(附詳細(xì)注釋)

標(biāo)簽:天水 錦州 隨州 股票 日照 白城 西安 安慶

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《超詳細(xì)PyTorch實(shí)現(xiàn)手寫(xiě)數(shù)字識(shí)別器的示例代碼》,本文關(guān)鍵詞  超,詳細(xì),PyTorch,實(shí)現(xiàn),手寫(xiě),;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《超詳細(xì)PyTorch實(shí)現(xiàn)手寫(xiě)數(shù)字識(shí)別器的示例代碼》相關(guān)的同類信息!
  • 本頁(yè)收集關(guān)于超詳細(xì)PyTorch實(shí)現(xiàn)手寫(xiě)數(shù)字識(shí)別器的示例代碼的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    主站蜘蛛池模板: 兰西县| 济宁市| 东城区| 滨州市| 周口市| 枞阳县| 汾阳市| 奎屯市| 北京市| 华蓥市| 威信县| 大余县| 平江县| 清丰县| 濮阳市| 荆州市| 昌宁县| 监利县| 赣州市| 鸡西市| 玉环县| 沭阳县| 龙游县| 清徐县| 威信县| 黄大仙区| 旬邑县| 溧阳市| 锡林浩特市| 美姑县| 黄浦区| 岳阳县| 梅州市| 基隆市| 富顺县| 巴马| 赞皇县| 湄潭县| 绍兴县| 鲁甸县| 林口县|