当TensorFlow 1.X在本地跑没问题,但上了Flask框架就有问题,报错为:
TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("keras_learning_phase:0", shape=(), dtype=bool) is not an element of this graph.
其实是一个TensorFlow自身的BUG,理解:Tensorflow的图Graph是动态的,
- 在Flask服务器中第一次调用,生成的model和各种资源都在一块区域A中。因此不会出错,此时服务器把model保存在区域A中。
- 第二次推导,生成的需要推导的内容因为你没有固定图Graph,所以服务器把他放进了区域B中,这样就导致了需要推导的内容和模型不在一块区域中,即图Graph不一样。
解决方案之一:将Graph固定起来
from xxx import model
import tensorflow as tf
graph = tf.get_default_graph()
@router...
def main():
global graph
with graph.as_default():
model.predict(xxx)