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

Jon*_*n.H 8 hdf5 keras 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])
Run Code Online (Sandbox Code Playgroud)

当我加载模型时,发生了错误。

  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'
Run Code Online (Sandbox Code Playgroud)

如果我使用参数 ' 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')
Run Code Online (Sandbox Code Playgroud)

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

Nic*_*nie 3

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

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

 if load_model_path.endswith('.h5'):
        model = tf.keras.models.load_model(load_model_path)
Run Code Online (Sandbox Code Playgroud)

错误信息:

  File "...../lib/python3.6/site-packages/tensorflow/python/keras/engine/saving.py", line 251, in load_model
    training_config['weighted_metrics'])
KeyError: 'weighted_metrics'
Run Code Online (Sandbox Code Playgroud)

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