TensorFlow 2.0:保存并加载包含 LSTM 层的模型,但加载失败并显示 ValueError [英] TensorFlow 2.0: Save and load a model that contains a LSTM layer, while the load commond failed with ValueError

查看:47
本文介绍了TensorFlow 2.0:保存并加载包含 LSTM 层的模型,但加载失败并显示 ValueError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试保存和加载包含 LSTM 层的模型时,加载通用失败,并显示 ValueError:找不到匹配的函数来调用从 SavedModel 加载.

When I was trying to save and load a model that contains a LSTM layer, the load commond failed with ValueError: Could not find matching function to call loaded from the SavedModel.

class RegNet(Model):
    def __init__(self,
             intermediate_dim=50,
             state_dim=9,
             name='RegNet',
             **kwargs):
        super(RegNet, self).__init__()
        self.d1 = Dense(intermediate_dim, activation='relu')
        self.d2 = Dense(state_dim, activation='relu')
        self.h = LSTM(state_dim, activation='sigmoid', return_sequences=True)
        self.o = Dense(state_dim, activation='softmax')

    def call(self, x):
        x = self.d1(x)
        x = self.d2(x)
        x = self.h(x)
        y = self.o(x)
        return y

regNet = RegNet()
...
# Export the model to a SavedModel
regNet.save(regNet_ckpt_dir, save_format='tf')
# Recreate the exact same model
tf.keras.models.load_model(regNet_ckpt_dir)

错误报告:

> ValueError: Could not find matching function to call loaded from the SavedModel. Got:
  Positional arguments (2 total):
    * Tensor("x:0", shape=(None, 1, 20), dtype=float32)
    * Tensor("training:0", shape=(), dtype=bool)
  Keyword arguments: {}

Expected these arguments to match one of the following 4 option(s):

Option 1:
  Positional arguments (2 total):
    * TensorSpec(shape=(None, 1, 20), dtype=tf.float32, name='input_1')
    * False
  Keyword arguments: {}

Option 2:
  Positional arguments (2 total):
    * TensorSpec(shape=(None, 1, 20), dtype=tf.float32, name='x')
    * False
  Keyword arguments: {}

Option 3:
  Positional arguments (2 total):
    * TensorSpec(shape=(None, 1, 20), dtype=tf.float32, name='x')
    * True
  Keyword arguments: {}

Option 4:
  Positional arguments (2 total):
    * TensorSpec(shape=(None, 1, 20), dtype=tf.float32, name='input_1')
    * True
  Keyword arguments: {}

当我评论LSTM层时,加载命令会成功.问题出在哪儿?我们无法在 TensorFlow 2.0 中保存和加载带有 LSTM 层的模型?

推荐答案

万一其他人偶然发现这个问题,这个解决方案对我有用:

In case anyone else stumbles upon this, this solution worked for me:

# Save model
tf.keras.models.save_model(model, "saved_model.hp5", save_format="h5")

# Load model
loaded_model = tf.keras.models.load_model("saved_model.hp5")

不确定为什么model.save(filename)"语法不适用于 LSTM,但我遇到了同样的问题.

Not sure why the "model.save(filename)" syntax doesn't work with LSTM, but I ran into the same issue.

这篇关于TensorFlow 2.0:保存并加载包含 LSTM 层的模型,但加载失败并显示 ValueError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆