PyTorch深度学习60分钟闪电战:03 神经网络

本系列是PyTorch官网Tutorial Deep Learning with PyTorch: A 60 Minute Blitz 的翻译和总结。

  1. PyTorch概览
  2. Autograd - 自动微分
  3. 神经网络
  4. 训练一个分类器

下载本文的Jupyter NoteBook文件:60min_01_PyTorch Overview.ipynb


可以使用 torch.nn包构建神经网络。

现在你已经对autograd有了基本的了解,nn依赖autograd来定义模型并执行微分。一个nn.Module包含层和一个forward(input)方法用以返回output

例如,请看以下对图像分类网络:

这是一个简单的前馈网络。它获取输入,将其一层又一层地馈入,然后最终给出输出。

神经网络的典型训练过程如下:

定义具有一些可学习参数(或权重)的神经网络
遍历输入数据集
通过网络处理输入
计算损失(输出正确的距离有多远)
将梯度传播回网络参数
通常使用简单的更新规则来更新网络的权重: 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__() # 多重继承
        # 一个图像输入channel,六个输出channel,3*3卷积核
        self.conv1 = nn.Conv2d(1,6,3)
        self.conv2 = nn.Conv2d(6,16,3)
        # 线性变换: 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):
        # 经过卷积层1、relu激活函数、max_pool降采样
        x = F.max_pool2d(F.relu(self.conv1(x)),(2,2))
        # 经过卷积层2、relu激活函数、max_pool降采样
        # 如果降采样尺寸为正方形,也可以只写一个数字
        x = F.max_pool2d(F.relu(self.conv2(x)), 2)
        # resize
        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)
)

你刚刚已经定义了前向传播的函数,而反向传播的函数将会由autograd自动给出。

网络的可学习由net.parameters()返回。

params = list(net.parameters())
print(len(params))
print(params[0].size())  # conv1's .weight
10
torch.Size([6, 1, 3, 3])

让我们尝试一个32×32随机输入。注意:该网络(LeNet)的预期输入大小为32x32。要在MNIST数据集上使用此网络,请将图像从数据集中调整为32×32。

input = torch.randn(1, 1, 32, 32)
out = net(input)
print(out)
tensor([[ 0.0203,  0.0255,  0.0466,  0.1283,  0.1069,  0.1514, -0.0276, -0.0390,
         -0.0746, -0.0476]], grad_fn=<AddmmBackward>)

用随机梯度将所有参数和反向传播器的梯度缓冲区归零:

net.zero_grad()
out.backward(torch.randn(1, 10))

Note:

torch.nn仅支持mini-batches。整个torch.nn仅支持作为mini-batch采样的输入,而非单采样的输入。
例如,nn.Conv2d接受4维的张量:nSamples x nChannels x Height x Width.
如果你有一个单采样的输入,则只需使用input.unsqueeze(0)即可添加伪造的批次尺寸。

在继续进行之前,让我们回顾一下到目前为止所看到的所有课程。

概括:

  • torch.Tensor - 一个支持例如backward()等autograd操作的多维数组,同时包含关于张量的梯度。
  • nn.Module - 神经网络模块。一个封装参数的便捷途径,同时有将其移动到GPU、导出、加载的帮助器。
  • nn.Parameter - 一种张量,当给Module赋值时能够自动注册为一个参数。
  • autograd.Function - 使用autograd自动实现前向传播和反向传播。每个张量的操作都至少会生成一个独立的Function节点,与生成该张量的函数相连之后,记录下操作历史。

到这里,我们掌握了:

  • 如何定义一个神经网络
  • 处理输入并调用反向传播

接下来我们还将了解到:

  • 计算损失函数
  • 更新网络权重

损失函数

损失函数采用一对(输出,目标)作为输入,并计算一个输出值来评估与目标的距离。

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.5661, 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 0x0000014700F28940>
<AddmmBackward object at 0x0000014700F28940>
<AccumulateGrad object at 0x0000014700EFECC0>

反向传播

要完成反向传播,我们所要做的是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.0008, -0.0017, -0.0009,  0.0055, -0.0086,  0.0021])

现在我们已经知道了如何使用损失函数。

只剩下:

  • 如何更新网络权重

更新网络权重

实践中最简单的权重更新规则是随机梯度下降(Stochastic Gradient Descent, 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

# 创建你的优化器
optimizer = optim.SGD(net.parameters(), lr=0.01)

# 在训练循环中
optimizer.zero_grad()   # zero the gradient buffers
output = net(input)
loss = criterion(output, target)
loss.backward()
optimizer.step()    # Does the update

猜你喜欢

转载自blog.csdn.net/weixin_43953703/article/details/102087664