【问题标题】:how to save best weights and best model using keras如何使用 keras 保存最佳权重和最佳模型
【发布时间】:2020-09-18 08:45:35
【问题描述】:

专家,我是机器学习新手,我是使用 Keras API 和 TensorFlow 后端来训练机器学习模型。我正在使用模型检查点在 .json 和 .h5 文件中独立保存最佳权重和最佳模型。到目前为止,我尝试编写如下代码,但没有保存任何模型或权重。希望我能得到好的解决方案。在此先感谢。

    filepath1="best_weights.h5"
    filepath2="best_model.json"
    checkpoint = ModelCheckpoint(filepath1, monitor='val_acc', verbose=1, save_best_only=True,  mode='max')
    callbacks_list = [checkpoint]
    history = model.fit_generator(train_generator,steps_per_epoch=nb_train_samples // batch_size, epochs=epochs, validation_data=validation_generator, callbacks=callbacks_list, validation_steps=nb_validation_samples // batch_size, verbose=1)
    

【问题讨论】:

    标签: python tensorflow keras deep-learning autoencoder


    【解决方案1】:

    解决方案 1(在培训结束时):

    您可以尝试在训练结束时使用以下 sn-p 来分别保存权重和模型架构。

    from tensorflow.keras.models import model_from_json
    model_json = model.to_json()
    with open("model.json", "w") as json_file:
        json_file.write(model_json)
    model.save_weights("model.h5")
    

    解决方案 2(在训练期间):

    我们可以观察到模型架构在训练期间没有改变,只有权重。因此,您可以使用此检查点在训练期间仅保存最佳权重,并在训练开始/结束时仅保存model_from_json

    checkpoint = ModelCheckpoint(filepath1, monitor='val_acc', verbose=1,save_best_only=True, save_weights_only=True, mode='max')
    
    ....training runs.....
    ......................
    ....training ends.....
    
    from tensorflow.keras.models import model_from_json
    model_json = model.to_json()
    with open("model.json", "w") as json_file:
        json_file.write(model_json)
    

    如果没有保存任何内容,请确保您拥有正确的filepath1

    【讨论】:

    • @Thanks Timbus ....but there is error lik name model is not defined in the line model_json = model.to_json()
    • 这是因为您将其指向“历史”对象。在您的代码中,将 model.to_json() 替换为 history.to_json()
    • 另外如何知道它保存了最好的权重......是否有任何标准来检查它......
    • 存在 Attributeerror: History object has no attribute 'to_json' while using history.to_json()
    • 请尽量不要返回 history = model.fit_generator() 而只返回 model.fit_generator() 并在之后检查解决方案 1
    猜你喜欢
    • 1970-01-01
    • 2019-06-13
    • 2018-06-25
    • 1970-01-01
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 2018-06-27
    相关资源
    最近更新 更多