如何在TensorFlow中避免每个请求都读取图形

3
我有一个Tensorflow的Python类,通过REST端点调用,并传入图像的URL。每次发起新请求时,它调用 create_graph 方法读取本地的 .pb 文件。该文件不会在每个请求之间更改。因此,我认为在每个请求中都读取该文件不是很好的资源和时间利用。
下面是代码:
import numpy as np
import tensorflow as tf
import urllib2

class MyTensorflow:

  def __init__(self, url):
     self.imageUrl = imageUrl

  def create_graph(self):
    with tf.gfile.FastGFile("/path/to/model.pb", 'rb') as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
        _ = tf.import_graph_def(graph_def, name='')

   def run_inference_on_image(self):
     image_string = urllib2.urlopen(self.imageUrl).read()
     with tf.Session() as sess:
       ...
       ...
       return a_text_value

上述代码是从flask_restful中调用的,如下所示:
c = my_tensorflow.MyTensorflow(args['url'])
    c.create_graph()
    returned = c.run_inference_on_image()

问题

有没有办法只在第一次请求时调用create_graph,然后在服务重新启动之前不再调用它?


before_first_request(f)将一个函数注册为在该应用程序实例的第一个请求之前运行。这有什么问题吗? - metmirr
1个回答

0

关于服务:每个进程只需创建一次会话。您可以多次调用 Session.run()。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接