神经网络

 

1. 概述

 

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

 

nn依赖于autograd来定义模型并对其进行微分

 

nn.Module包含层,以及返回output的方法forward(input)

 

以下是对数字图像进行分类的网络:

 

 

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

 

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

  • 定义具有一些可学习参数(或权重)的神经网络
  • 遍历输入数据集
  • 通过网络处理输入
  • 计算损失(输出正确的距离有多远)
  • 将梯度传播回网络参数
  • 通常使用简单的更新规则来更新网络的权重:weight = weight - learning_rate * gradient
 

2. 定义网络

In [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, 5x5 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) # 5*5 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 specify with a single number
x = F.max_pool2d(F.relu(self.conv2(x)), 2)
x = torch.flatten(x, 1) # flatten all dimensions except the batch dimension
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x 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函数,就可以使用autograd为您自动定义backward函数(计算梯度)。 您可以在forward函数中使用任何张量操作

 

模型的可学习参数由net.parameters()返回

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

尝试一个32x32随机输入

In [3]:
input = torch.randn(1, 1, 32, 32)
out = net(input)
print(out)
 
tensor([[-0.0201, -0.0048,  0.0562,  0.0409, -0.0155,  0.0404,  0.1170,  0.0380,
-0.0494, 0.0060]], grad_fn=<AddmmBackward0>)
 

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

In [4]:
net.zero_grad()
out.backward(torch.randn(1, 10))
 

注意:

 

torch.nn仅支持小批量。 整个torch.nn包仅支持作为微型样本而不是单个样本的输入

例如,nn.Conv2d将采用nSamples x nChannels x Height x Width的 4D 张量

如果您只有一个样本,只需使用input.unsqueeze(0)添加一个假批量尺寸

 

回顾:

 
  • torch.Tensor-一个多维数组,支持诸如backward()的自动微分操作。 同样,保持相对于张量的梯度
  • nn.Module-神经网络模块。 封装参数的便捷方法,并带有将其移动到 GPU,导出,加载等的帮助器
  • nn.Parameter-一种张量,即将其分配为Module的属性时,自动注册为参数
  • autograd.Function-实现自动微分操作的正向和反向定义。 每个Tensor操作都会创建至少一个Function节点,该节点连接到创建Tensor的函数,并且编码其历史记录
 

3. 损失函数

 

损失函数采用一对(输出,目标)输入,并计算一个值,该值估计输出与目标之间的距离

 

nn包下有几种不同的损失函数。 一个简单的损失是:nn.MSELoss,它计算输入和目标之间的均方误差

In [5]:
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.7557, grad_fn=<MseLossBackward0>)
 

现在,如果使用.grad_fn属性向后跟随loss,将看到一个计算图,如下所示:

 

input -> conv2d -> relu -> maxpool2d -> conv2d -> relu -> maxpool2d -> view -> linear -> relu -> linear -> relu -> linear -> MSELoss -> loss

 

因此,当我们调用loss.backward()时,整个图将被微分。 损失,并且图中具有requires_grad=True的所有张量将随梯度累积其.grad张量。

为了说明,让我们向后走几步:

In [6]:
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
 
<MseLossBackward0 object at 0x7f9b58584d30>
<AddmmBackward0 object at 0x7f9b58574ba8>
<AccumulateGrad object at 0x7f9b58584d30>
 

4. 反向传播

 

要反向传播误差,我们要做的只是对loss.backward()。不过,需要清除现有的梯度,否则梯度将累积到现有的梯度中

 

现在,我们将其称为loss.backward(),然后看一下向后前后conv1的偏差梯度

In [7]:
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.0066, -0.0124, -0.0028, 0.0020, -0.0132, 0.0006])
 

5. 更新权重

 

实践中使用的最简单的更新规则是随机梯度下降(SGD):

 

weight = weight - learning_rate * gradient

In [8]:
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()将梯度缓冲区手动设置为零。 这是因为如反向传播部分中所述累积了梯度

最新文章

  1. ubuntu svn
  2. React学习笔记
  3. PullToRefreshGridView刷新加载
  4. vscode配置
  5. Match:DNA repair(POJ 3691)
  6. iOS 获取快递物流信息(GCD异步加载)
  7. ext DateTime.js在ie下显示不全
  8. Effective Modern C++翻译(4)-条款3:了解decltype
  9. UVALive 7276 Wooden Signs (DP)
  10. Ajax页面逻辑
  11. const int *p,int *const p区别(转)
  12. Android studio 开发在真机测试
  13. mybatis优化配置
  14. 本地存储 web storage
  15. 进程互斥(锁)------------------&gt;一个坑
  16. chrome使用技巧整理
  17. Spark学习之编程进阶总结(一)
  18. Contest2154 - 2019-2-28 高一noip基础知识点 测试1 题解版
  19. Java 元编程及其应用
  20. Educational Codeforces Round 1

热门文章

  1. 【RocketMQ】主从同步实现原理
  2. Python编程规范之PEP8
  3. Java-递归查询法
  4. STM32用寄存器实现电平翻转(一个按键控制LED灯的开关)
  5. SQLMap入门——判断是否存在注入
  6. 2022年7月13日,第四组,周鹏,JS做计算器代码
  7. Maven项目中导入坐标依赖时报(Failure to transfer....)的错的问题
  8. CF构造题1600-1800(2)
  9. 代码小DEMO随笔---JS原生手机版本alert弹框
  10. golang 切片的长度和容量