gpt4 book ai didi

multithreading - 在带有线程的 Flask 应用程序中使用 Keras 模型

转载 作者:行者123 更新时间:2023-12-03 16:00:43 25 4
gpt4 key购买 nike

我有 3 个可用的 Keras 模型,每个模型都用 2 个文件 保存结构.json (保存模型结构)和 weight.h5 .

我已经构建了一个 Flask 应用程序来加载这些模型。但目前我无法像这样将 threading=True 添加到 run() 选项中:

api.run(threaded=True)

所以我只能使用:
api.run()

在这个 flask 应用程序中,我有两个不同的 api(1 GET 和 1 POST)。因为它在一个线程上运行,所以运行速度太慢。我的系统每秒有 100 多个连接,每个连接我都必须加载另一个模型。

请注意,我所有的 keras 模型都具有相同的结构。我只需要加载一个结构,每当有新的连接出现时,我都会为该结构加载重量。

我在 api 中的代码是这样的:
# Compile model
json_file = open(formal_model_path, 'r')
loaded_model_json = json_file.read()
json_file.close()
model = model_from_json(loaded_model_json)
model.compile(loss='mean_absolute_error', optimizer='adam')

@api.route("/predict", methods=["POST"])
try:
model.load_weights(os.path.join(cointainer_folder, 'weight.h5'))
except Exception:
return jsonify(
error_code='model_file_reading_failed'
)

在行 处启用 threading=True 时,我的代码运行出错模型.load_weights[...] .

是否有任何解决方案可以通过加载许多不同的 Keras 模型来构建多线程 API?

最佳答案

我认为您遇到了两个不同的问题:

  • 您正在为每个请求加载模型权重。这是一个坏主意,会使每个请求都非常缓慢。
  • flask 使用多线程。在一个线程中加载的 Tensorflow 模型必须在同一线程中使用。

  • 加载模型的正确位置是 init方法。您还需要使用 tf.get_default_graph()确保您在同一线程中加载模型和预测。

    您的代码可能如下所示
    def init():
    global models
    models = {}
    for idx, model_path in enumerate(model_paths):
    with open(model_path, "r") as fp:
    model = model_from_json(json.load(fp))
    model.compile(loss='mean_absolute_error', optimizer='adam')
    model.load_weights(os.path.join(model_path, "weights.h5"))
    models[idx] = model

    # save default graph in a global var
    global graph
    graph = tf.get_default_graph()

    在您的请求处理程序中
    @api.route("/predict", methods=["POST"])
    def predict():
    # select your model based on something inside the request
    # making up func !
    model = models[func(request)]

    with graph.as_default():
    model.predict(..)

    关于multithreading - 在带有线程的 Flask 应用程序中使用 Keras 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49400440/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com