1. 程式人生 > >tensorflow學習之stack_bidirectional_rnn使用詳解

tensorflow學習之stack_bidirectional_rnn使用詳解

tf.contrib.rnn.stack_bidirectional_rnn

tf.contrib.rnn.stack_bidirectional_rnn(
    cells_fw,
    cells_bw,
    inputs,
    initial_states_fw=None,
    initial_states_bw=None,
    dtype=None,
    sequence_length=None,
    scope=None
)

建立一個雙向迴圈神經網路。

堆疊幾個雙向rnn層。組合的前向和後向層輸出用作下一層的輸入。Tf.bidirectional_rnn不允許在層之間共享前向和後向資訊。第一個前向和後向cells必須皮匹配。兩個方向的初始狀態為0.並且不返回中間狀態。

引數說明:

  • cells_fw:RNNCell的例項list,每層一個,用於前向。
  • cells_bw: RNNCell的例項list,每層一個,用於後向。
  • inputs:一個長度為T的輸出list,每個張量的形狀為[batch_size,input_size]
  • initial_states_fw:可選引數。前向RNN的初始狀態list.每個張量必須具有適當的型別和形狀[batch_size,cell_fw.state_size].
  • Initial_state_bw: 可選引數。後向RNN的初始狀態list.每個張量必須具有適當的型別和形狀[batch_size,cell_bw.state_size].
  • dtype:可選引數。初始狀態的資料型別。初始狀態沒提供時則要求該引數。
  • sequence_length:可選引數,一個int32/int64的向量,大小為[batch_size],包含每個序列的實際長度。
  • scope:建立的子圖的VariableScope。預設為None。

返回:

一個(outputs, output_state_fw, output_state_bw)元組,其中:

  • outputs:是一個長度為T的列表(每個輸入對應一個),它們是深度級聯的前向和後向輸出。
  • output_states_fw:前向rnn的最終輸出狀態,每個層一個。
  • output_states_bw:後向rnn的最終輸出狀態,每個層一個。

程式碼例項:

import tensorflow as tf


fw_units=[10,20,30]
bw_units=[10,20,30]
fw_cells=[tf.nn.rnn_cell.BasicLSTMCell(unit) for unit in fw_units] #前向LSTM層
bw_cells=[tf.nn.rnn_cell.BasicLSTMCell(unit) for unit in bw_units] #後向LSTM層
batch_size=10
max_time=100
depth=64
inputs=tf.Variable(tf.random_normal([batch_size,max_time,depth]))
inputs=tf.unstack(inputs,axis=1)
outputs, output_state_fw, output_state_bw=tf.contrib.rnn.stack_bidirectional_rnn(fw_cells,bw_cells,inputs,dtype=tf.float32)
print(len(outputs)) #100
print(outputs[0].shape) #(10, 60)
print(outputs[-1].shape) #(10, 60)
print(len(output_state_fw)) #3
print(output_state_fw[0].h)
print(output_state_fw[0].c.shape) #(10, 10)
print(output_state_fw[1].c.shape) #(10, 20)
print(output_state_bw[0].c.shape) #(10, 10)
print(output_state_fw[2].h.shape) #(10, 30)