前言
本文參考PyTorch官網的教程,分為五個基本模塊來介紹PyTorch。為了避免文章過長,這五個模塊分別在五篇博文中介紹。
Part3:使用PyTorch構建一個神經網絡
神經網絡可以使用touch.nn來構建。nn依賴于autograd來定義模型,并且對其求導。一個nn.Module包含網絡的層(layers),同時forward(input)可以返回output。
這是一個簡單的前饋網絡。它接受輸入,然后一層一層向前傳播,最后輸出一個結果。
訓練神經網絡的典型步驟如下:
(1) 定義神經網絡,該網絡包含一些可以學習的參數(如權重)
(2) 在輸入數據集上進行迭代
(3) 使用網絡對輸入數據進行處理
(4) 計算loss(輸出值距離正確值有多遠)
(5) 將梯度反向傳播到網絡參數中
(6) 更新網絡的權重,使用簡單的更新法則:weight = weight - learning_rate* gradient,即:新的權重=舊的權重-學習率*梯度值。
1 定義網絡
我們先定義一個網絡:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
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) |
預期輸出:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
Net ( (conv1): Conv2d( 1 , 6 , kernel_size = ( 5 , 5 ), stride = ( 1 , 1 )) (conv2): Conv2d( 6 , 16 , kernel_size = ( 5 , 5 ), stride = ( 1 , 1 )) (fc1): Linear ( 400 - > 120 ) (fc2): Linear ( 120 - > 84 ) (fc3): Linear ( 84 - > 10 ) ) |
你只需要定義forward函數,那么backward函數(梯度在此函數中計算)就會利用autograd來自動定義。你可以在forward函數中使用Tensor的任何運算。
學習到的參數可以被net.parameters()返回。
1
2
3
|
params = list (net.parameters()) print ( len (params)) print (params[ 0 ].size()) # conv1's .weight |
預期輸出:
10
torch.Size([6, 1, 5, 5])
前向計算的輸入和輸出都是autograd.Variable,注意,這個網絡(LeNet)的輸入尺寸是32*32。為了在MNIST數據集上使用這個網絡,請把圖像大小轉變為32*32。
1
2
3
|
input = Variable(torch.randn( 1 , 1 , 32 , 32 )) out = net( input ) print (out) |
預期輸出:
Variable containing:
-0.0796 0.0330 0.0103 0.0250 0.1153 -0.0136 0.0234 0.0881 0.0374 -0.0359
[torch.FloatTensor of size 1x10]
將梯度緩沖區歸零,然后使用隨機梯度值進行反向傳播。
1
2
|
net.zero_grad() out.backward(torch.randn( 1 , 10 )) |
注意:torch.nn只支持mini-batches. 完整的torch.nn package只支持mini-batch形式的樣本作為輸入,并且不能只包含一個樣本。例如,nn.Conv2d會采用一個4D的Tensor(nSamples* nChannels * Height * Width)。如果你有一個單樣本,可以使用input.unsqueeze(0)來添加一個虛假的批量維度。
在繼續之前,讓我們回顧一下迄今為止所見過的所有類。
概述:
(1) torch.Tensor——多維數組
(2) autograd.Variable——包裝了一個Tensor,并且記錄了應用于其上的運算。與Tensor具有相同的API,同時增加了一些新東西例如backward()。并且有相對于該tensor的梯度值。
(3) nn.Module——神經網絡模塊。封裝參數的簡便方式,對于參數向GPU移動,以及導出、加載等有幫助。
(4) nn.Parameter——這是一種變量(Variable),當作為一個屬性(attribute)分配到一個模塊(Module)時,可以自動注冊為一個參數(parameter)。
(5) autograd.Function——執行自動求導運算的前向和反向定義。每一個Variable運算,創建至少一個單獨的Function節點,該節點連接到創建了Variable并且編碼了它的歷史的函數身上。
2 損失函數(Loss Function)
損失函數采用輸出值和目標值作為輸入參數,來計算輸出值距離目標值還有多大差距。在nn package中有很多種不同的損失函數,最簡單的一個loss就是nn.MSELoss,它計算輸出值和目標值之間的均方差。
例如:
1
2
3
4
5
6
|
output = net( input ) target = Variable(torch.arange( 1 , 11 )) # a dummy target, for example criterion = nn.MSELoss() loss = criterion(output, target) print (loss) |
現在,從反向看loss,使用.grad_fn屬性,你會看到一個計算graph如下:
1
2
3
4
|
input - > conv2d - > relu - > maxpool2d - > conv2d - > relu - > maxpool2d - > view - > linear - > relu - > linear - > relu - > linear - > MSELoss - > loss |
當我們調用loss.backward(),整個的graph關于loss求導,graph中的所有Variables都會有他們自己的.grad變量。
為了理解,我們進行幾個反向步驟。
1
2
3
|
print (loss.grad_fn) # MSELoss print (loss.grad_fn.next_functions[ 0 ][ 0 ]) # Linear print (loss.grad_fn.next_functions[ 0 ][ 0 ].next_functions[ 0 ][ 0 ]) # ReLU |
預期輸出:
1
2
3
4
5
|
< torch.autograd.function.MSELossBackwardobjectat0x7fb3c0dcf4f8 > < torch.autograd.function.AddmmBackwardobjectat0x7fb3c0dcf408 > < AccumulateGradobjectat0x7fb3c0db79e8 > |
3 反向傳播(Backprop)
可以使用loss.backward()進行誤差反向傳播。你需要清除已經存在的梯度值,否則梯度將會積累到現有的梯度上。
現在,我們調用loss.backward(),看一看conv1的bias 梯度在backward之前和之后的值。
1
2
3
4
5
6
7
8
9
|
net.zero_grad() # zeroes the gradient buffers of all parameters print ( 'conv1.bias.grad before backward' ) print (net.conv1.bias.grad) loss.backward() print ( 'conv1.bias.grad after backward' ) print (net.conv1.bias.grad) |
4 更新權重
實踐當中最簡單的更新法則就是隨機梯度下降法( StochasticGradient Descent (SGD))
1
|
weight = weight - learning_rate * gradient |
執行這個操作的python代碼如下:
1
2
3
|
learning_rate = 0.01 for f in net.parameters(): f.data.sub_(f.grad.data * learning_rate) |
但是當你使用神經網絡的時候,你可能會想要嘗試多種不同的更新法則,例如SGD,Nesterov-SGD, Adam, RMSProp等。為了實現此功能,有一個package叫做torch.optim已經實現了這些。使用它也很方便:
1
2
3
4
5
6
7
8
9
10
11
|
import torch.optim as optim # create your optimizer optimizer = optim.SGD(net.parameters(), lr = 0.01 ) # in your training loop: optimizer.zero_grad() # zero the gradient buffers output = net( input ) loss = criterion(output, target) loss.backward() optimizer.step() # Does the update |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/zzlyw/article/details/78769001