基礎LeNet
定義網絡
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, 3x3 square convolution
# kernel
self.conv1 = nn.Conv2d(1, 6, 3)
self.conv2 = nn.Conv2d(6, 16, 3)
# an affine operation: y = Wx + b
self.fc1 = nn.Linear(16 * 6 * 6, 120) # 6*6 from image dimension
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)
在pytorch中,通常來說,可以通過建立網絡的class來實現(方法之一,個人比較推薦). 新建的網絡繼承nn.Module 基類.構建新的神經網絡class的順序:
-
定義__init__(),並 super 父類(因爲需要實例化父類中的參數)初始化相關的網絡層,需要在__init__()中初始化的類型:
1.一般來說將torch.nn中的相關層在init中初始化(),以torch.nn.Conv2d爲例, 也就是說 torch.nn.Conv2d這種"函數"其實是個 Module類,在實例化類後會初始化2d卷積所需要的參數. 這些參數會在你做forward和 backward之後根據loss進行更新,所以通常存放在定義模型的 init() 中.
2.torch.nn.functional 中所需要的初始化參數,需要在__init__()中定義
-
定義forward():
輸入項爲x, 定義forward的整個流程
-
額外輔助函數
可以加可以不加, 爲了更好的進行forward,可以創建相關函數
-
我們只需要定義forward函數,backward函數會自動根據autograd定義
可學習的參數記錄可以通過 net.parameters()函數返回
params = list(net.parameters())
print(len(params))
print(params[0].size()) # conv1's .weight
10
torch.Size([6, 1, 3, 3])
用隨機32x32tensor做輸入,跑前向:
input = torch.randn(1, 1, 32, 32)
out = net(input)
print(out)
tensor([[-0.1564, 0.1191, 0.0464, -0.0260, -0.1250, 0.0476, 0.0177, -0.1471,
0.0538, 0.0109]], grad_fn=<AddmmBackward>)
將所有參數的.grad緩存全部置0用隨機梯度做backpropagation
net.zero_grad()
out.backward(torch.randn(1, 10))
torch.nn 僅支持mini batch處理,不支持單個樣本的處理,例如 nn.Conv2d需要的輸入圖像爲4維 nSamples x nChannels x Height x Width
,如果需要輸入單張圖片,需要 input.unsqueeze(0)升維
loss 函數
mean squared error
output = net(input)
target = torch.randn(10) # a dummy target, for example
target = target.view(1, -1) # make it the same shape as output
criterion = nn.MSELoss()
loss = criterion(output, target)
print(loss)
tensor(0.8938, grad_fn=<MseLossBackward>)
其實本質上,nn. 引導的loss functions也是一個類,和nn.Conv2D之類的layer層具有一樣的父類Module
,Module是一個可調類,本質上是通過 __ call__()來調用定義的forward().
另: 其實torch.nn.functional中的函數與torch.nn中最直接的區別是一個是函數,一個是類. 但是他們是有聯繫的, torch.nn往往是在forward()函數中調用torch.nn.functional來實現的.也就是說torch.nn相當於包裝了的torch.nn.functional
loss 和其他layer 的操作是平級的,因爲他們本質上是一致的,操作流程也是一致的. 因此完全可以把loss當成額外的一層"layer"(雖然它在結構上不屬於layer,但在實現上是按照layer層的運行規則去實現的)
查看backward的graph就會看到
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 0x7f5d2815d5c0>
<AddmmBackward object at 0x7f5d2815d128>
<AccumulateGrad object at 0x7f5d2815d128>
Backprop
要想完成backpropagation,我們只需要用 loss.backward()這一句就行了.但是我們在每次操作前需要把現有的參數的grad清零,否則這些緩存的參數則會被累計到當前backward()後得到的梯度上.
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
tensor([0., 0., 0., 0., 0., 0.])
conv1.bias.grad after backward
tensor([ 0.0012, 0.0053, -0.0044, 0.0030, -0.0081, 0.0011])
反向傳播在代碼上很簡單,如果想要了解詳細的 autograd過程和反向傳播的流程機制,請參閱
- one way的pytorch學習筆記(二)autograd自動求導
- one way的pytorch學習筆記(三)leaf 葉子(張量)
- one way的pytorch學習筆記(四)autograd的流程機制原理
更新參數
最簡單的更新參數的方法爲隨機梯度下降(SGD):
我們可以通過一下代碼實現
learning_rate = 0.01
for f in net.parameters():
f.data.sub_(f.grad.data * learning_rate)
如果想要用其他優化算法的話需要用到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