Neural networks
本篇文章是本人對Pytorch官方教程的原創(chuàng)翻譯(原文鏈接)僅供學(xué)習(xí)交流使用,轉(zhuǎn)載請注明出處!
torch.nn
包提供了各種神經(jīng)網(wǎng)絡(luò)的搭建方法。
nn
依賴于autograd
來對模型進(jìn)行定義、求導(dǎo)。
nn.Module
是所有模型的基類,它包含一個.forward(input)
方法來產(chǎn)生output。
一個基本的卷積神經(jīng)網(wǎng)絡(luò)如上圖所示,它用于對圖像進(jìn)行分類。
這是一個典型的前饋神經(jīng)網(wǎng)絡(luò),它接受輸入,并且將輸入的數(shù)據(jù)一層接一層地傳播給后面的神經(jīng)網(wǎng)絡(luò),最后產(chǎn)生輸出。
訓(xùn)練神經(jīng)網(wǎng)絡(luò)主要有一下幾個基本步驟:
- 定義神經(jīng)網(wǎng)絡(luò)的結(jié)構(gòu)和參數(shù)
- 將數(shù)據(jù)集迭代輸入神經(jīng)網(wǎng)絡(luò)
- 處理輸入的數(shù)據(jù)
- 計算損失(損失表示了輸出值與正確值的差異)
- 反向傳播(將損失傳播給各個參數(shù))
- 更新權(quán)重(常用算法
weight= weight - learning_rate * gradient
)
Define the network
接下來我們用pytorch仿照上圖定義一個神經(jīng)網(wǎng)絡(luò)
import torch
import torch.nn as nn
import torch.nn.functional as F # nn.functional提供了各種激勵函數(shù)
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的區(qū)域內(nèi)選擇1個最大特征
x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
# 如果窗口是正方形,也可以只指定一個參數(shù)
x = F.max_pool2d(F.relu(self.conv2(x)), 2)
#將圖片展開,變成一維數(shù)據(jù),以便輸入全連接層
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
包含的這些常用的網(wǎng)絡(luò)層對象都能直接調(diào)用,這是因為nn.Module
實現(xiàn)了.__call__()
方法,這使得對對象的調(diào)用將視為對.__call__()
方法的調(diào)用。例如我們有一個可調(diào)用對象x
,那么x()
就等價于x.__call__()
。對于nn.Module
類, 它的.__call__()
方法將會自動調(diào)用.forward()
方法,例如self.conv1(x)
等價于self.conv1.forward(x)
當(dāng)我們實現(xiàn)了.forward()
方法時,.backward()
方法也就自動定義了,這得益于autograd
機制。
.parameters()
方法可以列出網(wǎng)絡(luò)的參數(shù)。
params = list(net.parameters())
print(len(params))
print(params[0].size()) # conv1的參數(shù)
10
torch.Size([6, 1, 5, 5])
我們用一個隨機的32x32數(shù)據(jù)來測試網(wǎng)絡(luò)是否能運行:
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,[樣本數(shù), 通道數(shù), 長, 寬]
所以當(dāng)我們只有單個樣本時也要使用.unsqueeze(0)
來增加樣本維度
小結(jié):
-
nn.Module
神經(jīng)網(wǎng)絡(luò)模塊,搭建模型、封裝參數(shù)都十分方便,同時也支持將參數(shù)遷移至GPU,導(dǎo)入導(dǎo)出等等。 -
nn.Parameter
一種特殊的Tensor,nn.Module
會自動將傳入的參數(shù)記為parameter
。 -
autograd.Function
為自動求導(dǎo)機制實現(xiàn)了前饋和反饋的定義,每個Tensor操作都至少包含一個Function
,pytorch將這些function視為相互連接的結(jié)點,它們展示了新的tensor是如何產(chǎn)生的。
到這里,我們已經(jīng)解決了以下步驟:
- 定義神經(jīng)網(wǎng)絡(luò)
- 輸入數(shù)據(jù)
- 處理數(shù)據(jù)
為了訓(xùn)練神經(jīng)網(wǎng)絡(luò),還需要解決:
- 誤差計算
- 權(quán)重更新
Loss Function
損失函數(shù)負(fù)責(zé)計算預(yù)測值和真實值之間的差異,預(yù)測值即是神經(jīng)網(wǎng)絡(luò)的輸出,真實值一般由數(shù)據(jù)集給定,也稱為標(biāo)簽。
nn
提供了很多常用的損失函數(shù),最簡單的是nn.MSELoss
,即均方誤差。
output = net(input)
target = torch.randn(10) # 構(gòu)造一組虛擬的標(biāo)簽
target = target.view(1, -1) # 標(biāo)簽的尺寸必須和輸出一致
criterion = nn.MSELoss()
loss = criterion(output, target)
print(loss)
tensor(0.9284, grad_fn=<MseLossBackward>)
如果我們追蹤loss
產(chǎn)生的過程,調(diào)用它的.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
計算好誤差之后,我們應(yīng)該調(diào)用loss.backward()
,將誤差反向傳播給網(wǎng)絡(luò),此時所有與loss相關(guān)的Tensor都會計算梯度并且更新他們的.grad
屬性。
但在反向傳播之前,我們必須清空網(wǎng)絡(luò)的梯度,否則梯度會累加計算。
net.zero_grad() #將所有的參數(shù)梯度清零
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
目前實際應(yīng)用中最簡單的權(quán)重更新方法叫做隨機梯度下降法(Stochastic Gradient Descent, SGD):weight = weight - learning_rate * gradient
我們可以用Python簡單實現(xiàn)一個SGD算法:
learning_rate = 0.01
for f in net.parameters():
f.data.sub_(f.grad.data * learning_rate)
然而在訓(xùn)練神經(jīng)網(wǎng)絡(luò)的時候,常常用到不同的權(quán)重更新方法,為此pytorch提供了一個optim
模塊:
import torch.optim as optim
# 創(chuàng)建優(yōu)化器
optimizer = optim.SGD(net.parameters(), lr=0.01)
# 將此段代碼放入每次迭代訓(xùn)練中
optimizer.zero_grad() # 清空梯度緩存
output = net(input)
loss = criterion(output, target)
loss.backward()
optimizer.step() # 更新一次