python - 在同一个 Python 进程中运行多个 Tensorflow 会话时出错
问题描述
我有一个具有这种层次结构的项目:
project
├── libs
│ ├── __init__.py
│ ├── sub_lib1
│ │ ├── file1.py
│ │ └── __init__.py
│ └── sub_lib2
│ ├── file2.py
│ └── __init__.py
└── main.py
main.py 的内容:
from libs.sub_lib1.file1 import func1
from libs.sub_lib2.file2 import func2
#some code
func1(parameters)
#some code
func2(parameters)
#some code
file1.py 的内容:
#import some packages
import tensorflow as tf
def func1(parameters):
#some code
config = tf.ConfigProto()
config.gpu_options.allow_growth=True
tf.reset_default_graph()
x = tf.placeholder(tf.float32,shape=[None,IMG_SIZE_ALEXNET,IMG_SIZE_ALEXNET,3])
y_true = tf.placeholder(tf.float32,shape=[None,output_classes])
with tf.Session(config=config) as session:
saver.restore(session, "path to the model1")
k = session.run([tf.nn.softmax(y_pred)], feed_dict={x:test_x , hold_prob1:1,hold_prob2:1})
#some code
return(the_results)
file2.py 的内容:
#import some packages
import tensorflow as tf
def func2(parameters):
#some code
config = tf.ConfigProto()
config.gpu_options.allow_growth=True
sess = tf.Session(config=config)
with gfile.GFile('path the model2', 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
sess.graph.as_default()
tf.import_graph_def(graph_def, name='')
sess.run(tf.global_variables_initializer())
#Get the needed tensors
input_img = sess.graph.get_tensor_by_name('Placeholder:0')
output_cls_prob = sess.graph.get_tensor_by_name('Reshape_2:0')
output_box_pred = sess.graph.get_tensor_by_name('rpn_bbox_pred/Reshape_1:0')
#some code to prepare and resize the image
cls_prob, box_pred = sess.run([output_cls_prob, output_box_pred], feed_dict={input_img: blobs['data']})
#some code
return(the_results)
当我运行 main.py 时,出现以下错误:
Traceback (most recent call last):
File "main.py", line 46, in <module>
func2(parameters)
File "/home/hani/opti/libs/sub_lib2/file2.py", line 76, in func2
cls_prob, box_pred = sess.run([output_cls_prob, output_box_pred], feed_dict={input_img: blobs['data']})
File "/home/hani/.virtualenvs/opti/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 929, in run
run_metadata_ptr)
File "/home/hani/.virtualenvs/opti/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1128, in _run
str(subfeed_t.get_shape())))
ValueError: Cannot feed value of shape (1, 600, 863, 3) for Tensor 'Placeholder:0', which has shape '(?, 227, 227, 3)'
经过一些调试,我在第二个模型中没有找到任何具有 (?, 227, 227, 3) 形状的张量。相反,我发现张量 x(由x = tf.placeholder(tf.float32,shape=[None,IMG_SIZE_ALEXNET,IMG_SIZE_ALEXNET,3])
file1 中的 func1 定义)具有 (?, 227, 227, 3) 作为形状。我检查了 input_img 的形状(由input_img = sess.graph.get_tensor_by_name('Placeholder:0')
文件 file2 中的 func2 定义),当我运行 main.py 时发现它(?、227、227、3)。但是,当我运行 file2.py(独立运行python file2.py
)时,我没有收到此错误,并且我发现 input_img 的形状是占位符形状:(?, ?, ?, 3)。
所以我假设两个模型可能具有相同的张量名称(占位符),并且当我在 main.py 中同时导入 file1 和 file2 时,占位符的第一个形状(?、227、227、3)保留在 GPU 内存中。
我session.close()
在file1.py中试过了,但是没有用!
有没有更合适的方法在同一进程中使用多个 Tensorflow 会话而不会混淆它们?或者简单地说,如何在同一个 python 进程中启动另一个会话之前正确关闭一个 Tensorflow 会话?
解决方案
在阅读了 Stack Overflow 中的一些相关帖子后,我在这个答案中找到了一个解决方案,我引用了该解决方案:
由于尝试创建具有相同名称的变量(在您的情况下会发生什么情况),图形正在完成等,您可能会在第二次 build_graph() 期间遇到错误。
为了解决我的问题,我只需要添加tf.reset_default_graph()
到 main.py 以重置图形及其参数。
推荐阅读
- github-api - 如何将降价页面附加到 GitHub Actions 工作流程运行摘要?
- python - 为什么python的日志模块突然停止工作?
- javascript - 从 XML 字符串到动态“列表”输出
- powerbi - 在 PowerBI PBIX 仪表板上嵌入 RTMP 视频流
- regex - ubuntu 中的正则表达式专门排除名为 0 的文件
- c# - 为什么调用 sp_who 的 tsql 存储过程在通过 SqlCommnad 调用时返回的结果与通过 SSMS 不同?
- sql - 关系模式和完整性约束
- mysql - MySQL 在将新的 ENUM 值添加到现有的 ENUM 列时是否获得锁?
- javascript - TypeError:制作狙击命令时无法读取未定义的属性“get”
- swift - 使用列表中的 .onDelete 从 CoreData 关系中删除项目