keras "load_model" 多次加载时时间增加

keras "load_model" time increases when loading it multiple times

我有一个 python rest API(keras),它有 5 个模型文件供 5 个用户使用。当请求到来时会发生以下事情 1.查看用户 2.为该特定用户加载相关模型 3.执行并输出结果

但我的问题是当请求数增加时,执行时间也会增加。 debug output in the console

post请求的代码如下(flask app):

my_path = os.path.abspath(os.path.dirname(__file__))
    model_name = "./"+userName+"/model.h5"
    scaler_name = "./"+userName+"/scaler.sc"
    modelPath = os.path.join(my_path, model_name)
    scalerPath = os.path.join(my_path, scaler_name)

    start_time = time.time()
    # load the model
    model = load_model(modelPath)
    scaler = joblib.load(scalerPath)
    print("--- %s seconds ---" % (time.time() - start_time))
    ............

Keras 不会删除您不再使用的模型,因此仍在使用内存。

您可以尝试 clear_session(),如图 here,或者如果模型相同但权重不同,您可以尝试重新使用您的模型但替换权重。