Skip to main content
 首页 » 编程设计

python之如何使用 flask+uwsgi 服务 tensorflow 模型

2025年01月19日28kevingrace

我有一个训练有素的模型,我想用它来预测一些数据并使用 flask + uwsgi 提供它。一切正常,但当我访问服务器时,有时会抛出错误:

File "api.py", line 150, in get_data 
   im = sess.run(image_tf) 
`ValueError: Fetch argument <tf.Tensor 'DecodeJpeg_2:0' shape=(?, ?, 3) dtype=uint8> cannot be interpreted as a Tensor.  
      (Tensor Tensor("DecodeJpeg_2:0", shape=(?, ?, 3), dtype=uint8)  
       is not an element of this graph.)` 

很少有请求可以正常工作,但是 fe 会抛出上述错误。我发现它与 tensorflow session 有关,但我无法弄清楚如何在 flask 中有效地使用它。以下是片段:

config = my_config_pb2.MyConfig() 
with tf.gfile.FastGFile('myconfig.pbtxt', 'r') as f: 
  text_format.Merge(f.read(), config) 
 
sess_config = tf.ConfigProto( 
  log_device_placement=False, 
  allow_soft_placement = True 
) 
 
sess = tf.Session(config=sess_config) 
init_op = tf.global_variables_initializer() 
sess.run(init_op) 
 
def load_model(): 
 
  # Loading model that will be used. 
  tf.saved_model.loader.load(sess,  
      [tf.saved_model.tag_constants.SERVING],config.model_path) 
 
  graph = tf.get_default_graph() 
  input_image = graph.get_tensor_by_name('input_image:0') 
  .... 
  .... 
  params = some parameters 
  return params 
 
def get_data(im,ftype,params): 
  try: 
    img = tf.read_file(im) 
    image_tf = tf.image.decode_jpeg(img, channels=3) 
  except Exception as e: 
    print ("## Got Exception while reading: ", e) 
    return None 
 
  im = sess.run(image_tf) 
  pred = sess.run(....) 
  return pred 
 
params = load_model(sess) 
 
@app.route("/data", methods=['GET', 'POST']) 
def data(): 
  if request.method == 'GET': 
    url = request.args.get('path') 
    print ("##","recieved") 
    if not path: 
        abort(400) 
 
    pred = get_data(image,"url",params) 
    return pred 
 
if __name__ == "__main__": 
 
  app.run(host='0.0.0.0', debug=True, port=8011,use_reloader=False) 

最后,我使用以下方式运行该应用:

`uwsgi --http 0.0.0.0:8011 --wsgi-file api.py --master --processes 4 --threads 2 --callable app --lazy --lazy-apps` 

谁能告诉我我做错了什么?

请您参考如下方法:

原因是 uwsgi fork 进程来运行您的应用程序的多个“副本”。

但是,您在该上下文之外实例化了您的图表。您的可调用对象是 app,因此应该在其中实例化模型。 您可以使用 before_first_request 回调来加载您的模型。

这篇博文可以方便地了解如何设置它: https://networklore.com/start-task-with-flask/

相关 flask 文档:http://flask.pocoo.org/docs/0.12/api/#flask.Flask.before_first_request