使用torch.nn构建神经网络。
下图是对数字图像进行分类的网络
它是一个简单的前馈网络。它接受输入,将其传送到多个层,然后最后给出输出。
神经网络的典型训练过程
- 定义具有一些可学习参数(或权重)的神经网络
- 遍历输入数据集
- 通过网络处理输入
- 计算损失
- 将梯度传播回网络参数
- 更新网络的权重: 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
net.parameters() 返回模型可学习参数
params = list(net.parameters())
print(len(params))
print(params[0].size()) # conv1's .weight
让我们尝试一个32x32随机输入。注意:该网络的预期输入大小(LeNet)为32x32。MNIST数据集图像是28x28, 要在MNIST数据集上使用此网络,请将图像从数据集中调整为32x32。
input = torch.randn(1, 1, 32, 32)
out = net(input)
print(out)
梯度归零:
net.zero_grad()
out.backward(torch.randn(1, 10))
torch.nn仅支持小批量,而不支持单个样本。
例如,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)
现在,如果loss使用.grad_fn属性的属性向后移动, 您将看到如下所示的计算图:
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
反向传播
调用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)
更新权重
实践中使用的最简单的更新规则是随机梯度下降(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