循环神经网络(LSTM和GRU)(2)
1、tf.nn.dynamic_rnn()函数
参考:http://www.360doc.com/content/17/0321/10/10408243_638692495.shtml
参考:https://blog.csdn.net/u010089444/article/details/60963053
参考:https://blog.csdn.net/u010223750/article/details/71079036
在用rnn处理长文本时,使用dynamic_rnn()可以跳过padding部分的计算,从而减少计算量。假设有两个文本,一个为10,一个为5,那么需要对第二文本进行0-padding填充,得到shape维度[2,10,dim],其中dim为词向量的维度,
使用dynamic_run的代码如下:
outputs,last_states=tf.nn.dynamic_rnn(cell=cell,dtype=tf.float32,sequence_length=x_lengths,inputs=x)
其中cell为RNN节点,比如tf.contrib.rnn.BasicLSTMCell,x是0-padding之后的数据,x_lengths是每个文本的长度。
tf.nn.dynamic_rnn()返回两个变量,第一个是每个step的输出值,以上面的例子为例,得到的维度则为:[2,10,dim],第二个是最终的状态,是由(c,h)组成的tuple,均为[batch,dim],其中dynamic有个参数sequence_length,用来指定每个example的长度,
以如下为例:
import tensorflow as tf
import numpy as np
# 创建输入数据
X = np.random.randn(2, 10, 8) #其中2为batch_size,10为文本最大长度,8为embedding_size
# 第二个example长度为6 #randn从标准正态分布返回值,rand从[0,1)返回值
X[1,6:] = 0
X_lengths = [10, 6]
with tf.variable_scope('c', reuse=None) as scope: #根据调用是否首次来调整reuse为True或False
cell = tf.contrib.rnn.BasicLSTMCell(num_units=64, state_is_tuple=True) #num_units指的是一个cell中神经元的个数
#循环层的cell数目表示:X_split = tf.split(XR, time_step_size, 0) (X_split中划分出来的arrays数量为循环层的cell个数)
#在任意时刻,LSTM cell会产生两个内部状态c和h,当state_is_tuple=True时,该状态的c和h是分开记录的,放在一个二元tuple返回,维度均为[batch,embedding_size];如果state_is_tuple=False时,两个状态就按列连接起来返回,
outputs, last_states = tf.nn.dynamic_rnn( #outputs返回的维度是[2,10,8],last_states返回的维度是[2,64]
cell=cell, #tf.nn.dynamic_rnn用于实现不同迭代传入的batch可以是长度不同的数据,但是同一次迭代一个batch内部所有的数据长度仍然是固定的。也即第一次传入为[batch_size,10],第二次[batch_size,8],第三次[batch_size,11]
dtype=tf.float64, #然而对于rnn来说,每次输入的则是最大长度,也即[batch_size,max_seq]
sequence_length=X_lengths, #假若设置第二个example的有效长度为6,当传入这个参数时,tensorflow对6之后的padding就不计算了,其last_states将重复第6步的计算到末尾,而outputs中超过6步的结果会被置零。
inputs=X)
result = tf.contrib.learn.run_n(
{"outputs": outputs, "last_states": last_states},
n=1,
feed_dict=None)
print (result[0])
assert result[0]["outputs"].shape == (2, 10, 64) # 第二个example中的outputs超过6步(7-10步)的值应该为0
assert (result[0]["outputs"][1,7,:] == np.zeros(cell.output_size)).all()
2、tf.contrib.rnn.BasicLSTMCell()函数和tf.contrib.rnn.BasicRNNCell()函数
参考:https://blog.csdn.net/u013082989/article/details/73693392
参考:https://blog.csdn.net/u010089444/article/details/60963053
BasicRNNCell是最基本的RNN cell单元,输入参数包括:
num_units:RNN层神经元的个数
activation:内部状态间的激活函数
reuse:决定是否重用现有域的变量
BasicLSTMCell是最基本的LSTM循环神经网络单元,输入参数包括:
num_units:LSTM cell层中的单元数
forget_bias:forget gates中的偏置
state_is_tuple:返回(c_state,m_state)二元组
activation:状态间转移的激活函数
reuse:是否重用变量
以MNIST手写体数据集为例:
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
from tensorflow.contrib import rnn
import numpy as np
input_vec_size = lstm_size = 28 # 输入向量的维度
time_step_size = 28 # 循环层长度
batch_size = 128
test_size = 256
def init_weights(shape):
return tf.Variable(tf.random_normal(shape, stddev=0.01))
def model(X, W, B, lstm_size):
# X, input shape: (batch_size, time_step_size, input_vec_size)
# XT shape: (time_step_size, batch_size, input_vec_size)
XT = tf.transpose(X, [1, 0, 2]) # permute time_step_size and batch_size,[28, 128, 28]
# XR shape: (time_step_size * batch_size, input_vec_size)
XR = tf.reshape(XT, [-1, lstm_size]) # each row has input for each lstm cell (lstm_size=input_vec_size)
# Each array shape: (batch_size, input_vec_size)
X_split = tf.split(XR, time_step_size, 0) # split them to time_step_size (28 arrays),shape = [(128, 28),(128, 28)...]
# Make lstm with lstm_size (each input vector size). num_units=lstm_size; forget_bias=1.0
lstm = rnn.BasicLSTMCell(lstm_size, forget_bias=1.0, state_is_tuple=True)
# Get lstm cell output, time_step_size (28) arrays with lstm_size output: (batch_size, lstm_size)
# rnn..static_rnn()的输出对应于每一个timestep,如果只关心最后一步的输出,取outputs[-1]即可
outputs, _states = rnn.static_rnn(lstm, X_split, dtype=tf.float32) # 时间序列上每个Cell的输出:[... shape=(128, 28)..]
# Linear activation
# Get the last output
return tf.matmul(outputs[-1], W) + B, lstm.state_size # State size to initialize the stat
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels
# 将每张图用一个28x28的矩阵表示,(55000,28,28,1)
trX = trX.reshape(-1, 28, 28)
teX = teX.reshape(-1, 28, 28)
X = tf.placeholder("float", [None, 28, 28])
Y = tf.placeholder("float", [None, 10])
# get lstm_size and output 10 labels
W = init_weights([lstm_size, 10]) # 输出层权重矩阵28×10
B = init_weights([10]) # 输出层bais
py_x, state_size = model(X, W, B, lstm_size)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x, labels=Y))
train_op = tf.train.RMSPropOptimizer(0.001, 0.9).minimize(cost)
predict_op = tf.argmax(py_x, 1)
session_conf = tf.ConfigProto()
session_conf.gpu_options.allow_growth = True
# Launch the graph in a session
with tf.Session(config=session_conf) as sess:
# you need to initialize all variables
tf.global_variables_initializer().run()
for i in range(100):
for start, end in zip(range(0, len(trX), batch_size), range(batch_size, len(trX)+1, batch_size)):
sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end]})
test_indices = np.arange(len(teX)) # Get A Test Batch
np.random.shuffle(test_indices)
test_indices = test_indices[0:test_size]
print(i, np.mean(np.argmax(teY[test_indices], axis=1) ==
sess.run(predict_op, feed_dict={X: teX[test_indices]})))
循环神经网络(LSTM和GRU)(2)的更多相关文章
- 十 | 门控循环神经网络LSTM与GRU(附python演练)
欢迎大家关注我们的网站和系列教程:http://panchuang.net/ ,学习更多的机器学习.深度学习的知识! 目录: 门控循环神经网络简介 长短期记忆网络(LSTM) 门控制循环单元(GRU) ...
- 循环神经网络LSTM RNN回归:sin曲线预测
摘要:本篇文章将分享循环神经网络LSTM RNN如何实现回归预测. 本文分享自华为云社区<[Python人工智能] 十四.循环神经网络LSTM RNN回归案例之sin曲线预测 丨[百变AI秀]& ...
- Pytorch循环神经网络LSTM时间序列预测风速
#时间序列预测分析就是利用过去一段时间内某事件时间的特征来预测未来一段时间内该事件的特征.这是一类相对比较复杂的预测建模问题,和回归分析模型的预测不同,时间序列模型是依赖于事件发生的先后顺序的,同样大 ...
- 循环神经网络-LSTM进阶
基础的LSTM模型,单隐层,隐层单神经元,而实际中一般需要更为复杂的网络结构, 下面借用手写数字的经典案例构造比较复杂的LSTM模型,并用代码实现. 单隐层,隐层多神经元 # -*- coding:u ...
- 循环神经网络-LSTM
LSTM(Long Short-Term Memory)是长短期记忆网络,是一种时间递归神经网络,适合于处理和预测时间序列中间隔和延迟相对较长的重要事件. LSTM能够很大程度上缓解长期依赖的问题. ...
- 深度学习 循环神经网络 LSTM 示例
最近在网上找到了一个使用LSTM 网络解决 世界银行中各国 GDP预测的一个问题,感觉比较实用,毕竟这是找到的唯一一个可以正确运行的程序. #encoding:UTF-8 import pandas ...
- 循环神经网络之LSTM和GRU
看了一些LSTM的博客,都推荐看colah写的博客<Understanding LSTM Networks> 来学习LSTM,我也找来看了,写得还是比较好懂的,它把LSTM的工作流程从输入 ...
- 循环神经网络(LSTM和GRU)(1)
循环神经网络的简单实现: import tensorflow as tf x=[1,2] state=[0.0,0.0] w_cell_state=np.array([[0.1,0.2],[0.3,0 ...
- 机器学习(ML)九之GRU、LSTM、深度神经网络、双向循环神经网络
门控循环单元(GRU) 循环神经网络中的梯度计算方法.当时间步数较大或者时间步较小时,循环神经网络的梯度较容易出现衰减或爆炸.虽然裁剪梯度可以应对梯度爆炸,但无法解决梯度衰减的问题.通常由于这个原因, ...
- 深度学习四从循环神经网络入手学习LSTM及GRU
循环神经网络 简介 循环神经网络(Recurrent Neural Networks, RNN) 是一类用于处理序列数据的神经网络.之前的说的卷积神经网络是专门用于处理网格化数据(例如一个图像)的神经 ...
随机推荐
- Linux动态库和静态库
Linux下动态库查看办法:nm -D libavformat.so Linux下静态库查看办法:ar -t libavformat.a ------------------------------- ...
- dp基础大概 (8.6)
一些前言: 据说动态规划会用排序,数据结构来进行乱搞优化操作 动态规划滴核心是个啥呢?状态表示和状态转移 设状态:哪些因素会影响到最终答案,就把哪些因素用数组的维度表示出来 要充分描述,也要简洁 举个 ...
- 安装fedora23后的一些杂项设置
Boxes是创建虚拟机的技术 tweak: 拧, 捏; 微调 he gave the boy's ear a painful tweak. it's a small tweak over the ra ...
- java开发客户端发送请求到服务器端出现这样:JSON parse error: Unexpected character ('}' (code 125)): was expecting
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unexpected cha ...
- dig中文帮助
NAME(名称) dig — 发送域名查询信息包到域名服务器 SYNOPSIS(总览) dig [@server] domain [⟨query-type⟩] [⟨query-clas ...
- GMSSL中生成SM2或RSA1024或RSA2048的证书相关命令
1.生成KEY:gmssl sm2 -genkey -out 01.root.pemgmssl genrsa -out 01.root_plain.key 2048gmssl genrsa -out ...
- 【BASIS系列】SAP 批量锁住用户和TCODE的方法
公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[BASIS系列]SAP 批量锁住用户和TCOD ...
- ToolProvider.getSystemJavaCompiler()方法空指针的排坑
起因: 我在做一个编译Java代码的功能,基本写的差不多了,我就想把它打包部署到我服务器上跑一跑,但是这不做不知道,一做果然就出了问题.我在IDEA上跑一点问题都没有,但是打包成Jar后,后台就显示空 ...
- [Markdown] 01 简单应用 第一弹
目录 0. "调用函数前必先声明" 0.1 Table of Content 0.2 分割线 0.3 引用 0.4 标记 0.5 关于 html 0.6 代码块 用法 1 用法 2 ...
- python基础循环语句练习
1.使用while循环输入 1 2 3 4 5 6 8 9 10 n = 1 while n < 11: if n == 7: pass else: print(n) n = n + 1 ...