神经网络可以用torch.nn来构建。
现在您已经了解了autograd, nn依赖于autograd来定义模型并对它们进行区分。一个nn.Module包含层和返回output的方法forward(input)。
例如,看看这个对数字图像进行分类的网络:
convnet
它是一个简单的前馈网络。它接受输入,一个接一个地通过几个层为其提供数据,最后给出输出。
一个典型的神经网络训练过程如下:
- 定义一些参数(或权重)可学的神经网络
- 遍历输入数据集
- 通过网络处理输入
- 计算损失(输出距离正确有多远)
- 传播梯度回网络的参数
- 更新网络的权重,通常使用一个简单的更新规则:weight = weight - learning_rate * gradient
Define the network
让我们定义这个网络
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)
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)
Out:
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)
)
您只需定义forward函数,然后使用autograd自动为您定义backward函数(其中计算梯度)。你可以在forward函数中使用任何Tensor运算。
模型的可学习参数由net.parameters()返回
params = list(net.parameters())
print(len(params))
print(params[0].size()) # conv1's .weight
Out:
10
torch.Size([6, 1, 5, 5])
让我们尝试一个随机的32x32输入。注意:此网络(LeNet)的预期输入大小为32x32。要在MNIST数据集上使用此网络,请将数据集中的图像大小调整为32x32。
input = torch.randn(1, 1, 32, 32)
out = net(input)
print(out)
Out:
tensor([[ 0.0503, 0.0003, 0.0674, -0.1313, 0.1299, -0.1419, -0.0999, -0.0190,
-0.1661, 0.1051]], grad_fn=<AddmmBackward>)
所有参数和随机梯度的反向传播的梯度缓冲器为零:
net.zero_grad()
out.backward(torch.randn(1, 10))
注意
torch.nn只支持小批量。整个torch.nn包只支持小批量样本的输入,而不是单个样本。
例如,nn.Conv2d将接收nSamples x nChannels x Height x Width的4D张量。
如果只有一个示例,只需使用input.unsqueeze(0)添加一个伪批处理维度。
在继续之前,让我们先回顾一下到目前为止您已经看到的所有类。
扼要重述
- torch.Tensor——一个多维数组,支持像backward()这样的autograd操作。也包含梯度w.r.t张量。
- nn.Module——神经网络模块。方便的方式封装参数,与帮助移动到GPU,导出,加载等。
- nn.Parameter——一种张量,当作为一个属性分配给一个模块时,它自动注册为一个参数。
- autograd.Function——实现autograd操作的正向和反向定义。每个Tensor运算至少创建一个Function节点,该节点连接到创建张量并对其历史进行编码的函数。
至此,我们讨论了:
- 定义一个神经网络
- 处理输入并向后调用
还剩下:
- 计算损耗
- 更新网络权值
Loss Function
损失函数接受(输出、目标)输入对,并计算一个值,该值估计输出与目标的距离。
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)
Out:
tensor(0.9914, grad_fn=<MseLossBackward>)
现在,如果您使用它的.grad_fn属性沿着loss的反向进行跟踪,您将看到一个类似于这样的计算图:
input -> conv2d -> relu -> maxpool2d -> conv2d -> relu -> maxpool2d -> view -> linear -> relu -> linear -> relu -> linear -> MSELoss -> loss
因此,当我们调用loss.backward()时,整个图形被区分为w.r.t. 损失,图中所有具有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
Out:
<MseLossBackward object at 0x7f9eb40c88d0> <AddmmBackward object at 0x7f9eb40c85f8> <AccumulateGrad object at 0x7f9eb40c85f8>
Backprop
要反向传播误差,我们所要做的就是loss.backward()。不过,您需要清除现有的梯度,否则梯度将累积为现有梯度。
现在我们将调用loss. reverse(),并查看在反向之前和之后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)
Out:
conv1.bias.grad before backward tensor([0., 0., 0., 0., 0., 0.]) conv1.bias.grad after backward tensor([-0.0205, 0.0088, 0.0135, 0.0123, 0.0098, -0.0036])
现在,我们已经学习了如何使用损失函数。
Update the weights
在实践中使用的最简单的更新规则是随机梯度下降(SGD)
weight = weight - learning_rate * gradient
我们可以使用简单的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()手动将梯度缓冲区设置为零。这是因为梯度是累积的,正如在Backprop部分所解释的那样。