【问题标题】:How to save a trained model in Keras to use it in an application?如何在 Keras 中保存经过训练的模型以在应用程序中使用它?
【发布时间】:2019-01-08 17:45:03
【问题描述】:

我在 Keras 中训练了一个模型,并以不同的方式保存它:

model.save("filename")

model.to_json()  
model.save_weights("filename")

但是当我将训练好的模型加载到另一个程序中进行预测时,我得到的结果与测试结果大不相同。

为什么会发生这种情况,我该如何处理?

【问题讨论】:

  • 哦,我已经通过将模型保存为“.yaml”文件而不是“.json”来解决它。然后,加载权重并编译它。

标签: python tensorflow machine-learning keras machine-learning-model


【解决方案1】:

另存为:

     model.save('model.h5')
     model_json = model.to_json()
     with open("model.json", "w") as json_file:
         json_file.write(model_json)

然后为了有效地将其加载到应用程序中,将其设置为全局如下,这样它就不会一次又一次地加载:

    def load_model():

        global model

        json_file = open('model.json', 'r')
        model_json = json_file.read()
        model = model_from_json(model_json)
        model.load_weights("model.h5")
        model._make_predict_function()

【讨论】:

    【解决方案2】:

    您可以尝试将模型保存为 .h5 格式

    from keras.models import model_from_json   
    # serialize model to JSON
    model_json = parallel_model.to_json()
    with open("model.json", "w") as json_file:
        json_file.write(model_json)
    # serialize weights to HDF5
    model.save_weights("model.h5")
    print("Saved model to disk")
    

    【讨论】:

      【解决方案3】:

      另外,你可以这样做

      保存模型

       model.save('clasification_model.h5')
      

      读取模型

      from keras.models import load_model
      classifier = load_model('clasification_model.h5')
      

      预测

      res = classifier.predict_classes(x, batch_size=32, verbose=1)
      

      classifier.predict_classes vs classifier.predict

      keras Sequential model API

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-04
        • 1970-01-01
        • 1970-01-01
        • 2020-02-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多