使用torch.nn包来构建神经网络
上一讲是autograd,nn包以来autograd包来定义模型并求导,一个nn.Module包含各个层和一个forward(input)方法,该方法返回output
以下为定义一个网络的例子
定义网络和处理输入,调用backward
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, 5*5 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)
sefl.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=(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函数,backward函数(用于计算梯度)会被autograde自动创建,可以在forward函数中使用任何针对Tensor的操作,net.parameters() 返回可被学习的参数(权重)列表和值。
params = list(net.parameters())
print(len(params))
print(params[0].size()) # conv1's .weight
测试随机输入32*32,
input = torch.randn(1, 1, 32, 32)
out = net(input)
print(out)
将所有参数的梯度缓存清零,然后进行随机梯度的的反向传播:
net.zero_grad()
out.backward(torch.randn(1, 10))
Note注意点
torch.nn只支持小批量输入,整个torch.nn包都只支持小批量样本,不支持单个样本
如果是单个样本,需要用 input.unsqueeze(0)来添加他的维数。
回顾目前为止用到的类:
- torch.Tensor: 一个自动调用backward()实现 支持自动梯度计算的多维数组,并且保存关于这个向量的梯度
- nn.Module: 神经网络模块。封装参数,移动到GPU上运行、导出、加载等
- nn.Parameter: 一种变量, 当把它赋值给一个Module时,被自动注册为一个参数
- autograde.Function: 实现一个自动求导操作前向和反向定义,每个变量操作至少创建一个函数节点,每个Tensor的操作都会创建一个接受到创建Tensor和编码其历史信息的函数Function节点。
损失函数
一个损失函数接受一对(output, target)作为输入,计算一个值来估计网络的输出和目标值相差多少。
nn包中有很多不同的损失函数,nn.MSELoss是一个比较简单的损失函数,它计算输出和目标间的均方误差。例如
output = net(input)
target = torch.randn(10) # 随机值作为样例
target = target.view(1, -1) # 是target和output的shape一样
criterion = nn.MSELoss()
loss = criterion(output, target)
print(loss)
# tensor(0.8109, grad_fn=<MseLossBackward>)
现在,如果在反向过程中跟随loss , 使用它的 .grad_fn 属性,将看到如下所示的计算图。
::
input -> conv2d -> relu -> maxpool2d -> conv2d -> relu -> maxpool2d
-> view -> linear -> relu -> linear -> relu -> linear
-> MSELoss
-> loss
所以,当我们调用 loss.backward()时,整张计算图都会 根据loss进行微分,而且图中所有设置为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 0x7f3b49fe2470>
# <AddmmBackward object at 0x7f3bb05f17f0>
# <AccumulateGrad object at 0x7f3b4a3c34e0>
反向传播
调用loss.backward()获得反向传播的误差,但是在调用前需要清除已存在的梯度,否则梯度将被累加到已存在的梯度。
net.zero_grad() # 清除梯度
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.0051, 0.0042, 0.0026, 0.0152, -0.0040, -0.0036])
更新网络权重
在实践中最简单的权重更新规则是随机梯度下降(SGD)
weight = weight - learning_rate * gradient
我们可以使用简单的Python代码实现这个规则:
learning_rate = 0.01
for f in net.parameters():
f.data.sub_(f.grad.data * learning_rate)
PyTorch中构建了一个包torch.optim实现其他的不同的更新规则,例如SGD, Nesterov-SGD, Adam, RMSPROP,等。
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, 这是因为按照backprop部分中的说明累积的。
多批次训练网络
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
for epoch in range(2): # epoch number
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
# 获取输入
inputs, labels = data
#梯度置0
optimizer.zero_grad()
# 正向传播,反向传播,优化
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# 打印状态信息
running_loss += loss.item()
if i%2000 == 1999: #每2000打印一次
pint('[%d, %5d] loss: %.3f' %
(epoch+1, i+1, running_loss/2000))
running_loss = 0.0
# 网络预测
outputs = net(test_images)
_, predicted = torch.max(outputs, 1)
# 整个统计准确率
correct = 0
total = 0
with torch.no_grad():
for data in testloader:
images, labels = data
outputs = net(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the 10000 test images: %d %%' % (
100 * correct / total))
在GPU上训练
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# 确认我们的电脑支持CUDA,然后显示CUDA信息:
print(device)
net.to(device)
#inputs, targets和images也要转换
inputs, labels = inputs.to(device), labels.to(device)