注意
轉到末尾 下載完整的示例程式碼。
神經網路#
創建於: 2017年3月24日 | 最後更新: 2024年5月6日 | 最後驗證: 2024年11月5日
您可以使用 torch.nn 包來構建神經網路。
既然您已經對 autograd 有了初步瞭解,那麼 nn 就依賴於 autograd 來定義模型並進行微分。 nn.Module 包含層,以及一個返回 output 的 forward(input) 方法。
例如,看看這個對數字影像進行分類的網路
convnet#
這是一個簡單的前饋網路。它接收輸入,依次透過多個層,然後最終輸出結果。
神經網路的典型訓練過程如下:
定義一個具有可學習引數(或權重)的神經網路
遍歷資料集的輸入
透過網路處理輸入
計算損失(輸出與正確答案的差距有多大)
將梯度反向傳播到網路的引數中
更新網路的權重,通常使用簡單的更新規則:
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.0022, -0.1108, 0.1433, -0.0090, -0.1501, 0.0117, -0.0448, 0.0890,
0.0395, 0.0250]], grad_fn=<AddmmBackward0>)
清零所有引數的梯度緩衝區,並用隨機梯度進行反向傳播。
net.zero_grad()
out.backward(torch.randn(1, 10))
注意
torch.nn 只支援 mini-batch。整個 torch.nn 包僅支援 mini-batch 樣本的輸入,而不支援單個樣本。
例如,nn.Conv2d 將接收一個 4D Tensor,格式為 nSamples x nChannels x Height x Width。
如果您只有一個樣本,只需使用 input.unsqueeze(0) 新增一個假的批次維度。
在繼續之前,讓我們回顧一下您到目前為止看到的所有類。
- 回顧
torch.Tensor- 一個支援backward()等自動微分操作的多維陣列。它也儲存了相對於該 Tensor 的梯度。nn.Module- 神經網路模組。封裝引數的便捷方式,並提供將引數移動到 GPU、匯出、載入等輔助功能。nn.Parameter- 一種 Tensor,當作為屬性分配給Module時,它會被自動註冊為引數。autograd.Function- 實現自動微分操作的前向和後向定義。每個Tensor操作至少會建立一個Function節點,該節點連線到建立Tensor的函式,並編碼其歷史記錄。
- 此時,我們已經涵蓋了
定義神經網路
處理輸入和呼叫 backward
- 待完成
計算損失
更新網路權重
損失函式#
損失函式接收 (output, target) 對輸入,並計算一個值,該值估算輸出與目標的差距有多大。
nn 包中包含多種損失函式。一個簡單的損失是:nn.MSELoss,它計算輸出和目標之間的均方誤差。
例如
tensor(0.9673, 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 0x7fadecb73820>
<AddmmBackward0 object at 0x7fadecb73dc0>
<AccumulateGrad object at 0x7fadecb73100>
反向傳播#
要反向傳播誤差,我們只需要呼叫 loss.backward()。但是,您需要先清零現有的梯度,否則梯度將累積到現有梯度上。
現在,我們將呼叫 loss.backward(),並檢視 conv1 的偏置梯度在反向傳播之前和之後。
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.0273, -0.0096, -0.0059, -0.0020, 0.0224, 0.0143])
現在,我們已經看到了如何使用損失函式。
稍後閱讀
神經網路包包含構成深度神經網路構建塊的各種模組和損失函式。完整的文件列表在此處:這裡。
唯一剩下要學習的是
更新網路權重
更新權重#
實踐中最簡單的更新規則是隨機梯度下降 (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.358 秒)