双向RNN理解笔记

单层

时间序列展开表示python

image.png

公式表示3d

image.png

这里的[S1t→;S2t→]作的是一个拼接,若是他们都是1000维的,拼接在一块儿就是2000维的了。 双向RNN须要的内存是单向RNN的两倍,由于在同一时间点,双向RNN须要保存两个方向上的权重参数,在分类的时候,须要同时输入两个隐藏层输出的信息。code

举例表示blog

image.png

image.png

程序表示内存

n是很是类似的.
定义前向和反向rnn_cell
定义前向和反向rnn_cell的初始状态
准备好序列
调用bidirectional_dynamic_rnn
import tensorflow as tf
from tensorflow.contrib import rnn
cell_fw = rnn.LSTMCell(10)
cell_bw = rnn.LSTMCell(10)
initial_state_fw = cell_fw.zero_state(batch_size)
initial_state_bw = cell_bw.zero_state(batch_size)
seq = ...
seq_length = ...
(outputs, states)=tf.nn.bidirectional_dynamic_rnn(cell_fw, cell_bw, seq,
 seq_length, initial_state_fw,initial_state_bw)
out = tf.concat(outputs, 2)

多层

时间序列展开表示image.png image.pngget

公式表示input

image.png

结构表示it

image.png

程序表示io

def get_mul_cell(hidden_dim, num_layers):
            # 建立多层lstm
            def get_en_cell(hidden_dim):
                # 建立单个lstm
                enc_base_cell = tf.nn.rnn_cell.BasicLSTMCell(hidden_dim, forget_bias=1.0)
                return enc_base_cell
            return tf.nn.rnn_cell.MultiRNNCell([get_en_cell(hidden_dim) for _ in range(num_layers)])


        with tf.variable_scope("encoder"):
            # 构建双向lstm
            encode_cell_fw = get_mul_cell(self.config.hidden_dim, self.config.num_layers)
            encode_cell_bw = get_mul_cell(self.config.hidden_dim, self.config.num_layers)
            bi_encoder_output, bi_encoder_state = tf.nn.bidirectional_dynamic_rnn(  cell_fw=encode_cell_fw,
                                                                                    cell_bw=encode_cell_bw,
                                                                                    inputs=embed_en_seqs,
                                                                                    sequence_length=self.en_length,
                                                                                    dtype=tf.float32,
                                                                                    time_major=False)
相关文章
相关标签/搜索