【问题标题】:Using LSTM in Keras and tensorflow for time series predictions在 Keras 和 tensorflow 中使用 LSTM 进行时间序列预测
【发布时间】:2018-03-27 19:22:18
【问题描述】:

我想在 keras 中使用 tensorflow 定义一个 LSTM 层。代码如下:

model = Sequential()
inputs = Input(shape=(time_steps, 1))

cell = tf.nn.rnn_cell.LSTMCell(n_neurons)
multi_cell = tf.nn.rnn_cell.MultiRNNCell([cell] * n_layers)
lstm_outputs, states = tf.nn.dynamic_rnn(multi_cell, inputs, dtype=tf.float32)

outputs = TimeDistributed(Dense(1))(lstm_outputs)

model = Model(inputs=inputs, outputs=outputs)

adam = optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08)
model.compile(loss='mean_squared_error', optimizer=adam)

print(model.summary())

运行时出现错误:

Using TensorFlow backend.
Traceback (most recent call last):
  File "/Users/zhjmdcjk/Desktop/Untitled.py", line 81, in <module>
    model = Model(inputs=inputs, outputs=outputs)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keras/legacy/interfaces.py", line 91, in wrapper
    return func(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keras/engine/topology.py", line 1734, in __init__
    build_map_of_graph(x, finished_nodes, nodes_in_progress)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keras/engine/topology.py", line 1724, in build_map_of_graph
    layer, node_index, tensor_index)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keras/engine/topology.py", line 1695, in build_map_of_graph
    layer, node_index, tensor_index = tensor._keras_history
AttributeError: 'Tensor' object has no attribute '_keras_history'

我不清楚这些,谁能给我一些建议。非常感谢!

【问题讨论】:

    标签: python-3.x tensorflow keras lstm


    【解决方案1】:

    您在 Keras 中使用 Tensorflow 的 LSTM 有什么特别的原因吗?您可以直接使用 Keras LSTM 层。

    inputs = Input(shape=(time_steps, 1))
    
    lstm1 = LSTM(n_neurons, return_sequences=True)(inputs)
    
    lstm_outputs = LSTM(n_neurons, return_sequences=True)(lstm1)
    
    outputs = TimeDistributed(Dense(1))(lstm_outputs)
    
    model = Model(inputs=inputs, outputs=outputs)
    

    此外,对于 Keras 的功能 API,您不需要使用 model = Sequential()。

    【讨论】:

    • 感谢您的回答。我正在做一个关于时间序列预测的项目。序列的长度太长,所以我想把它分成很多部分。为了获得最佳结果,我将使用第 i 部分的最终状态作为第 i+1 部分的初始状态。但我不知道如何保存最终状态并输入 Keras 的下一部分。你有更好的建议吗?
    • 看看this blog。作者已经清楚地解释了在 Keras 中使用 LSTM 进行时间序列预测所涉及的步骤。
    • 对了,如何在 Keras 中定义 LSTM 的初始单元状态和隐藏状态?
    • docs 中提到我们可以使用关键字参数initial_state 并将张量传递给它。您还可以在创建图层时将stateful 参数设置为True
    • 得到它。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2021-11-09
    • 2018-09-04
    • 1970-01-01
    • 2017-10-03
    • 2021-09-15
    • 1970-01-01
    • 2019-12-26
    相关资源
    最近更新 更多