无法保存保存/导出并加载使用急切执行的 keras 模型

数据挖掘 喀拉斯 张量流
2022-03-11 21:16:48

我正在关注 RNN 文本生成教程,几乎每行都急切地执行。我已经用自己的数据集训练了模型,并保存了一个低损失检查点。我能够加载权重并生成文本,但我想导出/保存模型,以便我可以学习如何使用烧瓶部署模型。但是我不知道怎么做。我使用的版本是“1.14.0-rc1”。

教程:https ://www.tensorflow.org/tutorials/sequences/text_generation

我已经能够将模型保存为 HDF5 文件,但我无法加载它。我还禁用了急切执行,但这会导致以后运行代码出现问题。我已经尝试了以下和更多的片段,但也没有任何结果:

new_model = keras.models.load_model("/content/gdrive/My Drive/ColabNotebooks/ckpt4/my_model.h5")

我怎么得到

RuntimeError: tf.placeholder() is not compatible with eager execution.

最后我在另一篇文章中找到了这个并尝试了它,但遇到了另一个错误:

tf.saved_model.save(model, "/content/gdrive/My Drive/Colab Notebooks/ckpt4/my_model.h5")

错误:

AssertionError: Tried to export a function which references untracked object Tensor("StatefulPartitionedCall/args_2:0", shape=(), dtype=resource).TensorFlow objects (e.g. tf.Variable) captured by functions must be tracked by assigning them to an attribute of a tracked object or assigned to an attribute of the main object directly.

1个回答

我遇到了同样的问题,并通过运行 tensorflow 附带的 keras 解决了它:

from tensorflow.python.keras.models import Model, load_model

代替:

from keras.models import Model, load_model

我怀疑这个问题的核心是版本不匹配。使用当前 Tensorflow 2.0.0-beta1 中包含的 Keras 加载模型。