关于python和Flask中遇到的问题(不定期更新)

1. Tensor Tensor("dense_1/Softmax:0", shape=(?, 10), dtype=float32) is not an element of this graph

解决:

原因:是因为Tensorflow的运行机制正好和Web有冲突,Tensorflow在后端做预测时是将“图”导入到内存中,之后对图进行计算返回结果,正常情况下这样执行完成之后,程序就Kill掉了,但是由于这里有Web服务,所以那个“图”的计算并没有Kill掉,在第二次执行时,“图”再次被导入计算,由于同时出现了两张一样的“图”,程式就分不清楚哪个是哪个的元素了,于是乎就产生了这样的问题。

解决方法一:

添加代码:将预测程序打包,每次查询的时候使用系统命令直接调用这个程序,获取返回结果。缺点是,每次预测都要重新加载一次模型,时间消耗过大。

解决方法二:

在初始化的时候,加载模型文件和生成graph。

import tensorflow as tf
graph = tf.get_default_graph()
...
...
...
global graph
with graph.as_default():
    # 执行预测函数
    # 如:predictions = model.predict(img, batch_size = 1, verbose = 0)

后来发现用解决方法2解决后的程序可以在tensorflowCPU版本中运行无误,在tensorflowGPU版本中运行会出现:

2. tensorflow.python.framework.errors_impl.FailedPreconditionError: Error while reading resource variable conv_dw_7/depthwise_kernel from Container: localhost. This could mean that the variable was uninitialized. Not found: Container localhost does not exist. (Could not find resource: localhost/conv_dw_7/depthwise_kernel)
     [[{ {node conv_dw_7/depthwise/ReadVariableOp}}]]

解决方法:

global sess
global graph
sess = tf.Session()
graph = tf.get_default_graph()
# 在model加载前添加set_session
set_session(sess)

#加载模型

with graph.as_default():
    set_session(sess)
    # 预测

注意:代码顺序不得改变,不然还是会报错。一天的血泪教训!

猜你喜欢

转载自blog.csdn.net/wwwangzai/article/details/102683059