keras - 在 Keras 中加载由 callbakcs.ModelCheckpoint() 保存的模型时出错

标签 keras hdf5 tensorflow-lite

我通过 callbacks.ModelCheckpoint() 自动保存了我的模型使用 HDF5 文件。

# Checkpoint In the /output folder
filepath = "./model/mnist-cnn-best.hd5"

# Keep only a single checkpoint, the best over test accuracy.
checkpoint = keras.callbacks.ModelCheckpoint(filepath, monitor='val_acc', 
                                             verbose=1, save_best_only=True,
                                             mode='max')

# Train
model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test),
          callbacks=[checkpoint])

当我加载模型时,发生了错误。
  model = keras.models.load_model("./mnist-cnn-best.hd5")

  File "D:\Program Files\Anaconda3\lib\site-packages\tensorflow\python\keras\engine\saving.py", line 251, in load_model
    training_config['weighted_metrics'])
KeyError: 'weighted_metrics'

如果我使用参数 'compile=False' 加载模型,它可以正常工作。

我知道在 keras 中保存模型的正常方法是:
from keras.models import load_model

model.save('my_model.h5')  # creates a HDF5 file 'my_model.h5'
del model  # deletes the existing model

# returns a compiled model
# identical to the previous one
model = load_model('my_model.h5')

顺便说一句,当我通过 Tensorflow Lite 转换此模型时,也发生了此错误。
但我不知道我的模型有什么问题。
有没有人有想法?

最佳答案

我遇到了一个类似的问题,它产生了相同的错误消息,但原因可能与您的不同:

代码: (Tensorflow 1.11 和 tf.keras。 版本 :2.1.6-tf)

 if load_model_path.endswith('.h5'):
        model = tf.keras.models.load_model(load_model_path)

错误信息:
  File "...../lib/python3.6/site-packages/tensorflow/python/keras/engine/saving.py", line 251, in load_model
    training_config['weighted_metrics'])
KeyError: 'weighted_metrics'

我发现这是因为模型保存在较旧的 Keras 版本中。
我不得不注释掉与 weighted_metrics 相关的代码能够加载模型。但是,在我找到解决不匹配问题的可持续解决方案之前,这只是一种解决方法。有趣的是,@fchollet刚刚添加 weighted_metrics最近(2018 年 10 月)更新到最新的 Keras 版本。
https://github.com/keras-team/keras/blob/master/keras/engine/saving.py#L136
我希望这会帮助那些和我遇到同样问题的人。

关于keras - 在 Keras 中加载由 callbakcs.ModelCheckpoint() 保存的模型时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52753846/

相关文章:

c++ - HDF5内置并行支持,但未找到特定于MPI的功能

python - 遇到 Unresolved 自定义操作 : TensorListFromTensor. 节点号 4 (TensorListFromTensor) 准备失败

android - android中U2Net模型的使用

tensorflow - 在其他平台(如 Linux)上构建 tensorflow lite

tensorflow - Tensorflow 中的 RNN 与 Keras,tf.nn.dynamic_rnn() 的贬值

python - 是否有相当于 np.nanmean() 的 Keras?

python - 尝试合并两个模型的输入和输出时出现问题

python - 使用keras同时训练两个网络

python - HDF5 在 brew update & upgrade 后出现问题

image - 如何将 {UINT16, 2} 数组保存到 Julia 中的图像