如何在张量流中实现LSTM的更复杂的initial_state

时间:2018-03-22 10:47:55

标签: python-3.x tensorflow lstm

我目前正在使用tensorflow和python处理多层LSTM。 我使用tf.nn.dynamic_rnn中的 initial_state 将单元格的上一个状态传递给下一步。

像这样创建图层:

cells = []
for c in range(0, num_layers):
    cells.append(tf.nn.rnn_cell.BasicLSTMCell(num_units = num_units, forget_bias = 1.0, activation = tf.nn.tanh))
basic_cell = tf.nn.rnn_cell.MultiRNNCell(cells)
state_series, current_state = tf.nn.dynamic_rnn(basic_cell, x, dtype=tf.float32, initial_state = rnn_tuple_state)

使用类似的尺寸和尺寸:

rnn_tuple_state: <class 'tuple'>                                                len:num_layers
  Layer  0 : <class 'tensorflow.python.ops.rnn_cell_impl.LSTMStateTuple'>       len:2
     cell: <class 'tensorflow.python.framework.ops.Tensor'>                     dimensions:(outputs, truncated_backprop_len)
     hidden: <class 'tensorflow.python.framework.ops.Tensor'>                   dimensions:(outputs, truncated_backprop_len)
  Layer 1 : ...
  ...
  Layer num_layers : ...

state_series: <class 'tensorflow.python.framework.ops.Tensor'>                  dimension:(outputs, truncated_backprop_len, num_units)
current_state: <class 'tuple'>                                                  len:num_layers
    Layer 0 : <class 'tensorflow.python.ops.rnn_cell_impl.LSTMStateTuple'>      len:2
       cell_state: <class 'tensorflow.python.framework.ops.Tensor'> (7, 360)    dimensions:(outputs, truncated_backprop_len)
       hidden_state: <class 'tensorflow.python.framework.ops.Tensor'> (7, 360)  dimensions:(outputs, truncated_backprop_len)
    Layer 1 : ...
    ...
    Layer num_layers: ...

使用这个我能够实现状态空间LSTM:

simple_initial-state

在蓝色的图片中是zero_state,在绿色的2个LSTM图层中,列都是相同的单元格,只应显示重复,箭头表示状态从一个步骤传递到下一个步骤。 / p>

现在我想使用一个更复杂的initial_state,不仅将状态从一个步骤传递到另一个步骤,而且从一个层传递到另一个层,如下所示:

wanted complex initial_state

这就是我现在被卡住的地方。 我只是在初始状态中添加了额外的元组,但这导致我只是出现像 ValueError这样的错误:解压缩的值太多(预期为2)。 我也在研究其他类型的LSTM细胞,但无法识别所需的细胞。

所以我的问题是,如何在tensorflow中实现这个更复杂的initial_state,例如:要使用哪种细胞类型或如何塑造initial_state?

提前谢谢。

1 个答案:

答案 0 :(得分:0)

您的单元格状态必须是单个数字向量,其数量必须与LSTM单元格中定义的大小相同。 LSTM单元将输出与其输入相同的大小。当您有多个图层时,通常会通过第一层的输出将信息从一个层传递到下一个层到第二个层的输入。你通常不会通过国家。但是,如果你想以这种方式进行实验,我认为这样做的方法是将两个状态加在一起,因为你无法真正改变形状。您可能会认为剩余网络的优先级是这种想法的理由(尽管我不知道这是不是一个好主意)。

如果要输出与输入不同的单元状态大小,以便在输入单元状态之前实际连接层的状态,则必须手动编码RNN,而不是LSTM单元包装器将允许这种配置。

为了更好地了解我在这里读到的LSTM细胞的内部结构:

http://colah.github.io/posts/2015-08-Understanding-LSTMs/