Container localhost does not exist error when using Keras + Flask Blueprints

2024/11/15 12:12:35

I am trying to serve a machine learning model via an API using Flask's Blueprints, here is my flask __init__.py file

from flask import Flaskdef create_app(test_config=None):app = Flask(__name__)@app.route("/healthcheck")def healthcheck() -> str:return "OK"# Registers the machine learning blueprintfrom . import mlapp.register_blueprint(ml.bp)return app

The ml.pyfile which contains the blueprint for the /ml endpoint

import numpy as np
from . import configuration as cfg
import tensorflow as tffrom 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_modelglobal graphwith 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 graphfeatures = 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

I run the server using a command line script

#!/bin/bash export FLASK_APP=src
export FLASK_ENV=development
flask run

And if I go to localhost:5000/healthcheckI get the OK response as I should, when I run the following 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]
}'

For the first time, I get the response [[1.00]], if I run it again I get the following error

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}}]]

If I modify the Blueprint file the server will detect the changes and refresh it, I can call the API again and it will return the correct result for the first call and I am back to the error again. Why does this happen? And why only for the calls after the first one?

Answer

You can try creating a reference to the session that is used for loading the models and then to set it to be used by keras in each request. i.e. do the following:

from tensorflow.python.keras.backend import set_session
from tensorflow.python.keras.models import load_modeltf_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(...)

and then in each request:

global sess
global graph
with graph.as_default():set_session(sess)model.predict(...)
https://en.xdnf.cn/q/72123.html

Related Q&A

Serving static files with WSGI and Python 3

What is the simplest way to serve static files with WSGI and Python 3.2? There are some WSGI apps for PEP 333 and Python 2 for this purpose - but was is about PEP 3333 and Python 3? I want to use wsg…

Force INNER JOIN for Django Query

Here is my schema:City PhotographerIm trying to get a list of cities that have at least one photographer, and return the photographer count for the cities.Here is the queryset Im working with:City.obj…

Sklearn Decision Rules for Specific Class in Decision tree

I am creating a decision tree.My data is of the following typeX1 |X2 |X3|.....X50|Y _____________________________________ 1 |5 |7 |.....0 |1 1.5|34 |81|.....0 |1 4 |21 |21|.... 1 |0 65 |34 |23|..…

Cubic hermit spline interpolation python

I would like to calculate a third-degree polynomial that is defined by its function values and derivatives at specified points.https://en.wikipedia.org/wiki/Cubic_Hermite_splineI know of scipys interpo…

Increase Accuracy of float division (python)

Im writing a bit of code in PyCharm, and I want the division to be much more accurate than it currently is (40-50 numbers instead of about 15). How Can I accomplish this?Thanks.

Twitter API libraries for desktop apps?

Im looking for a way to fetch recent posts from twitter. Really I just want to be able to grab and store new posts about a certain topic from twitter in a text file. Are there any current programs or l…

How to generate a PDF from an HTML / CSS (including images) source in Python? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, argum…

Modify subclassed string in place

Ive got the following string subclass:class S(str):def conc(self, next_val, delimiter = ):"""Concatenate values to an existing string"""if not next_val is None:self = sel…

sum numpy ndarray with 3d array along a given axis 1

I have an numpy ndarray with shape (2,3,3),for example:array([[[ 1, 2, 3],[ 4, 5, 6],[12, 34, 90]],[[ 4, 5, 6],[ 2, 5, 6],[ 7, 3, 4]]])I am getting lost in np.sum(above ndarray ,axis=1), why …

Get the number of nonzero elements in a numpy array?

Is it possible to get the length of the nonzero elements in a numpy array without iterating over the array or masking the array. Speed is the main goal of calculating the length.Essentially, something…