【Pytorch教程】Pytorch tutorials 03-Neural networks 中文翻譯

Neural networks

本篇文章是本人對Pytorch官方教程的原創翻譯(原文鏈接)僅供學習交流使用,轉載請注明出處!

torch.nn包提供了各種神經網絡的搭建方法。

nn依賴于autograd來對模型進行定義、求導。

nn.Module是所有模型的基類,它包含一個.forward(input)方法來產生output。

一個基本的卷積神經網絡如上圖所示,它用于對圖像進行分類。

這是一個典型的前饋神經網絡,它接受輸入,并且將輸入的數據一層接一層地傳播給后面的神經網絡,最后產生輸出。

訓練神經網絡主要有一下幾個基本步驟:

  • 定義神經網絡的結構和參數
  • 將數據集迭代輸入神經網絡
  • 處理輸入的數據
  • 計算損失(損失表示了輸出值與正確值的差異)
  • 反向傳播(將損失傳播給各個參數)
  • 更新權重(常用算法weight= weight - learning_rate * gradient

Define the network

接下來我們用pytorch仿照上圖定義一個神經網絡

import torch
import torch.nn as nn
import torch.nn.functional as F  # nn.functional提供了各種激勵函數

class Net(nn.Module):
    
    def __init__(self):
        super(Net, self).__init__()
        # 第一個卷積層輸入1張圖片,輸出6張圖片,卷積核大小為5
        self.conv1 = nn.Conv2d(1, 6, 5)
        # 第二個卷積層輸入6張圖片,輸出16張圖片,卷積核大小為5
        self.conv2 = nn.Conv2d(6, 16, 5)
        
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)
    
    def forward(self, x):
        # 最大池化, 使用2x2的窗口,也就是在2x2的區域內選擇1個最大特征
        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
        # 如果窗口是正方形,也可以只指定一個參數
        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:]
        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)
)

可以注意到,torch.nn包含的這些常用的網絡層對象都能直接調用,這是因為nn.Module實現了.__call__()方法,這使得對對象的調用將視為對.__call__()方法的調用。例如我們有一個可調用對象x,那么x()就等價于x.__call__()。對于nn.Module類, 它的.__call__()方法將會自動調用.forward()方法,例如self.conv1(x)等價于self.conv1.forward(x)

當我們實現了.forward()方法時,.backward()方法也就自動定義了,這得益于autograd機制。

.parameters()方法可以列出網絡的參數。

params = list(net.parameters())
print(len(params))
print(params[0].size())  # conv1的參數
10
torch.Size([6, 1, 5, 5])

我們用一個隨機的32x32數據來測試網絡是否能運行:

input = torch.randn(1, 1, 32, 32)
out = net(input)
print(out)
tensor([[ 0.0014,  0.0215, -0.0656, -0.1787,  0.0457,  0.0719,  0.0304,  0.0375,
         -0.0414, -0.0557]], grad_fn=<AddmmBackward>)
net.zero_grad()
out.backward(torch.randn(1, 10))

torch.nn僅支持mini-batch的樣本,不能只輸入單個樣本。
例如nn.Conv2d必須接受一個4維的Tensor,[樣本數, 通道數, 長, 寬]
所以當我們只有單個樣本時也要使用.unsqueeze(0)來增加樣本維度

小結:

  • nn.Module神經網絡模塊,搭建模型、封裝參數都十分方便,同時也支持將參數遷移至GPU,導入導出等等。
  • nn.Parameter一種特殊的Tensor,nn.Module會自動將傳入的參數記為parameter
  • autograd.Function 為自動求導機制實現了前饋和反饋的定義,每個Tensor操作都至少包含一個Function,pytorch將這些function視為相互連接的結點,它們展示了新的tensor是如何產生的。

到這里,我們已經解決了以下步驟:

  • 定義神經網絡
  • 輸入數據
  • 處理數據

為了訓練神經網絡,還需要解決:

  • 誤差計算
  • 權重更新

Loss Function

損失函數負責計算預測值和真實值之間的差異,預測值即是神經網絡的輸出,真實值一般由數據集給定,也稱為標簽。

nn提供了很多常用的損失函數,最簡單的是nn.MSELoss,即均方誤差。

output = net(input)
target = torch.randn(10)  # 構造一組虛擬的標簽
target = target.view(1, -1)  # 標簽的尺寸必須和輸出一致
criterion = nn.MSELoss()

loss = criterion(output, target)
print(loss)
tensor(0.9284, grad_fn=<MseLossBackward>)

如果我們追蹤loss產生的過程,調用它的.grad_fn屬性,我們會看到這樣一條路徑:

input -> conv2d -> relu -> maxpool2d -> conv2d -> relu -> maxpool2d
-> view -> linear -> relu -> linear -> relu -> linear
-> MSELoss
-> loss

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 0x000001A0F053E5C8>
<AddmmBackward object at 0x000001A0F053E688>
<AccumulateGrad object at 0x000001A0F053E5C8>

Backprop

計算好誤差之后,我們應該調用loss.backward(),將誤差反向傳播給網絡,此時所有與loss相關的Tensor都會計算梯度并且更新他們的.grad屬性。

但在反向傳播之前,我們必須清空網絡的梯度,否則梯度會累加計算。

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.0016,  0.0073, -0.0150, -0.0061, -0.0189, -0.0052])

Update the weights

目前實際應用中最簡單的權重更新方法叫做隨機梯度下降法(Stochastic Gradient Descent, SGD):weight = weight - learning_rate * gradient

我們可以用Python簡單實現一個SGD算法:

learning_rate = 0.01
for f in net.parameters():
    f.data.sub_(f.grad.data * learning_rate)

然而在訓練神經網絡的時候,常常用到不同的權重更新方法,為此pytorch提供了一個optim模塊:

import torch.optim as optim

# 創建優化器
optimizer = optim.SGD(net.parameters(), lr=0.01)

# 將此段代碼放入每次迭代訓練中
optimizer.zero_grad()  # 清空梯度緩存
output = net(input)
loss = criterion(output, target)
loss.backward()
optimizer.step()  # 更新一次
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容