【问题标题】:How to save and reload hidden states of Keras encoder-decoder model for inference如何保存和重新加载 Keras 编码器-解码器模型的隐藏状态以进行推理
【发布时间】:2019-08-22 13:58:59
【问题描述】:

我正在使用 Keras 中带有 LSTM 层的编码器解码器架构进行序列文本生成。
我的代码是 Keras LSTM seq2seq 教程的修改版本: https://keras.io/examples/lstm_seq2seq/
训练模型后,我想设置一个推理模式,我可以仅使用预保留模型的隐藏状态来解码序列,而无需每次都重新训练整个模型。 我正在寻找一种方法将这些隐藏的 LSTM 状态保存到文件中,然后重新加载它们以设置我的推理模型。

模型训练部分的一部分如下所示:

encoder = LSTM(latent_dim, return_state=True)
encoder_outputs, state_h, state_c = encoder(encoder_inputs)

稍后我将需要隐藏单元状态和编码器输出(encoder_outputs、state_h 和 state_c)以相同的方式设置推理模型(如教程中所述):

encoder_model = Model(inputs=encoder_inputs,outputs=[encoder_outputs, state_h, state_c])

在有一个程序时重用变量可以正常工作,但是我想将我的代码拆分为训练和推理。然后我需要找到一种方法将隐藏的单元格状态保存到文件中。

到目前为止我尝试过的是

  • 将作为张量的 state_h 和 state_c 直接保存到文件中,但是从张量重新整形为 numpy 数组对我来说不起作用

  • 保存整个 Keras 模型,在推理模式下加载它并通过

  • 提取隐藏的单元格状态
from tensorflow.keras.models import load_model
model.save("current_model.h5")
newmodel = load_model('./current_model.h5', custom_objects={'AttentionLayer': AttentionLayer})

encoder_outputs_2, state_h_2, state_c_2 = newmodel.layers[7].output

以这种方式重新分配变量确实有效,但没有将它们输入推理模型:这给了我错误消息

ValueError: Graph disconnected: cannot obtain value for tensor     Tensor("input_1_2:0", shape=(?, 30), dtype=float32) at layer "input_1". The following previous layers were accessed without issue: []

对我迄今为止尝试过的任何帮助或新方法的想法将不胜感激。干杯!

【问题讨论】:

    标签: python-3.x keras nlp lstm seq2seq


    【解决方案1】:

    解决了这个问题:由于引用了不正确的堆叠 LSTM 层实例而发生 Graph disconnected 错误,应该是 newmodel.layers[6].output

    【讨论】:

      猜你喜欢
      • 2021-08-22
      • 2019-09-11
      • 2019-05-20
      • 2020-09-26
      • 2019-06-14
      • 2018-10-30
      • 2022-01-04
      • 2019-07-25
      • 2019-09-13
      相关资源
      最近更新 更多