最美情侣中文字幕电影,在线麻豆精品传媒,在线网站高清黄,久久黄色视频

歡迎光臨散文網(wǎng) 會(huì)員登陸 & 注冊(cè)

Pytorch學(xué)習(xí)筆記8:MNIST多分類實(shí)踐(GPU版本)

2020-12-03 10:02 作者:車科技2020  | 我要投稿

#需要import的lib?

import torch?

import numpy as np?

from matplotlib import pyplot as plt?

from mpl_toolkits.mplot3d import Axes3D?

from torchvision import datasets, transforms?

from torch.utils.data import DataLoader?

?#需要import的lib

print('——————————用GPU加速M(fèi)NIST——————————')
#加載數(shù)據(jù)
batch_size=200
learning_rate=0.01
epochs=10

train_loader=torch.utils.data.DataLoader(
? ?datasets.MNIST('../data',train=True,download=True,
? ? ? ? ? ? ? ? ? transform=transforms.Compose(
? ? ? ? ? ? ? ? ? ? ? [
? ? ? ? ? ? ? ? ? ? ? ? ? transforms.ToTensor(),
? ? ? ? ? ? ? ? ? ? ? ? ? transforms.Normalize((0.1307,),(0.3081,))
? ? ? ? ? ? ? ? ? ? ? ]
? ? ? ? ? ? ? ? ? )

? ?),
? ?batch_size=batch_size,shuffle=True #每個(gè)batch load的數(shù)據(jù),是不是打亂每個(gè)batch的數(shù)據(jù)
)
test_loader=torch.utils.data.DataLoader(
? ?datasets.MNIST('../data',train=False,
? ? ? ? ? ? ? ? ? transform=transforms.Compose(
? ? ? ? ? ? ? ? ? ? ? [
? ? ? ? ? ? ? ? ? ? ? ? ? transforms.ToTensor(),
? ? ? ? ? ? ? ? ? ? ? ? ? transforms.Normalize((0.1307,),(0.3081,))
? ? ? ? ? ? ? ? ? ? ? ]
? ? ? ? ? ? ? ? ? )

? ?),
? ?batch_size=batch_size,shuffle=True #每個(gè)batch load的數(shù)據(jù),是不是打亂每個(gè)batch的數(shù)據(jù)
)
#寫網(wǎng)絡(luò)模型
class MLP1(torch.nn.Module):
? ?def __init__(self):
? ? ? ?super(MLP1, self).__init__()
? ? ? ?self.model= torch.nn.Sequential(
? ? ? ? ? ?torch.nn.Linear(784, 200),
? ? ? ? ? ?torch.nn.LeakyReLU(inplace=True),
? ? ? ? ? ?torch.nn.Linear(200, 200),
? ? ? ? ? ?torch.nn.LeakyReLU(inplace=True),
? ? ? ? ? ?torch.nn.Linear(200, 10),
? ? ? ? ? ?torch.nn.LeakyReLU(inplace=True),
? ? ? ?)
def forward(self,x):#自定義forword函數(shù)
? ?x=self.model(x)
? ?return x
device=torch.device('cuda:0')
net=MLP1().to(device)
optimizer=torch.optim.SGD(net.parameters(),lr=learning_rate)
criteon=torch.nn.CrossEntropyLoss().to(device)

#迭代優(yōu)化過(guò)程
for epoch in range(epochs):
? ?for batch_idx,(data,target) in enumerate(train_loader):
? ? ? ?data=data.view(-1,28*28)
? ? ? ?data,target=data.to(device),target.to(device)

? ? ? ?logits=forward(net,data) #把數(shù)據(jù)放入神經(jīng)網(wǎng)絡(luò)得出pred的值
? ? ? ?loss=criteon(logits,target) #用loss函數(shù)計(jì)算pred和target的差
? ? ? ?optimizer.zero_grad() #清零梯度
? ? ? ?loss.backward() #重新計(jì)算梯度

? ? ? ?optimizer.step() #用新的梯度計(jì)算新的w b,然后迭代

? ? ? ?if batch_idx % 100 == 0:
? ? ? ? ? ?#print('epoch:',epoch)
? ? ? ? ? ?#print('batch_idx:', batch_idx)
? ? ? ? ? ?#print('len data', len(data))
? ? ? ? ? ?#print('len(train_loader.dataset)', len(train_loader.dataset))
? ? ? ? ? ?#print('len(train_loader)', len(train_loader))
? ? ? ? ? ?print(
? ? ? ? ? ? ? ?'train epoch:{}[{}/{}({:.0f}%)]\tLoss:{:.6f}'.format(
? ? ? ? ? ? ? ? ? ?epoch,batch_idx * len(data), len(train_loader.dataset),
? ? ? ? ? ? ? ? ? ?100. * batch_idx / len(train_loader),loss.item()
? ? ? ? ? ? ? ?)
? ? ? ? ? ?)

? ?test_loss=0
? ?correct=0
? ?for data,target in test_loader:
? ? ? ?data=data.view(-1,28*28)
? ? ? ?data, target = data.to(device), target.to(device)
? ? ? ?logits = forward(net,data)#把數(shù)據(jù)放入神經(jīng)網(wǎng)絡(luò)得出pred的值
? ? ? ?test_loss +=criteon(logits,target).item()#?累加loss

? ? ? ?pred =logits.data.max(1)[1]#得出pred的最大值,就是網(wǎng)絡(luò)識(shí)別出來(lái)的數(shù)字
? ? ? ?correct +=pred.eq(target.data).sum()#?target.data
? ?test_loss /=len(test_loader.dataset)
? ?#print('len(test_loader.dataset):', len(test_loader.dataset))
? ?print(
? ? ? ?'\ntest set:avg loss:{:.4f},accu:{}/{} ({:.0f}%)\n'.format(
? ? ? ? ? ?test_loss,correct,len(test_loader.dataset),
? ? ? ? ? ?100.*correct/len(test_loader.dataset)
? ? ? ?)
? ?)

print('——————————用GPU加速M(fèi)NIST——————————')


Pytorch學(xué)習(xí)筆記8:MNIST多分類實(shí)踐(GPU版本)的評(píng)論 (共 條)

分享到微博請(qǐng)遵守國(guó)家法律
邹城市| 新津县| 成都市| 酉阳| 清涧县| 朝阳县| 屯留县| 井研县| 莫力| 巧家县| 安化县| 湟中县| 肇东市| 乌恰县| 祁门县| 民和| 红原县| 布尔津县| 应城市| 洪湖市| 定结县| 金山区| 塔河县| 巢湖市| 晋城| 呼伦贝尔市| 塔城市| 闽侯县| 台湾省| 明星| 舒城县| 淳安县| 印江| 建湖县| 邛崃市| 左权县| 齐齐哈尔市| 金门县| 沙河市| 莆田市| 航空|