Pytorch入門——神經網路
上一篇部落格對Pytorch包中的變數和梯度有了初步瞭解,接下來進入正題——用Pytorch中的torch.nn包實現神經網路。
1.Pytorch實現神經網路的典型訓練過程
在這裡以Lenet模型為例,由兩個卷積層,兩個池化層,以及兩個全連線層組成。 卷積核大小為5*5,stride為1,採用MAX池化。以該網路分類數字影象為例:
Pytorch實現神經網路的典型訓練過程如下:
- 定義具有一些可學習引數(權重)的神經網路
- 迭代輸入資料
- 通過網路處理輸入
- 計算損失
- 將梯度傳播回到網路引數中
- 使用梯度下降更新網路權重,
weight = weight - learning_rate * gradient
2.定義網路
Lenet模型的Pytorch程式碼如下:
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 (400 -> 120)
(fc2): Linear (120 -> 84)
(fc3): Linear (84 -> 10)
)
只需定義forward函式,並backward自動使用函式autograd,可以在forward功能中使用任何Tensor操作。
用net.parameters()返回模型學習的引數
params = list(net.parameters())
print(len(params))
print(params[0].size()) # conv1's .weight
輸出
10
(6L, 1L, 5L, 5L)
前向傳播的輸入輸出都是autograd.Variable
input = Variable(torch.randn(1, 1, 32, 32))
out = net(input)
print(out)
輸出
Variable containing:
0.0809 0.0700 0.0478 -0.0280 -0.0281 0.1334 -0.0481 0.0195 -0.0522 0.1430
[torch.FloatTensor of size 1x10]
將隨機梯度的所有引數和backprops的梯度緩衝區置零:
net.zero_grad()
out.backward(torch.randn(1, 10))
注意:torch.nn
僅支援mini-batch
,整個torch.nn
軟體包僅支援輸入,這些輸入是小批量樣品,而不是單個樣品。例如,nn.Conv2d將採用nSamples x nChannels x Height x Width
的4D Tensor
。如果有一個樣本,只需使用input.unsqueeze(0)
來新增假批量維。
3.損失函式
損失函式採用(輸出,目標)輸入對,並計算估計輸出距離目標距離的值。nn
包下有幾種不同的損失函式,具體參考官網提供的損失函式說明。一個簡單的損失是:nn.MSELoss
,用於計算輸入和目標之間的平均平方誤差。
例如
output = net(input)
target = Variable(torch.arange(1, 11)) # a dummy target, for example
criterion = nn.MSELoss()
loss = criterion(output, target)
print(loss)
輸出
Variable containing:
38.1674
[torch.FloatTensor of size 1]
4.反向傳播
要反向傳播誤差,只需要用loss.backward()
,需要清除現有的梯度,否則漸變將累積到現有的梯度。
如下呼叫loss.backward()
,並且看看在conv1
之前和之後的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
Variable containing:
0
0
0
0
0
0
[torch.FloatTensor of size 6]
conv1.bias.grad after backward
Variable containing:
-0.1000
0.0343
-0.1194
-0.0136
-0.0767
0.0224
[torch.FloatTensor of size 6]
神經網路包包含形成深層神經網路、構建模組的各種模組和損失函式,官網提供一個完整的文件列表。
5.權重更新
實現中使用的最簡單的更新規則是隨機梯度下降(SGD)
:
weight = weight - learning_rate * gradient
用python
具體實現如下:
learning_rate = 0.01
for f in net.parameters():
f.data.sub_(f.grad.data * learning_rate)
torch.optim
提供了很多種更新方法,如SGD、nesterov - SGD、Adam、RMSProp
等,使用起來很簡單,如下:
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