%matplotlib inline
使用torch.nn包來構建神經網絡。html
上一講已經講過了autograd
,nn
包依賴autograd
包來定義模型並求導。
一個nn.Module
包含各個層和一個forward(input)
方法,該方法返回output
。python
例如:數組
它是一個簡單的前饋神經網絡,它接受一個輸入,而後一層接着一層地傳遞,最後輸出計算的結果。緩存
神經網絡的典型訓練過程以下:網絡
weight = weight - learning_rate * gradient
開始定義一個網絡:ide
import torch 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)
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(in_features=400, out_features=120, bias=True) (fc2): Linear(in_features=120, out_features=84, bias=True) (fc3): Linear(in_features=84, out_features=10, bias=True) )
在模型中必需要定義 forward
函數,backward
函數(用來計算梯度)會被autograd
自動建立。
能夠在 forward
函數中使用任何針對 Tensor 的操做。函數
net.parameters()
返回可被學習的參數(權重)列表和值oop
params = list(net.parameters()) print(len(params)) print(params[0].size()) # conv1's .weight
10 torch.Size([6, 1, 5, 5])
測試隨機輸入32×32。
注:這個網絡(LeNet)指望的輸入大小是32×32,若是使用MNIST數據集來訓練這個網絡,請把圖片大小從新調整到32×32。學習
input = torch.randn(1, 1, 32, 32) out = net(input) print(out)
tensor([[ 0.1470, -0.0240, 0.0103, 0.0705, 0.0650, -0.0010, -0.0083, 0.0556, -0.0686, -0.0675]], grad_fn=<AddmmBackward>)
將全部參數的梯度緩存清零,而後進行隨機梯度的的反向傳播:測試
net.zero_grad() out.backward(torch.randn(1, 10))
``torch.nn`` 只支持小批量輸入。整個 ``torch.nn`` 包都只支持小批量樣本,而不支持單個樣本。 例如,``nn.Conv2d`` 接受一個4維的張量, ``每一維分別是sSamples * nChannels * Height * Width(樣本數*通道數*高*寬)``。 若是你有單個樣本,只需使用 ``input.unsqueeze(0)`` 來添加其它的維數
在繼續以前,咱們回顧一下到目前爲止用到的類。
回顧:
torch.Tensor
:一個用過自動調用 backward()
實現支持自動梯度計算的 多維數組 ,nn.Module
:神經網絡模塊。封裝參數、移動到GPU上運行、導出、加載等。nn.Parameter
:一種變量,當把它賦值給一個Module
時,被 自動 地註冊爲一個參數。autograd.Function
:實現一個自動求導操做的前向和反向定義,每一個變量操做至少建立一個函數節點,每個Tensor
的操做都回建立一個接到建立Tensor
和 編碼其歷史 的函數的Function
節點。重點以下:
還剩:
一個損失函數接受一對 (output, target) 做爲輸入,計算一個值來估計網絡的輸出和目標值相差多少。
譯者注:output爲網絡的輸出,target爲實際值
nn包中有不少不一樣的損失函數。
nn.MSELoss
是一個比較簡單的損失函數,它計算輸出和目標間的均方偏差,
例如:
output = net(input) target = torch.randn(10) # 隨機值做爲樣例 target = target.view(1, -1) # 使target和output的shape相同 criterion = nn.MSELoss() loss = criterion(output, target) print(loss)
tensor(0.7241, grad_fn=<MseLossBackward>)
如今,若是您使用它的.grad_fn
屬性沿着loss
的方向向後移動,您將看到一個計算圖,以下所示:
::
input -> conv2d -> relu -> maxpool2d -> conv2d -> relu -> maxpool2d -> view -> linear -> relu -> linear -> relu -> linear -> MSELoss -> loss
So, when we call loss.backward()
, the whole graph is differentiated
w.r.t. the loss, and all Tensors in the graph that has requires_grad=True
will have their .grad
Tensor accumulated with the gradient.
For illustration, let us follow a few steps backward:
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
<MseLossBackward object at 0x0000001FCC3CEEB8> <AddmmBackward object at 0x0000001FCC3CEBE0> <AccumulateGrad object at 0x0000001FCC3CEEB8>
調用loss.backward()得到反向傳播的偏差。
可是在調用前須要清除已存在的梯度,不然梯度將被累加到已存在的梯度。
如今,咱們將調用loss.backward(),並查看conv1層的誤差(bias)項在反向傳播先後的梯度。
net.zero_grad() # 清除梯度 print('conv1.bias.grad before backward') print(net.conv1.bias.grad) loss.backward() print('conv1.bias.grad after backward') print(net.conv1.bias.grad)
conv1.bias.grad before backward tensor([0., 0., 0., 0., 0., 0.]) conv1.bias.grad after backward tensor([-0.0024, 0.0044, -0.0027, 0.0066, -0.0034, 0.0067])
如何使用損失函數
稍後閱讀:
nn
包,包含了各類用來構成深度神經網絡構建塊的模塊和損失函數,完整的文檔請查看here。
剩下的最後一件事:
在實踐中最簡單的權重更新規則是隨機梯度降低(SGD):
``weight = weight - learning_rate * gradient``
咱們可使用簡單的Python代碼實現這個規則:
learning_rate = 0.01 for f in net.parameters(): f.data.sub_(f.grad.data * learning_rate)
可是當使用神經網絡是想要使用各類不一樣的更新規則時,好比SGD、Nesterov-SGD、Adam、RMSPROP等,PyTorch中構建了一個包torch.optim
實現了全部的這些規則。
使用它們很是簡單:
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
.. Note::
Observe how gradient buffers had to be manually set to zero using ``optimizer.zero_grad()``. This is because gradients are accumulated as explained in `Backprop`_ section.