【发布时间】:2018-08-18 18:36:46
【问题描述】:
我正在使用 flask、tensorflow 和 keras 模型构建一个多线程的 rest api。在收到this 错误后,我做了一些研究并提出了以下解决方案:
executor = ThreadPoolExecutor(10)
@app.route('/createLearningTask', methods=['POST'])
def createLearningTask():
request_data = request.get_json(force=True)
executor.submit(LearningTask().processData)
return ('', 200)
基本上,我将每个新的帖子请求提交给执行者。在每个请求中,我使用给定的参数构建模型,生成模型,预测并存储另一个 GET 请求的结果。
class LearningTask:
resultDict = {} # access to this map is protected by locks, which I omitted in here
def processData(self, **kwargs):
graph = tf.Graph() # tf = tensorflow
with graph.as_default():
with tf.Session().as_default():
model = Sequential() # keras model
model.add(..)
model.add(..)
model.add(..)
model.compile(..)
model.fit(..)
model.predict(..)
我省略了代码中不相关的部分。它工作得很好,在处理数据并获得结果后,我将它保存到字典中。我为每个发布请求创建新图表和新会话。
在阅读了this 和this github 的讨论后,我提出了我的解决方案。
我的问题是,该解决方案是否安全且正确地使用 tensorflow?在documentation 中,它说图形不是线程安全的,但我做了一些负载测试,它可以毫无问题地处理同时请求。
【问题讨论】:
-
您在问两个不同的问题。我认为。一是关于Web并发架构。为什么在使用 Keras 时需要
tf.Graph()? Keras 不是thread-safe 吗?如果您担心在 TF 中排队,请考虑使用线程安全队列,例如 PriorityQueue。
标签: python tensorflow flask keras deep-learning