TensorFlow2.5+Flask图像识别站调用Model.predict报图模式不兼容错误求解
错误原因
- TensorFlow 2.x默认开启eager execution,你用原生Keras API保存的.h5模型本身是在eager模式下构建的,和
tf.compat.v1.Session的graph模式是完全不兼容的两套执行机制。 - Flask多线程处理请求的特性会进一步加剧冲突:模型加载在主线程完成,请求处理在子线程执行,跨线程调用graph模式的Session会出现上下文不匹配问题,就算添加
Session.as_default()声明也会和eager模式构建的模型产生冲突。
解决方案
优先推荐适配TF2.x原生逻辑的方案,确实有遗留代码需求再使用兼容方案:
方案1:弃用tf.compat.v1.Session,改用TF2.x原生方式加载模型(最稳定)
完全删除所有和tf.compat.v1.Session相关的代码,直接在Flask应用启动时全局加载模型:
import tensorflow as tf from flask import Flask app = Flask(__name__) # 应用启动时全局加载模型 model = tf.keras.models.load_model("your_model.h5") # 提前编译预测函数,适配Flask多线程场景,避免线程安全问题 model.make_predict_function() @app.route("/predict", methods=["POST"]) def predict_handler(): # 此处省略图片预处理逻辑 img = preprocess_your_image(uploaded_img) # 直接调用predict,不需要套Session上下文 result = model.predict(img[tf.newaxis, ...]) # 后续结果处理逻辑
该方案完全适配TF2.x的执行逻辑,不需要手动管理graph、Session生命周期,稳定性最高。
方案2:保留Session使用场景的兼容方案
如果项目存在大量TF1.x遗留代码必须使用Session,需要全局关闭eager execution,统一模型构建和执行的模式:
import tensorflow as tf # 应用启动前全局关闭eager模式,全程使用graph模式执行 tf.compat.v1.disable_eager_execution() graph = tf.Graph() with graph.as_default(): sess = tf.compat.v1.Session() with sess.as_default(): model = tf.keras.models.load_model("your_model.h5") @app.route("/predict", methods=["POST"]) def predict_handler(): img = preprocess_your_image(uploaded_img) # 调用predict时必须指定和加载阶段完全一致的graph、Session上下文 with graph.as_default(): with sess.as_default(): result = model.predict(img[tf.newaxis, ...])
验证方法
- 加载模型后打印
tf.executing_eagerly(),返回True为eager模式,返回False为graph模式,确保模型构建和predict调用时的执行模式完全一致即可。 - 首次测试可以先在单线程模式启动Flask,添加参数
app.run(threaded=False)排除多线程干扰,验证通过后再开启多线程。
内容的提问来源于stack exchange,提问作者Ram raj
相关产品推荐
相关产品推荐

