【问题标题】:PYTHON FLASK app (with KERAS & tensorflow backend) : unable to load model at runtime : 'The Session graph is empty'PYTHON FLASK 应用程序(带有 KERAS 和 tensorflow 后端):无法在运行时加载模型:“会话图为空”
【发布时间】:2019-05-14 19:22:11
【问题描述】:

当直接使用 python 代码(通过 SPYDER 或通过命令提示符)运行时,我有一个运行 KERAS LSTM 模型的 python 代码非常好。

Python(蟒蛇):3.6.7 烧瓶:0.12.3 凯拉斯:2.2.4 张量流:1.10.0

当尝试将其作为 FLASK 应用程序运行时,相同的代码会引发以下错误: 错误:会话图为空。在调用 run() 之前向图中添加操作。

我必须设置会话并设置种子,以便模型结果不会因不同的运行而变化。 我在我的代码中使用了 Kera 文档 (https://keras.io/getting-started/faq/#how-can-i-obtain-reproducible-results-using-keras-during-development) 中的代码,当作为简单的 python 脚本运行时,它运行得非常好。

问题仅在尝试在 Flask 应用程序中运行时出现(这没有意义)。

代码中的错误出现在我尝试从保存的 h5 文件加载模型的那一行。

有人可以帮我解决这个问题吗?

已经阅读了大部分来自 google 和 StackOverflow 的类似问题,但没有一个解决方案。

我还检查了 KERAS 的 github 存储库,自 1 年以来似乎存在与票证相同的问题。 (https://github.com/keras-team/keras/issues/10585)

FLASK 应用代码(app.py):

from flask import Flask, jsonify

from PREDICT import worker

app = Flask(__name__)

@app.route('/api/Model', methods=['GET', 'POST'])
def Model_predict():
    worker()
    return ('Model run')

if __name__ == '__main__':
    app.run(debug=True)

我用来设置 PREDICT.py 中的会话(取自 KERAS 的文档站点)的代码: **

# The below is necessary for starting Numpy generated random numbers in a well-defined initial state.
np.random.seed(42)
# The below is necessary for starting core Python generated random numbers in a well-defined state.
rn.seed(12345)

# Force TensorFlow to use single thread.
# Multiple threads are a potential source of non-reproducible results.
# For further details, see: https://stackoverflow.com/questions/42022950/
session_conf = tf.ConfigProto(intra_op_parallelism_threads=1,
                              inter_op_parallelism_threads=1)
from keras import backend as K
# The below tf.set_random_seed() will make random number generation in the TensorFlow backend have a well-defined initial state.
# For further details, see: https://www.tensorflow.org/api_docs/python/tf/set_random_seed

tf.set_random_seed(1234)

sess = tf.Session(graph=tf.get_default_graph(), config=session_conf)
K.set_session(sess)
**

预期的结果是模型文件应该被正确加载以便以后用于预测。

错误详情:

**
2019-05-15 00:19:19,121 ERROR  : Error at Line : 363
2019-05-15 00:19:19,122 ERROR  : Error : The Session graph is empty.  Add operations to the graph before calling run().
2019-05-15 00:19:19,123 ERROR Stack Trace : 
Traceback (most recent call last):
  File "PREDICT.py", line 363, in worker
    model = loading_model(output_path, weekno, prod)
  File "PREDICT.py", line 104, in loading_model
    m = load_model(model_name)
  File "C:\Users\12345\AppData\Local\Continuum\anaconda3\lib\site-packages\keras\engine\saving.py", line 419, in load_model
    model = _deserialize_model(f, custom_objects, compile)
  File "C:\Users\12345\AppData\Local\Continuum\anaconda3\lib\site-packages\keras\engine\saving.py", line 287, in _deserialize_model
    K.batch_set_value(weight_value_tuples)
  File "C:\Users\12345\AppData\Local\Continuum\anaconda3\lib\site-packages\keras\backend\tensorflow_backend.py", line 2470, in batch_set_value
    get_session().run(assign_ops, feed_dict=feed_dict)
  File "C:\Users\12345\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\client\session.py", line 877, in run
    run_metadata_ptr)
  File "C:\Users\12345\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\client\session.py", line 1025, in _run
    raise RuntimeError('The Session graph is empty.  Add operations to the '
RuntimeError: The Session graph is empty.  Add operations to the graph before calling run().
**

【问题讨论】:

    标签: python-3.x tensorflow flask keras lstm


    【解决方案1】:

    经过彻底的搜索,我发现了这个博客,它帮助我了解了 Flask 和 Keras 是如何协同工作的。

    https://towardsdatascience.com/deploying-keras-deep-learning-models-with-flask-5da4181436a2

    解决方案(如果以后有人需要)是您需要做两件事:

    1. 将图表定义为全局
    global graph
    graph = tf.get_default_graph()
    sess = tf.Session(graph=graph, config=session_conf)
    
    1. 在加载模型和预测之前,将其包裹在一个循环中,以便为每个循环生成一个新图
    with graph.as_default():
    

    注意:如果您收到“ValueError:信号仅在主线程中有效”之类的错误,请检查您的 FLask-SocketIO 包 - 您可能需要卸载并使用最新版本重新安装它。

    【讨论】:

    • 我也面临同样的问题。将模型包装在循环下是什么意思?谢谢
    • @ArthurClerc-Gherardi - 在我的情况下,我必须循环运行每个产品的模型,因此是评论。您可以在没有循环的情况下执行此操作,只需将您的代码包含在上面提到的 WITH 子句中,它应该可以正常工作。
    • 嗯..好的。你有这个项目的开放 github 吗?我想看看整个实现。我坚持对每个 http 请求使用相同的模型。
    猜你喜欢
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 2018-09-26
    • 1970-01-01
    • 1970-01-01
    • 2018-12-19
    相关资源
    最近更新 更多