注意
here下载完整的示例代码
神经网络|
神经网络可以使用torch.nn
包构建。
现在你已经粗略看过autograd
,nn
依赖于autograd
来定义模型并对它们求导。
一个nn.Module
包含一层层网络和一个返回output
的forward(input)
方法。
例如,看下这个对图像数字进行分类的神经网络:
它是一个简单的前馈网络。 它获取输入,通过多个层逐个馈送,最后给出输出。
神经网络的典型训练过程如下:
定义具有一些可学习参数(或权重)的神经网络
迭代输入数据集
通过网络处理输入
计算损失(模型输出与正确值的距离)
将梯度反向传播给网络的参数
更新网络权重,通常使用简单的更新规则:
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
函数,backward
函数(梯度在这个函数中计算)用autograd
自动定义。
你可以在forward
函数中使用任何张量运算。
模型的可学习参数由net.parameters()
返回
params = list(net.parameters())
print(len(params))
print(params[0].size()) # conv1's .weight
输出:
10
torch.Size([6, 1, 3, 3])
让我们尝试一个随机的 32x32 输入。 注意:此网络 (LeNet) 的预期输入大小为 32x32。 要在 MNIST 数据集上使用此网络,请将数据集中的图像大小调整为 32x32。
input = torch.randn(1, 1, 32, 32)
out = net(input)
print(out)
输出:
tensor([[ 0.0263, 0.0803, 0.0338, 0.0432, 0.0129, -0.0767, 0.0314, -0.0725,
0.0332, 0.0386]], grad_fn=<AddmmBackward>)
清零所有参数的梯度缓存,然后进行随机梯度的反向传播:
net.zero_grad()
out.backward(torch.randn(1, 10))
注意
torch.nn
仅支持mini-batches。 整个torch.nn
包仅支持 mini-batch 作为输入,而不是单个样本。
例如,nn.Conv2d
接受一个nSamples x nChannels x Height x Width
的 4D 张量 。
如果是一个单独的样本,只需要使用input.unsqueeze(0)
来添加一个“假的”批大小维度。
在继续之前,让我们回顾一下到目前为止你所看到的所有类。
- 回顾:
torch.Tensor
— 一个多维数组,支持诸如backward()
等自动求导操作。 同时还为相关张量保存梯度 。nn.Module
— 神经网络模块。 封装参数的便捷方法,并带有将参数移动到 GPU、导出、加载等辅助方法。nn.Parameter
—一种张量,即作为属性赋值给一个Module
时自动注册为参数。autograd.Function
— 实现自动求导操作的前向和后向定义。 每个Tensor
操作至少创建一个Function
节点,该节点连接到创建Tensor
并对其历史记录进行编码的函数。
- 到这里,我们介绍了:
定义神经网络
处理输入并调用 backward
- 仍然剩下:
计算损失
更新网络权重
损失函数¶
损失函数接受 (output, target) 输入对,并计算一个估计输出与目标的距离值。
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(0.6766, 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 0x7f7fa5d39630>
<AddmmBackward object at 0x7f7fa5d39438>
<AccumulateGrad object at 0x7f7fa5d39438>
反向传播¶
为了反向传播误差,我们要做的就是调用loss.backward()
。
你需要清零现有的梯度,否则梯度将会与已有的梯度累加。
现在,我们将调用loss.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)
输出:
conv1.bias.grad before backward
tensor([0., 0., 0., 0., 0., 0.])
conv1.bias.grad after backward
tensor([ 0.0085, 0.0077, -0.0137, 0.0031, -0.0045, 0.0134])
现在,我们已经看到如何使用损失函数。
稍后阅读:
神经网络软件包包含各种模块和损失函数,这些模块和损失函数构成深度神经网络的基础模块。 完整的文档列表在这里。
剩下唯一需要学习的是:
更新网络权重
更新权重|
实际中使用的最简单的更新规则是随机梯度下降 (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()
手动将梯度缓冲区清零。 这是因为梯度会累积,如反向传播部分所述。
脚本总运行时间: (0 分 0.098 秒)