前言
本文參考PyTorch官網(wǎng)的教程,分為五個(gè)基本模塊來(lái)介紹PyTorch。為了避免文章過長(zhǎng),這五個(gè)模塊分別在五篇博文中介紹。
Part3:使用PyTorch構(gòu)建一個(gè)神經(jīng)網(wǎng)絡(luò)
神經(jīng)網(wǎng)絡(luò)可以使用touch.nn來(lái)構(gòu)建。nn依賴于autograd來(lái)定義模型,并且對(duì)其求導(dǎo)。一個(gè)nn.Module包含網(wǎng)絡(luò)的層(layers),同時(shí)forward(input)可以返回output。
這是一個(gè)簡(jiǎn)單的前饋網(wǎng)絡(luò)。它接受輸入,然后一層一層向前傳播,最后輸出一個(gè)結(jié)果。
訓(xùn)練神經(jīng)網(wǎng)絡(luò)的典型步驟如下:
(1) 定義神經(jīng)網(wǎng)絡(luò),該網(wǎng)絡(luò)包含一些可以學(xué)習(xí)的參數(shù)(如權(quán)重)
(2) 在輸入數(shù)據(jù)集上進(jìn)行迭代
(3) 使用網(wǎng)絡(luò)對(duì)輸入數(shù)據(jù)進(jìn)行處理
(4) 計(jì)算loss(輸出值距離正確值有多遠(yuǎn))
(5) 將梯度反向傳播到網(wǎng)絡(luò)參數(shù)中
(6) 更新網(wǎng)絡(luò)的權(quán)重,使用簡(jiǎn)單的更新法則:weight = weight - learning_rate* gradient,即:新的權(quán)重=舊的權(quán)重-學(xué)習(xí)率*梯度值。
1 定義網(wǎng)絡(luò)
我們先定義一個(gè)網(wǎng)絡(luò):
import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def __init__(self): super(Net, self).__init__() # 1 input image channel, 6 output channels, 5x5 square convolution # kernel self.conv1 = nn.Conv2d(1, 6, 5) self.conv2 = nn.Conv2d(6, 16, 5) # an affine operation: y = Wx + b self.fc1 = nn.Linear(16 * 5 * 5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x): # Max pooling over a (2, 2) window x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) # If the size is a square you can only specify a single number x = F.max_pool2d(F.relu(self.conv2(x)), 2) x = x.view(-1, self.num_flat_features(x)) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x def num_flat_features(self, x): size = x.size()[1:] # all dimensions except the batch dimension num_features = 1 for s in size: num_features *= s return num_features net = Net() print(net)
名稱欄目:PyTorch的深度學(xué)習(xí)入門教程之構(gòu)建神經(jīng)網(wǎng)絡(luò)-創(chuàng)新互聯(lián)
當(dāng)前網(wǎng)址:http://jinyejixie.com/article18/dshpgp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)頁(yè)設(shè)計(jì)公司、面包屑導(dǎo)航、網(wǎng)站內(nèi)鏈、外貿(mào)網(wǎng)站建設(shè)、定制開發(fā)、網(wǎng)站設(shè)計(jì)公司
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容