如何将Keras模型保持加载到内存中并在需要时使用它?

时间:2018-10-22 20:24:19

标签: python node.js keras

我正在阅读Keras blog,该课程教您如何使用Flask创建简单的图像分类器静态API。我想知道如何在不使用python的其他Web框架中实现加载模型的相同方法。 在下面的代码中,将在服务器启动之前将模型加载到内存中,直到服务器处于活动状态,该模型才会运行:

# if this is the main thread of execution first load the model and
# then start the server
if __name__ == "__main__":
    print(("* Loading Keras model and Flask starting server..."
        "please wait until server has fully started"))
    load_model()
    app.run()

我熟悉Pickle,并且知道如何在其他Web框架(例如Node.js的python-shell)中运行python代码。腌制的模型只建立一次,每次需要时都可以加载。但我希望实现与本教程建议的相同的功能,即仅加载一次,并多次使用。创建一个单独的python服务器应用程序来将加载的模型提供给Node.js要求很好吗?

2 个答案:

答案 0 :(得分:0)

您可以使用load_model在Keras中加载模型并传递路径:

from keras.models import load_model
model = load_model('model.hd5')

我已经创建了一个加载Keras模型的Flask API,如果有帮助,可以在这里查看: https://github.com/Ares513/DetectingTrollsApi/blob/master/api.py

答案 1 :(得分:0)

我设法开发了一个python“模型”服务器,其中ML模型被加载到内存中并通过套接字共享。另一方面,消费者应用程序是一个简单的Node.js Web应用程序,可将请求转发到python服务器并检索答复。 您可以在此处找到代码示例:Keras deep api 这是一个使用ResNet50对图像进行分类的图像分类器应用。图像可以通过Node.js应用程序上传,然后传递到python服务器进行分类,然后将结果发送回Node.js应用程序。