注意
點選此處下載完整示例程式碼
神經網路¶
建立時間:2017年3月24日 | 最後更新:2024年5月6日 | 最後驗證:2024年11月5日
神經網路可以使用 torch.nn 包構建。
既然您已經對 autograd 有所瞭解,nn 依賴於 autograd 來定義模型並對其進行微分。一個 nn.Module 包含層,以及一個 forward(input) 方法,該方法返回 output。
例如,看看這個對數字影像進行分類的網路
卷積網路¶
它是一個簡單的全連線前饋網路。它接收輸入,將其依次透過多個層,最後給出輸出。
神經網路的典型訓練過程如下
定義具有一些可學習引數(或權重)的神經網路
迭代輸入資料集
透過網路處理輸入
計算損失(輸出與正確結果相差多遠)
將梯度反向傳播到網路的引數中
更新網路的權重,通常使用簡單的更新規則:
weight = weight - learning_rate * gradient
定義網路¶
讓我們定義這個網路
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) # 5*5 from image dimension
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, input):
# Convolution layer C1: 1 input image channel, 6 output channels,
# 5x5 square convolution, it uses RELU activation function, and
# outputs a Tensor with size (N, 6, 28, 28), where N is the size of the batch
c1 = F.relu(self.conv1(input))
# Subsampling layer S2: 2x2 grid, purely functional,
# this layer does not have any parameter, and outputs a (N, 6, 14, 14) Tensor
s2 = F.max_pool2d(c1, (2, 2))
# Convolution layer C3: 6 input channels, 16 output channels,
# 5x5 square convolution, it uses RELU activation function, and
# outputs a (N, 16, 10, 10) Tensor
c3 = F.relu(self.conv2(s2))
# Subsampling layer S4: 2x2 grid, purely functional,
# this layer does not have any parameter, and outputs a (N, 16, 5, 5) Tensor
s4 = F.max_pool2d(c3, 2)
# Flatten operation: purely functional, outputs a (N, 400) Tensor
s4 = torch.flatten(s4, 1)
# Fully connected layer F5: (N, 400) Tensor input,
# and outputs a (N, 120) Tensor, it uses RELU activation function
f5 = F.relu(self.fc1(s4))
# Fully connected layer F6: (N, 120) Tensor input,
# and outputs a (N, 84) Tensor, it uses RELU activation function
f6 = F.relu(self.fc2(f5))
# Gaussian layer OUTPUT: (N, 84) Tensor input, and
# outputs a (N, 10) Tensor
output = self.fc3(f6)
return output
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() 返回
params = list(net.parameters())
print(len(params))
print(params[0].size()) # conv1's .weight
10
torch.Size([6, 1, 5, 5])
讓我們嘗試一個隨機的 32x32 輸入。注意:該網路 (LeNet) 的預期輸入大小是 32x32。要在 MNIST 資料集上使用此網路,請將資料集中的影像大小調整為 32x32。
input = torch.randn(1, 1, 32, 32)
out = net(input)
print(out)
tensor([[ 0.1453, -0.0590, -0.0065, 0.0905, 0.0146, -0.0805, -0.1211, -0.0394,
-0.0181, -0.0136]], grad_fn=<AddmmBackward0>)
將所有引數的梯度緩衝區清零,並使用隨機梯度進行反向傳播
net.zero_grad()
out.backward(torch.randn(1, 10))
注意
torch.nn 只支援 mini-batch。整個 torch.nn 包只支援輸入是樣本的 mini-batch,而不是單個樣本。
例如,nn.Conv2d 將接收一個形狀為 nSamples x nChannels x Height x Width 的 4D Tensor。
如果您有一個單個樣本,只需使用 input.unsqueeze(0) 來新增一個偽造的 batch 維度。
在繼續之前,讓我們回顧一下目前為止您所見過的所有類。
- 回顧
torch.Tensor- 一個支援backward()等 autograd 操作的多維陣列。也持有關於該張量的梯度。nn.Module- 神經網路模組。一種方便封裝引數的方式,並提供將引數移動到 GPU、匯出、載入等輔助功能。nn.Parameter- 一種 Tensor,在被賦值為Module的屬性時會自動註冊為引數。autograd.Function- 實現autograd 操作的前向和後向定義。每個Tensor操作都會建立至少一個Function節點,該節點連線到建立該Tensor的函式,並編碼其歷史。
- 至此,我們已經涵蓋了
定義神經網路
處理輸入並呼叫 backward
- 剩餘部分
計算損失
更新網路權重
損失函式¶
損失函式接收 (輸出, 目標) 對作為輸入,並計算一個值來估計輸出與目標之間的距離。
nn 包下有幾種不同的損失函式。一個簡單的損失函式是:nn.MSELoss,它計算輸出和目標之間的均方誤差。
例如
tensor(1.3619, grad_fn=<MseLossBackward0>)
現在,如果您使用 loss 的 .grad_fn 屬性沿著反向方向跟蹤,您會看到一個計算圖,看起來像這樣
input -> conv2d -> relu -> maxpool2d -> conv2d -> relu -> maxpool2d
-> flatten -> linear -> relu -> linear -> relu -> linear
-> MSELoss
-> loss
因此,當我們呼叫 loss.backward() 時,整個圖將相對於神經網路引數進行微分,並且圖中所有 requires_grad=True 的 Tensor 的 .grad Tensor 將累積梯度。
作為說明,讓我們向後跟蹤幾個步驟
<MseLossBackward0 object at 0x7fbc2e2a7eb0>
<AddmmBackward0 object at 0x7fbc2e2a78e0>
<AccumulateGrad object at 0x7fbc2e2a7b80>
反向傳播¶
要反向傳播誤差,我們只需呼叫 loss.backward()。但是,您需要清除現有的梯度,否則梯度會累積到現有梯度中。
現在我們將呼叫 loss.backward(),並檢視 conv1 的 bias 梯度在反向傳播之前和之後的變化。
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)
conv1.bias.grad before backward
None
conv1.bias.grad after backward
tensor([ 0.0081, -0.0080, -0.0039, 0.0150, 0.0003, -0.0105])
現在,我們已經瞭解瞭如何使用損失函式。
稍後閱讀
神經網路包包含各種模組和損失函式,它們構成了深度神經網路的構建塊。包含文件的完整列表在此處。
剩下的唯一需要學習的是
更新網路權重
更新權重¶
實踐中最簡單的更新規則是隨機梯度下降 (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 等。為了實現這一點,我們構建了一個小型包: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
注意
請注意,必須使用 optimizer.zero_grad() 手動將梯度緩衝區設定為零。這是因為正如 反向傳播 部分所解釋的,梯度是累積的。
指令碼總執行時間: ( 0 分鐘 0.137 秒)