Pytorch入门——神经网络
2017-09-01 17:39
363 查看
上一篇博客对Pytorch包中的变量和梯度有了初步了解,接下来进入正题——用Pytorch中的torch.nn包实现神经网络。
Pytorch实现神经网络的典型训练过程如下:
定义具有一些可学习参数(权重)的神经网络
迭代输入数据
通过网络处理输入
计算损失
将梯度传播回到网络参数中
使用梯度下降更新网络权重,
输出
只需定义forward函数,并backward自动使用函数autograd,可以在forward功能中使用任何Tensor操作。
用net.parameters()返回模型学习的参数
输出
前向传播的输入输出都是autograd.Variable
输出
将随机梯度的所有参数和backprops的梯度缓冲区置零:
注意:
例如
输出
如下调用
输出
神经网络包包含形成深层神经网络、构建模块的各种模块和损失函数,官网提供一个完整的文档列表。
用
1.Pytorch实现神经网络的典型训练过程
在这里以Lenet模型为例,由两个卷积层,两个池化层,以及两个全连接层组成。 卷积核大小为5*5,stride为1,采用MAX池化。以该网络分类数字图像为例:Pytorch实现神经网络的典型训练过程如下:
定义具有一些可学习参数(权重)的神经网络
迭代输入数据
通过网络处理输入
计算损失
将梯度传播回到网络参数中
使用梯度下降更新网络权重,
weight = weight - learning_rate * gradient
2.定义网络
Lenet模型的Pytorch代码如下: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) 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=(5, 5), stride=(1, 1)) (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1)) (fc1): Linear (400 -> 120) (fc2): Linear (120 -> 84) (fc3): Linear (84 -> 10) )
只需定义forward函数,并backward自动使用函数autograd,可以在forward功能中使用任何Tensor操作。
用net.parameters()返回模型学习的参数
params = list(net.parameters()) print(len(params)) print(params[0].size()) # conv1's .weight
输出
10 (6L, 1L, 5L, 5L)
前向传播的输入输出都是autograd.Variable
input = Variable(torch.randn(1, 1, 32, 32)) out = net(input) print(out)
输出
Variable containing: 0.0809 0.0700 0.0478 -0.0280 -0.0281 0.1334 -0.0481 0.0195 -0.0522 0.1430 [torch.FloatTensor of size 1x10]
将随机梯度的所有参数和backprops的梯度缓冲区置零:
net.zero_grad() out.backward(torch.randn(1, 10))
注意:
torch.nn仅支持
mini-batch,整个
torch.nn软件包仅支持输入,这些输入是小批量样品,而不是单个样品。例如,nn.Conv2d将采用
nSamples x nChannels x Height x Width的
4D Tensor。如果有一个样本,只需使用
input.unsqueeze(0)来添加假批量维。
3.损失函数
损失函数采用(输出,目标)输入对,并计算估计输出距离目标距离的值。nn包下有几种不同的损失函数,具体参考官网提供的损失函数说明。一个简单的损失是:
nn.MSELoss,用于计算输入和目标之间的平均平方误差。
例如
output = net(input) target = Variable(torch.arange(1, 11)) # a dummy target, for example criterion = nn.MSELoss() loss = criterion(output, target) print(loss)
输出
Variable containing: 38.1674 [torch.FloatTensor of size 1]
4.反向传播
要反向传播误差,只需要用loss.backward(),需要清除现有的梯度,否则渐变将累积到现有的梯度。
如下调用
loss.backward(),并且看看在
conv1之前和之后的
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 Variable containing: 0 0 0 0 0 0 [torch.FloatTensor of size 6] conv1.bias.grad after backward Variable containing: -0.1000 0.0343 -0.1194 -0.0136 -0.0767 0.0224 [torch.FloatTensor of size 6]
神经网络包包含形成深层神经网络、构建模块的各种模块和损失函数,官网提供一个完整的文档列表。
5.权重更新
实现中使用的最简单的更新规则是随机梯度下降(SGD):
weight = weight - learning_rate * gradient
用
python具体实现如下:
learning_rate = 0.01 for f in net.parameters(): f.data.sub_(f.grad.data * learning_rate)
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
相关文章推荐
- 基于PyTorch的深度学习入门教程(五)——训练神经网络分类器
- 神经网络入门
- 神经网络模型入门之模型概述
- [机器学习入门] 李宏毅机器学习笔记-33 (Recurrent Neural Network part 2;循环神经网络 part 2)
- 神经网络和机器学习基础入门分享
- 机器学习笔记——神经网络入门篇
- 手把手入门神经网络系列(2)_74行代码实现手写数字识别
- 神经网络入门(连载之六)
- 入门实现神经网络
- Tensorflow入门练习(简单神经网络的训练过程)
- 转:神经网络编程入门
- 手把手入门神经网络系列(1)_从初等数学的角度初探神经网络
- (二)神经网络入门之Logistic回归(分类问题)
- tensorflow入门之训练简单的神经网络
- 神经网络入门 第3章 S函数
- 神经网络入门(连载之四)
- 神经网络编程入门
- 神经网络入门 第二部分
- 神经网络入门(连载之一)
- 神经网络入门 Python 十行核心代码