使用 Keras + Flask 蓝图时容器本地主机不存在错误

Vic*_*one 6 python flask keras

我正在尝试使用 Flask 的蓝图通过 API 提供机器学习模型,这是我的烧瓶__init__.py文件

from flask import Flask

def create_app(test_config=None):
    app = Flask(__name__)

    @app.route("/healthcheck")
    def healthcheck() -> str:
        return "OK"

    # Registers the machine learning blueprint
    from . import ml
    app.register_blueprint(ml.bp)

    return app
Run Code Online (Sandbox Code Playgroud)

ml.py包含/ml端点蓝图的文件

import numpy as np
from . import configuration as cfg
import tensorflow as tf

from flask import (
    Blueprint, flash, request, url_for
)


bp = Blueprint("ml", __name__, url_prefix="/ml")
keras_model = None
graph = None

@bp.before_app_first_request
def load_model():
    print("Loading keras model")
    global keras_model
    global graph
    with open(cfg.config["model"]["path"], 'r') as model_file:
        yaml_model = model_file.read()
        keras_model = tf.keras.models.model_from_yaml(yaml_model)
        graph = tf.get_default_graph()
        keras_model.load_weights(cfg.config["model"]["weights"])

@bp.route('/predict', methods=['POST'])
def predict() -> str:
    global graph
    features = np.array([request.get_json()['features']])
    print(features, len(features), features.shape)
    with graph.as_default():
        prediction = keras_model.predict(features)
    print(prediction)
    return "%.2f" % prediction
Run Code Online (Sandbox Code Playgroud)

我使用命令行脚本运行服务器

#!/bin/bash 

export FLASK_APP=src
export FLASK_ENV=development
flask run
Run Code Online (Sandbox Code Playgroud)

如果我去我应该localhost:5000/healthcheck得到OK响应,当我运行以下 curl

curl -X POST \
  http://localhost:5000/ml/predict \
  -H 'Cache-Control: no-cache' \
  -H 'Content-Type: application/json' \
  -d '{
 "features" : [17.0, 0, 0, 12.0, 1, 0, 0]
}'
Run Code Online (Sandbox Code Playgroud)

第一次,我得到了响应[[1.00]],如果我再次运行它,我会收到以下错误

tensorflow.python.framework.errors_impl.FailedPreconditionError: 
Error while reading resource variable dense/kernel from
Container: localhost. This could mean that the variable was uninitialized. 
Not found: Container localhost does not exist. (Could not find resource: localhost/dense/kernel)
         [[{{node dense/MatMul/ReadVariableOp}}]]
Run Code Online (Sandbox Code Playgroud)

如果我修改蓝图文件,服务器将检测更改并刷新它,我可以再次调用 API,它会为第一次调用返回正确的结果,然后我又回到错误。为什么会发生这种情况?为什么只针对第一个之后的电话?

小智 2

您可以尝试创建对用于加载模型的会话的引用,然后将其设置为 keras 在每个请求中使用。即执行以下操作:

from tensorflow.python.keras.backend import set_session
from tensorflow.python.keras.models import load_model

tf_config = some_custom_config
sess = tf.Session(config=tf_config)
graph = tf.get_default_graph()

# IMPORTANT: models have to be loaded AFTER SETTING THE SESSION for keras! 
# Otherwise, their weights will be unavailable in the threads after the session there has been set
set_session(sess)
model = load_model(...)
Run Code Online (Sandbox Code Playgroud)

然后在每个请求中:

global sess
global graph
with graph.as_default():
    set_session(sess)
    model.predict(...)
Run Code Online (Sandbox Code Playgroud)

  • 这个解决方案对我有用,更确切地说,我想说的是,在加载模型时创建会话,然后通过加载相同的会话进行预测将始终在类似的情况下完成工作。 (2认同)