# 变长双向rnn的正确使用姿势

## 如何使用双向RNN

• stack_bidirectional_dynamic_rnn
• bidirectional_dynamic_rnn
二者的实现上大同小异，放置的位置也不一样，前者放在contrib下面，而后者显得更加根红苗正，放在了tf的核心库下面。在使用时二者的返回值也有所区别。下面就来一一介绍。

## 示例代码

import tensorflow as tf
import numpy as np
tf.reset_default_graph()
# 创建输入数据
X = np.random.randn(2, 4, 5)# 批次 、序列长度、样本维度

# 第二个样本长度为3
X[1,2:] = 0
seq_lengths = [4, 2]

Gstacked_rnn = []
Gstacked_bw_rnn = []
for i in range(3):
Gstacked_rnn.append(tf.contrib.rnn.GRUCell(3))
Gstacked_bw_rnn.append(tf.contrib.rnn.GRUCell(3))

#建立前向和后向的三层RNN
Gmcell = tf.contrib.rnn.MultiRNNCell(Gstacked_rnn)
Gmcell_bw = tf.contrib.rnn.MultiRNNCell(Gstacked_bw_rnn)

sGbioutputs, sGoutput_state_fw, sGoutput_state_bw = tf.contrib.rnn.stack_bidirectional_dynamic_rnn([Gmcell],[Gmcell_bw], X,sequence_length=seq_lengths,                                           dtype=tf.float64)

Gbioutputs, Goutput_state_fw = tf.nn.bidirectional_dynamic_rnn(Gmcell,Gmcell_bw, X,sequence_length=seq_lengths,dtype=tf.float64)

## 代码：BiRNN输出

#建立一个会话
sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())

sgbresult,sgstate_fw,sgstate_bw=sess.run([sGbioutputs,sGoutput_state_fw,sGoutput_state_bw])
print("全序列：\n", sgbresult[0])
print("短序列：\n", sgbresult[1])
print('Gru的状态：',len(sgstate_fw[0]),'\n',sgstate_fw[0][0],'\n',sgstate_fw[0][1],'\n',sgstate_fw[0][2])
print('Gru的状态：',len(sgstate_bw[0]),'\n',sgstate_bw[0][0],'\n',sgstate_bw[0][1],'\n',sgstate_bw[0][2])


## 代码：BiRNN输出

gbresult,state_fw=sess.run([Gbioutputs,Goutput_state_fw])

print("正向：\n", gbresult[0])
print("反向：\n", gbresult[1])
print('状态：',len(state_fw),'\n',state_fw[0],'\n',state_fw[1])  #state_fw[0]：【层，批次，cell个数】 重头到最后一个序列
print(state_fw[0][-1],state_fw[1][-1])
out  = np.concatenate((state_fw[0][-1],state_fw[1][-1]),axis = 1)
print("拼接",out)

## 代码：LSTM的双向RNN

stacked_rnn = []
stacked_bw_rnn = []
for i in range(3):
stacked_rnn.append(tf.contrib.rnn.LSTMCell(3))
stacked_bw_rnn.append(tf.contrib.rnn.LSTMCell(3))

mcell = tf.contrib.rnn.MultiRNNCell(stacked_rnn)
mcell_bw = tf.contrib.rnn.MultiRNNCell(stacked_bw_rnn)

bioutputs, output_state_fw, output_state_bw = tf.contrib.rnn.stack_bidirectional_dynamic_rnn([mcell],[mcell_bw], X,sequence_length=seq_lengths,
dtype=tf.float64)

bioutputs, output_state_fw = tf.nn.bidirectional_dynamic_rnn(mcell,mcell_bw, X,sequence_length=seq_lengths,
dtype=tf.float64)

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120