gpt4 book ai didi

tensorflow - 无法将 LSTM 与 MultiRNNCell 和dynamic_rnn 堆叠

转载 作者:行者123 更新时间:2023-12-03 01:20:12 25 4
gpt4 key购买 nike

我正在尝试建立一个多元时间序列预测模型。我按照以下教程进行温度预测。 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)

但我有一个错误:

ValueError: Dimensions must be equal, but are 256 and 142 for 'rnn/while/rnn/multi_rnn_cell/cell_0/cell_0/lstm_cell/MatMul_1' (op: 'MatMul') with input shapes: [?,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)

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

我定义hidden=128

features = tf.reshape(features, [-1, n_steps, n_input]) 对于单层情况具有形状 (?,1,14)

我的数据如下所示x.shape=(594,14), y.shape=(591,1)

我很困惑如何在 tensorflow 中堆叠 LSTM 单元。我的 tensorflow 版本是0.14。

最佳答案

这是一个非常有趣的问题。最初,我认为两个代码会产生相同的输出(即堆叠两个 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)

代码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)

但是,如果您在这两种情况下打印单元格,则会产生如下所示的内容,

代码1

[<tensorflow.python.ops.rnn_cell_impl.BasicLSTMCell object at 0x000000000D7084E0>, <tensorflow.python.ops.rnn_cell_impl.BasicLSTMCell object at 0x000000000D7084E0>]

代码2

[<tensorflow.python.ops.rnn_cell_impl.BasicLSTMCell object at 0x000000000D7084E0>, <tensorflow.python.ops.rnn_cell_impl.BasicLSTMCell object at 0x000000000D708B00>]

如果你仔细观察结果,

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

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

enter image description here

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

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

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

但是,如果您使用的隐藏单位数量与输入单位数量相同(在您的情况下,输入为14,隐藏单位为14)尽管您使用相同的 LSTM 单元,但没有错误(因为权重矩阵的维度相同)。

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

关于tensorflow - 无法将 LSTM 与 MultiRNNCell 和dynamic_rnn 堆叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47371608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com