神经网络是使用 torch.nn 包构建的
现在我们对 autograd 有了一个初步的了解, nn 依赖 autograd 定义模型并且微分这些模型, 一个 nn.Module 包含神经网络的层, 和一个返回 output 的方法 forward(input).
查看这副图片, 图片中描绘的是用于分类数字图像的神经网络.
这是一个简单的 feed-forward network. 它接收input, 通过一层一层的将input传递几层, 然后给出输出.
weight = weight - learning_rate * gradient
import torch
from torch.autograd import Variable
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, 5*5 square convolution
# kernel
self.conv1 = nn.Conv2d(1, 6, 5)
self.conv2 = nn.Conv2d(6, 16, 5)
# an affine operation y = W*x + 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)
我们刚刚定义了 forward 函数, backward()(在backward中计算gradients) 函数是在使用 autograd 自动定义的. 我们可以在forward函数中看到对Tensor的任何操作
一个模型的可学习参数由 net.parameters() 返回
params = list(net.parameters())
print(len(params))
print(params[0].size()) # conv1's weight
forward函数的输入是一个 autograd.Variable, 输出也是这样.
为了在 MNIST 上使用这个网络需要将dataset中获取的图像裁剪为32*32
input = Variable(torch.randn(1, 1, 32, 32))
out = net(input)
print(out)
清零所有参数梯度缓冲并且使用随机梯度反向传播
net.zero_grad()
out.backward(torch.randn(1, 10))
Note: 整个torch.nn包只支持mini-batch样本输入, 不支持一个单一的样本, 如果你只有一个单一的样本,可以使用input.unsqueeze(0)增加假的batch维度
1.torch.Tensor: 一个多维数组
一个loss function记录输入的对, 并且计算输出和目标之间差距的估计值.
nn包中有很多loss function, 最简单的loss function是 nn.MSELoss 计算目标和输出之间mean-square error
output = net(input)
target = Variable(torch.arange(1, 11))
target = target.view(1, -1)
criterion = nn.MSELoss()
loss = critetion(output, input)
print(loss)
现在,如果你在反向方向跟踪 loss, 使用.grad_fn, 就会看到计算过程的图. 因此,当我们调用loss.backward(),整幅图是对loss的微分,图中所有的Variable将会有一个.grad Variable, 随着梯度自增.
为了说明,使用下面几步backward
print(loss.grad_fn) # MSELoss
print(loss.grad_fn.next_functions[0][0])
# Linear
print(loss.grad_fn.next_functions[0][0].next_function[0][0])
# Relu
为了反向传播error我们要做的仅仅是 loss.backward(). 我们需要清理所有存在梯度,其他的梯度会随着已存在的梯度增加.
net.zero_grad()
print('conv1.bias.grad before backward')
print(net.conv1.bias.grad)
loss.backward()
print('conv2.bias.grad after backward')
print(net.conv1.bias.grad)
实际中使用最简单的更新规则是随机梯度下降(SGD)
weight = weight - learning_rate * gradient
在包 torch.optium 中实现了不同更新规则
import torch.optim as optim
# create your optimizer
optimizer = optim.SGD(net.parameters(), lr=0.01)
# in your training loop
optimizer.zero_grad()
output = net(input)
loss = criterion(output, target)
loss.backward()
optimizer.step() # Does the update