DEEP LEARNING WITH PYTORCH: A 60 MINUTE BLITZ
最近因为课题的需要,要利用pytorch实现pointer network,所以在这里对ytorch的基本语法做一个简答的教程,主要参考了《60分钟闪电战:使用pytorch进行深度学习》。
本教程的目标如下:
- 理解pytorch的张量(Tensor)库和顶层神经网络;
- 训练一个简单神经网络进行图像分类。
- 深度学习pytorch基础入门教程(1小时)-张量、操作、转换
- 深度学习pytorch基础入门教程(1小时)-自动梯度
- 深度学习pytorch基础入门教程(1小时)-神经网络
神经网络
神经网络可以使用torch.nn包来构建。
现在已经对autograd有了解了,nn就是通过autograd对模型进行定义和微分的。nn模块包含了层(layers)和一个forward(输入)方法用于返回输出(output)。
例如,看看这个数字图像分类网络:
这是一个简单的前馈网络,它接受输入,将其传送到多个层,最后给出输出。
典型的神经网络训练过程如下:
- 定义具有一些可学习参数(或权值)的神经网络;
- 在输入数据集上多次迭代;
- 通过网络处理输入;
- 计算损失(输出距离正确有多远);
- 方向传播梯度到网络的参数;
- 更新网络的权值,通常使用一个简单的更新规则: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, 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)
输出:
Net(
(conv1): Conv2d(1, 6, kernel_size=(3, 3), stride=(1, 1))
(conv2): Conv2d(6, 16, kernel_size=(3, 3), stride=(1, 1))
(fc1): Linear(in_features=576, 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函数,并且通过autograd可以自动定义backward函数(在这里计算梯度)。在forward函数中可以使用任何张量运算。
模型中的可学习参数通过 nn.parameter返回:
params = list(net.parameters())
print(len(params))
print(params[0].size()) # conv1's .weight
输出:
10
torch.Size([6, 1, 3, 3])
下面尝试一个随机的32x32输入。注意:网络的期望输入大小为32x32,要在MINIST数据集上使用此网络,需要将数据集的图像大小调整为32x32。
input = torch.randn(1, 1, 32, 32)
out = net(input)
print(out)
输出:
tensor([[ 0.0225, 0.0284, 0.0803, 0.0649, 0.0772, -0.0396, 0.1045, 0.0433,
0.0554, -0.0409]], grad_fn=<AddmmBackward>)
清除所有参数的梯度缓存,使用随机梯度进行反向传播:
说明:torch.nn仅支持mini-batches。整个torch.nn包仅支持mini-batch样本的输入,而不是单个样本。
例如,nn.Conv2d将输入一个4D张量nSamples x nChannels x Height x Width。
如果只有一个样本,只需要通过input.unsqueeze(0)来增加一个批次维度。
损失函数
损失函数将(输出,目标)对作为输入,用来计算估计输出距离目标多远的值。
在nn包下有多个不同的损失函数,一个简单的损失是nn.MSELoss,其计算了输出和目标之间的均方误差。
例如:
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(1.1812, grad_fn=<MseLossBackward>)
现在,如果你使用 .grad_fn属性,按照loss的反向方向,你会看到一个类似这样的计算图:
input -> conv2d -> relu -> maxpool2d -> conv2d -> relu -> maxpool2d
-> view -> linear -> relu -> linear -> relu -> linear
-> MSELoss
-> loss
所以当调用loss.backward()是,整个图是关于损失进行微分的,图中所有requires_grad=True的张量都将随着梯度累积.grad张量。
为了说明这一点,让我们反向执行几步:
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 0x00000196495DEB08>
<AddmmBackward object at 0x0000019649C6ED48>
<AccumulateGrad object at 0x00000196495DEB08>
反向传播
为了反向传播误差,所要做的就是loss.backward()。但是首先需要清除现有的梯度,否则梯度会累积到现有的梯度中。
现在调用loss.backward(),看一下执行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)
输出:
tensor([0., 0., 0., 0., 0., 0.])
conv1.bias.grad after backward
tensor([0.0051, 0.0014, 0.0124, 0.0196, 0.0045, 0.0071])
更新权重
实际中使用的最简单的更新规则是随机梯度下降(SGD):
可通过如下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。