张量不是此图的一个元素; 部署Keras模型

Dat*_*Guy 23 python flask keras tensorflow

我正在部署keras模型并通过烧瓶api将测试数据发送到模型.我有两个文件:

第一:我的烧瓶应用:

# Let's startup the Flask application
app = Flask(__name__)

# Model reload from jSON:
print('Load model...')
json_file = open('models/model_temp.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
keras_model_loaded = model_from_json(loaded_model_json)
print('Model loaded...')

# Weights reloaded from .h5 inside the model
print('Load weights...')
keras_model_loaded.load_weights("models/Model_temp.h5")
print('Weights loaded...')

# URL that we'll use to make predictions using get and post
@app.route('/predict',methods=['GET','POST'])
def predict():
    data = request.get_json(force=True)
    predict_request = [data["month"],data["day"],data["hour"]] 
    predict_request = np.array(predict_request)
    predict_request = predict_request.reshape(1,-1)
    y_hat = keras_model_loaded.predict(predict_request, batch_size=1, verbose=1)
    return jsonify({'prediction': str(y_hat)}) 

if __name__ == "__main__":
    # Choose the port
    port = int(os.environ.get('PORT', 9000))
    # Run locally
    app.run(host='127.0.0.1', port=port)
Run Code Online (Sandbox Code Playgroud)

第二:我用来发送json数据发送到api端点的文件:

response = rq.get('api url has been removed')
data=response.json()
currentDT = datetime.datetime.now()
Month = currentDT.month
Day = currentDT.day
Hour = currentDT.hour

url= "http://127.0.0.1:9000/predict"
post_data = json.dumps({'month': month, 'day': day, 'hour': hour,})
r = rq.post(url,post_data)
Run Code Online (Sandbox Code Playgroud)

我从Flask得到关于Tensorflow的回复:

ValueError:Tensor Tensor("dense_6/BiasAdd:0",shape =(?,1),dtype = float32)不是此图的元素.

我的keras模型是一个简单的6密集层模型,训练没有错误.

有任何想法吗?

Sat*_*jit 28

Flask使用多个线程.您遇到的问题是因为tensorflow模型未加载并在同一个线程中使用.一种解决方法是强制tensorflow使用gloabl默认图.

加载模型后添加此项

global graph
graph = tf.get_default_graph() 
Run Code Online (Sandbox Code Playgroud)

在你的预测中

with graph.as_default():
    y_hat = keras_model_loaded.predict(predict_request, batch_size=1, verbose=1)
Run Code Online (Sandbox Code Playgroud)

  • 我想到了。在上下文管理器中应为with with graph.as_default():`。参见[此处](https://www.tensorflow.org/api_docs/python/tf/get_default_graph) (3认同)

And*_*ouw 12

将您的keras模型包装到一个类中非常简单,并且该类可以跟踪它自己的图和会话。这样可以避免具有多个线程/进程/模型可能导致的问题,而这几乎可以肯定是导致问题的原因。尽管其他解决方案也可以使用,但这是目前为止最通用,可扩展并涵盖所有方面的解决方案。使用这个:

import os
from keras.models import model_from_json
from keras import backend as K
import tensorflow as tf
import logging

logger = logging.getLogger('root')


class NeuralNetwork:
    def __init__(self):
        self.session = tf.Session()
        self.graph = tf.get_default_graph()
        # the folder in which the model and weights are stored
        self.model_folder = os.path.join(os.path.abspath("src"), "static")
        self.model = None
        # for some reason in a flask app the graph/session needs to be used in the init else it hangs on other threads
        with self.graph.as_default():
            with self.session.as_default():
                logging.info("neural network initialised")

    def load(self, file_name=None):
        """
        :param file_name: [model_file_name, weights_file_name]
        :return:
        """
        with self.graph.as_default():
            with self.session.as_default():
                try:
                    model_name = file_name[0]
                    weights_name = file_name[1]

                    if model_name is not None:
                        # load the model
                        json_file_path = os.path.join(self.model_folder, model_name)
                        json_file = open(json_file_path, 'r')
                        loaded_model_json = json_file.read()
                        json_file.close()
                        self.model = model_from_json(loaded_model_json)
                    if weights_name is not None:
                        # load the weights
                        weights_path = os.path.join(self.model_folder, weights_name)
                        self.model.load_weights(weights_path)
                    logging.info("Neural Network loaded: ")
                    logging.info('\t' + "Neural Network model: " + model_name)
                    logging.info('\t' + "Neural Network weights: " + weights_name)
                    return True
                except Exception as e:
                    logging.exception(e)
                    return False

    def predict(self, x):
        with self.graph.as_default():
            with self.session.as_default():
                y = self.model.predict(x)
        return y
Run Code Online (Sandbox Code Playgroud)


小智 5

在加载模型后添加model._make_predict_function() `

# Model reload from jSON:
print('Load model...')
json_file = open('models/model_temp.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
keras_model_loaded = model_from_json(loaded_model_json)
print('Model loaded...')

# Weights reloaded from .h5 inside the model
print('Load weights...')
keras_model_loaded.load_weights("models/Model_temp.h5")
print('Weights loaded...')
keras_model_loaded._make_predict_function()
Run Code Online (Sandbox Code Playgroud)