无法使用MultiRNNCell和dynamic_rnn堆叠LSTM

zda*_*ght 6 multi-layer lstm tensorflow

我正在尝试建立一个多变量时间序列预测模型.我按照以下教程进行温度预测.http://nbviewer.jupyter.org/github/addfor/tutorials/blob/master/machine_learning/ml16v04_forecasting_with_LSTM.ipynb

我想通过使用以下代码将他的模型扩展到多层LSTM模型:

cell = tf.contrib.rnn.LSTMCell(hidden, state_is_tuple=True)  
cell = tf.contrib.rnn.MultiRNNCell([cell] * num_layers,state_is_tuple=True)  
output, _ = tf.nn.dynamic_rnn(cell=cell, inputs=features, dtype=tf.float32)
Run Code Online (Sandbox Code Playgroud)

但我有一个错误说:

ValueError:尺寸必须相等,但对于输入形状为'rnn/while/rnn/multi_rnn_cell/cell_0/cell_0/lstm_cell/MatMul_1'(op:'MatMul')的值为256和142:[?,256],[142,512] .

当我尝试这个时:

cell = []
for i in range(num_layers):
    cell.append(tf.contrib.rnn.LSTMCell(hidden, state_is_tuple=True))
cell = tf.contrib.rnn.MultiRNNCell(cell,state_is_tuple=True)
output, _ = tf.nn.dynamic_rnn(cell=cell, inputs=features, dtype=tf.float32)
Run Code Online (Sandbox Code Playgroud)

我没有这样的错误,但预测真的很糟糕.

我定义 hidden=128.

features = tf.reshape(features, [-1, n_steps, n_input])具有(?,1,14)单层表壳的形状.

我的数据看起来像这样 x.shape=(594,14), y.shape=(591,1)

我很困惑如何在张量流中堆叠LSTM单元.我的张量流版本是0.14.

Nip*_*hne 11

这是一个非常有趣的问题.最初,我认为两个代码产生相同的输出(堆叠两个LSTM单元).

代码1

cell = tf.contrib.rnn.LSTMCell(hidden, state_is_tuple=True)  
cell = tf.contrib.rnn.MultiRNNCell([cell] * num_layers,state_is_tuple=True)
print(cell) 
Run Code Online (Sandbox Code Playgroud)

代码2

cell = []
for i in range(num_layers):
    cell.append(tf.contrib.rnn.LSTMCell(hidden, state_is_tuple=True))
cell = tf.contrib.rnn.MultiRNNCell(cell,state_is_tuple=True)
print(cell) 
Run Code Online (Sandbox Code Playgroud)

但是,如果在两个实例中打印单元格会产生类似下面的内容,

代码1

[<tensorflow.python.ops.rnn_cell_impl.BasicLSTMCell object at 0x000000000D7084E0>, <tensorflow.python.ops.rnn_cell_impl.BasicLSTMCell object at 0x000000000D7084E0>]
Run Code Online (Sandbox Code Playgroud)

代码2

[<tensorflow.python.ops.rnn_cell_impl.BasicLSTMCell object at 0x000000000D7084E0>, <tensorflow.python.ops.rnn_cell_impl.BasicLSTMCell object at 0x000000000D708B00>]
Run Code Online (Sandbox Code Playgroud)

如果你仔细观察结果,

  • 对于代码1,打印两个LSTM单元对象的列表,一个对象是其他对象的副本(因为两个对象的指针是相同的)
  • 对于代码2,打印两个不同LSTM单元对象的列表(因为两个对象的指针不同).

堆叠两个LSTM单元如下所示,

在此输入图像描述

因此,如果你考虑大局(实际的Tensorflow操作可能会有所不同),它的作用是,

  1. 首先将输入映射到LSTM单元1隐藏单元(在您的情况下为14128).
  2. 其次,将LSTM单元1的隐藏单元映射到LSTM单元2的隐藏单元(在您的情况下为128128).

因此,当您尝试对LSTM单元的同一副本执行上述两个操作时(由于权重矩阵的维度不同),会出现错误.

但是,如果使用隐藏单位数相同的数字输入单位(在您的情况下输入为14且隐藏为14),则没有错误(因为权重矩阵的维数相同),尽管您使用的是相同的LSTM细胞.

因此,如果您考虑堆叠两个LSTM单元,我认为您的第二种方法是正确的.