前提
1.使用torch.nn包构建神经网络;
2.nn依赖于autograd来定义模型并对其进行微分;
3.nn.Module
包含层,以及返回output的方法forward(input)。
注:pytorch里面一切自定义操作基本上都是继承nn.Module类来实现的
任务
对数字图像进行分类的网络:
神经网络的典型训练过程如下:
1.定义具有一些可学习参数(或权重)的神经网络
2.遍历输入数据集
3.通过网络处理输入
4.计算损失(输出正确的距离有多远)
5.将梯度传播回网络参数
6.通常使用简单的更新规则来更新网络的权重: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, 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) # 5*5 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 specify with a single number
x = F.max_pool2d(F.relu(self.conv2(x)), 2)
x = torch.flatten(x, 1) # flatten all dimensions except the batch dimension
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
net = Net()
print(net)
注:您只需要定义forward函数,就可以使用autograd为您自动定义backward函数(计算梯度)。 您可以在forward函数中使用任何张量操作
。
模型的可学习参数由net.parameters()返回
params = list(net.parameters())
print(len(params))
print(params[0].size()) # conv1's .weight
以一个32x32随机输入
input = torch.randn(1, 1, 32, 32)
out = net(input)
print(out)
使用随机梯度将所有参数和反向传播的梯度缓冲区归零:
net.zero_grad()
out.backward(torch.randn(1, 10))
回顾:
torch.Tensor:一个多维数组,支持诸如backward()的自动微分操作。 同样,保持相对于张量的梯度
。
nn.Module:神经网络模块
。 封装参数的便捷方法,并带有将其移动到 GPU,导出,加载等的帮助器。
nn.Parameter:一种张量,即将其分配为Module的属性时,自动注册为参数。
autograd.Function:实现自动微分操作的正向和反向定义
。 每个Tensor操作都会创建至少一个Function节点,该节点连接到创建Tensor的函数,并且编码其历史记录。
损失函数
损失函数采用一对(输出,目标)输入,并计算一个值,该值估计输出与目标之间的距离
。
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)
使用.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
#result:
#<MseLossBackward0 object at 0x7f71283dd048>
#<AddmmBackward0 object at 0x7f71283dd7f0>
#<AccumulateGrad object at 0x7f71283dd7f0>
反向传播
反向传播误差,要做的只是对loss.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)
#result:
#conv1.bias.grad before backward
#tensor([0., 0., 0., 0., 0., 0.])
#conv1.bias.grad after backward
#tensor([ 0.0188, 0.0172, -0.0044, -0.0141, -0.0058, -0.0013])
更新权重
实践中使用的最简单的更新规则是随机梯度下降(SGD)
:weight = weight - learning_rate * gradient
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