Pytorch实现LSTM和GRU示例


Posted in Python onJanuary 14, 2020

为了解决传统RNN无法长时依赖问题,RNN的两个变体LSTM和GRU被引入。

LSTM

Long Short Term Memory,称为长短期记忆网络,意思就是长的短时记忆,其解决的仍然是短时记忆问题,这种短时记忆比较长,能一定程度上解决长时依赖。

Pytorch实现LSTM和GRU示例

上图为LSTM的抽象结构,LSTM由3个门来控制,分别是输入门、遗忘门和输出门。输入门控制网络的输入,遗忘门控制着记忆单元,输出门控制着网络的输出。最为重要的就是遗忘门,可以决定哪些记忆被保留,由于遗忘门的作用,使得LSTM具有长时记忆的功能。对于给定的任务,遗忘门能够自主学习保留多少之前的记忆,网络能够自主学习。

具体看LSTM单元的内部结构:

Pytorch实现LSTM和GRU示例

Pytorch实现LSTM和GRU示例

Pytorch实现LSTM和GRU示例

Pytorch实现LSTM和GRU示例

在每篇文章中,作者都会使用和标准LSTM稍微不同的版本,针对特定的任务,特定的网络结构往往表现更好。

GRU

Pytorch实现LSTM和GRU示例

上述的过程的线性变换没有使用偏置。隐藏状态参数不再是标准RNN的4倍,而是3倍,也就是GRU的参数要比LSTM的参数量要少,但是性能差不多。

Pytorch

在Pytorch中使用nn.LSTM()可调用,参数和RNN的参数相同。具体介绍LSTM的输入和输出:

输入: input, (h_0, c_0)

input:输入数据with维度(seq_len,batch,input_size)

h_0:维度为(num_layers*num_directions,batch,hidden_size),在batch中的

初始的隐藏状态.

c_0:初始的单元状态,维度与h_0相同

输出:output, (h_n, c_n)

output:维度为(seq_len, batch, num_directions * hidden_size)。

h_n:最后时刻的输出隐藏状态,维度为 (num_layers * num_directions, batch, hidden_size)

c_n:最后时刻的输出单元状态,维度与h_n相同。

LSTM的变量:

Pytorch实现LSTM和GRU示例

以MNIST分类为例实现LSTM分类

MNIST图片大小为28×28,可以将每张图片看做是长为28的序列,序列中每个元素的特征维度为28。将最后输出的隐藏状态Pytorch实现LSTM和GRU示例 作为抽象的隐藏特征输入到全连接层进行分类。最后输出的

导入头文件:

import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
from torchvision import transforms
class Rnn(nn.Module):
  def __init__(self, in_dim, hidden_dim, n_layer, n_classes):
    super(Rnn, self).__init__()
    self.n_layer = n_layer
    self.hidden_dim = hidden_dim
    self.lstm = nn.LSTM(in_dim, hidden_dim, n_layer, batch_first=True)
    self.classifier = nn.Linear(hidden_dim, n_classes)

  def forward(self, x):
    out, (h_n, c_n) = self.lstm(x)
    # 此时可以从out中获得最终输出的状态h
    # x = out[:, -1, :]
    x = h_n[-1, :, :]
    x = self.classifier(x)
    return x

训练和测试代码:

transform = transforms.Compose([
  transforms.ToTensor(),
  transforms.Normalize([0.5], [0.5]),
])

trainset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=128, shuffle=True)

testset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=100, shuffle=False)

net = Rnn(28, 10, 2, 10)

net = net.to('cpu')
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.1, momentum=0.9)

# Training
def train(epoch):
  print('\nEpoch: %d' % epoch)
  net.train()
  train_loss = 0
  correct = 0
  total = 0
  for batch_idx, (inputs, targets) in enumerate(trainloader):
    inputs, targets = inputs.to('cpu'), targets.to('cpu')
    optimizer.zero_grad()
    outputs = net(torch.squeeze(inputs, 1))
    loss = criterion(outputs, targets)
    loss.backward()
    optimizer.step()

    train_loss += loss.item()
    _, predicted = outputs.max(1)
    total += targets.size(0)
    correct += predicted.eq(targets).sum().item()

    print(batch_idx, len(trainloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'
      % (train_loss/(batch_idx+1), 100.*correct/total, correct, total))

def test(epoch):
  global best_acc
  net.eval()
  test_loss = 0
  correct = 0
  total = 0
  with torch.no_grad():
    for batch_idx, (inputs, targets) in enumerate(testloader):
      inputs, targets = inputs.to('cpu'), targets.to('cpu')
      outputs = net(torch.squeeze(inputs, 1))
      loss = criterion(outputs, targets)

      test_loss += loss.item()
      _, predicted = outputs.max(1)
      total += targets.size(0)
      correct += predicted.eq(targets).sum().item()

      print(batch_idx, len(testloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'
        % (test_loss/(batch_idx+1), 100.*correct/total, correct, total))




for epoch in range(200):
  train(epoch)
  test(epoch)

以上这篇Pytorch实现LSTM和GRU示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python实现比较两个列表(list)范围
Jun 12 Python
python安装PIL模块时Unable to find vcvarsall.bat错误的解决方法
Sep 19 Python
Python读csv文件去掉一列后再写入新的文件实例
Dec 28 Python
Python星号*与**用法分析
Feb 02 Python
python实现远程通过网络邮件控制计算机重启或关机
Feb 22 Python
Python cookbook(数据结构与算法)通过公共键对字典列表排序算法示例
Mar 15 Python
python浪漫表白源码
Apr 05 Python
浅谈Django中的QueryDict元素为数组的坑
Mar 31 Python
在python中实现求输出1-3+5-7+9-......101的和
Apr 02 Python
使用Python防止SQL注入攻击的实现示例
May 21 Python
PyTorch的torch.cat用法
Jun 28 Python
python pymysql库的常用操作
Oct 16 Python
Python生成词云的实现代码
Jan 14 #Python
pytorch-RNN进行回归曲线预测方式
Jan 14 #Python
利用pytorch实现对CIFAR-10数据集的分类
Jan 14 #Python
pytorch下使用LSTM神经网络写诗实例
Jan 14 #Python
python使用openCV遍历文件夹里所有视频文件并保存成图片
Jan 14 #Python
pytorch实现mnist数据集的图像可视化及保存
Jan 14 #Python
Pytorch在dataloader类中设置shuffle的随机数种子方式
Jan 14 #Python
You might like
PHP简单系统查询模块代码打包下载
2008/06/07 PHP
从康盛产品(discuz)提取出来的模板类
2011/06/28 PHP
php 无限分类 树形数据格式化代码
2016/10/11 PHP
大家未必知道的Js技巧收藏
2008/04/07 Javascript
JavaScript中变量提升 Hoisting
2012/07/03 Javascript
jQuery中读取json文件示例代码
2013/05/10 Javascript
JavaScript字符串对象replace方法实例(用于字符串替换或正则替换)
2014/10/16 Javascript
domReady的实现案例
2016/11/23 Javascript
详解nodejs 文本操作模块-fs模块(四)
2016/12/22 NodeJs
关于meta viewport中target-densitydpi属性详解(推荐)
2017/08/18 Javascript
node和vue实现商城用户地址模块
2018/12/05 Javascript
简单两步使用node发送qq邮件的方法
2019/03/01 Javascript
Vuex modules模式下mapState/mapMutations的操作实例
2019/10/17 Javascript
小程序实现投票进度条
2019/11/20 Javascript
python实现定制交互式命令行的方法
2014/07/03 Python
python爬取m3u8连接的视频
2018/02/28 Python
python实现csv格式文件转为asc格式文件的方法
2018/03/23 Python
在Django中输出matplotlib生成的图片方法
2018/05/24 Python
在Pandas中DataFrame数据合并,连接(concat,merge,join)的实例
2019/01/29 Python
Python中字符串与编码示例代码
2019/05/20 Python
python实现超级玛丽游戏
2020/03/18 Python
django 利用Q对象与F对象进行查询的实现
2020/05/15 Python
一文弄懂Pytorch的DataLoader, DataSet, Sampler之间的关系
2020/07/03 Python
html5 sessionStorage会话存储_动力节点Java学院整理
2017/07/06 HTML / CSS
中国茶叶、茶具一站式网上购物商城:醉品茶城
2018/07/03 全球购物
亚洲在线旅行门户网站:Expedia.com.hk(智游网)
2020/04/14 全球购物
六查六看剖析材料
2014/02/15 职场文书
2014年9.18纪念日演讲稿
2014/09/14 职场文书
个人先进事迹总结
2015/02/26 职场文书
乡镇法制宣传日活动总结
2015/05/05 职场文书
2015年幼儿教育工作总结
2015/07/24 职场文书
Nginx反爬虫策略,防止UA抓取网站
2021/03/31 Servers
golang通过递归遍历生成树状结构的操作
2021/04/28 Golang
nginx的zabbix 5.0安装部署的方法步骤
2021/07/16 Servers
Ubuntu Server 安装Tomcat并配置systemctl
2022/04/28 Servers
mysql字段为NULL索引是否会失效实例详解
2022/05/30 MySQL