目录
神经网络可以使用 torch.nn 包来构建。nn 依赖 autograd 来定义模型并对其进行微分。一个 nn.Module 包含层以及返回输出的 forward 方法。
下图为对数字进行分类的神经网络:
它是一个简单的前馈网络。 它接受输入,一个接一个地将其通过几个层,最终给出输出。
神经网络的典型训练过程如下:
- 定义具有一些可学习参数(或权重)的神经网络。
- 迭代输入数据集
- 通过神经网络处理输入
- 计算损失(输出距离正确的目标值有多远)
- 将梯度传播回神经网络的参数
- 通常使用简单的更新规则更新网络权重:
weight = weight - learning_rate * gradient
1、定义神经网络
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 方法将会自动被定义。你可以在 forward 方法中使用任何tensor操作。
net.patameters() 返回模型的可学习参数。
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.0057, -0.0952, 0.1055, -0.0916, -0.1350, 0.0857, -0.0890, 0.0326,
-0.0554, 0.1451]], grad_fn=<AddmmBackward>)
将所有参数的梯度缓冲区置零,并使用随机梯度进行反向传播:
net.zero_grad()
out.backward(torch.randn(1, 10))
注意
torch.nn仅支持mini-batches。 整个torch.nn包只支持小批量样本的输入,而不是单个样本- 例如,
nn.Conv2d将采用4维张量:nSamples x nChannels x Height x Width。- 如果你有单个样本,只需使用
input.unsqueeze(0)添加一个假的批量维度。
总结:
torch.Tensor- 支持autograd操作(如backward())的多维数组。 同时保存关于tensor的梯度。nn.Module- 神经网络模块。 方便的封装参数的方法,使用帮助程序将它们移动到GPU,导出,加载等。nn.Parameter- 一种Tensor,在被指定为Module的属性时自动注册为参数。autograd.Function- 实现autograd操作的forward和backward定义。 每个Tensor操作都会创建至少一个Function节点,该节点连接到创建Tensor并对其历史进行编码的函数。
2、损失函数
损失函数以(输出,目标)对为输入,并计算一个值以估计输出距和目标之间的距离。
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.9991, grad_fn=<MseLossBackward>)
现在,如果你使用 .grad_fn 属性在反向方向上跟随损失,你将看到如下所示的计算图:
input -> conv2d -> relu -> maxpool2d -> conv2d -> relu -> maxpool2d
-> view -> linear -> relu -> linear -> relu -> linear
-> MSELoss
-> loss
因此,当我们调用 loss.backward() 时,整个计算图关于loss被微分,图中所有具有requires_grad = True的tensor将拥有梯度累积的.grad Tensor。
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 0x7ff716c28630>
<AddmmBackward object at 0x7ff716c28400>
<AccumulateGrad object at 0x7ff716c28400>
3、反向传播
要反向传播误差,我们所要做的就是 lost.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.0081, 0.0029, 0.0248, -0.0054, 0.0051, 0.0008])
4、更新参数
实践中使用的最简单的更新规则是随机梯度下降(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()手动将梯度缓冲区设置为零。 这是因为梯度是累积的。
本文详细介绍了使用PyTorch构建和训练神经网络的过程,包括定义神经网络、选择损失函数、执行反向传播以及更新参数等关键步骤。
9万+

被折叠的 条评论
为什么被折叠?



