我正在阅读一段TensorFlow codes(第85-89行)并感到困惑。我做了一些修改来澄清:
with tf.Graph().as_default():
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_memory_fraction)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))
with sess.as_default():
pnet = align.detect_face.create_mtcnn(sess, None)
out = pnet(img_y)
create_mtcnn
定义为:
def create_mtcnn(sess, model_path):
if not model_path:
model_path,_ = os.path.split(os.path.realpath(__file__))
with tf.variable_scope('pnet'):
data = tf.placeholder(tf.float32, (None,None,None,3), 'input')
pnet = PNet({'data':data})
pnet.load(os.path.join(model_path, 'det1.npy'), sess)
pnet_fun = lambda img : sess.run(('pnet/conv4-2/BiasAdd:0', 'pnet/prob1:0'), feed_dict={'pnet/input:0':img})
return pnet_fun
我的问题是,为什么out = pnet(img_y)
因为图表和会话关闭而没有抛出错误?
答案 0 :(得分:0)
Graph
和Session
在as_default
块退出后仍然存在,它们不再是默认值。您可以运行session.close()
来关闭Session
。
>>> import tensorflow as tf
>>> const = tf.constant(3.)
>>> session = tf.Session()
>>> session.run(const)
3.0
>>> session.close()
>>> session.run(const)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py", line 906, in run
run_metadata_ptr)
File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py", line 1064, in _run
raise RuntimeError('Attempted to use a closed Session.')
RuntimeError: Attempted to use a closed Session.
答案 1 :(得分:0)
我只想澄清@Allen和我之间的对话。 Session
后仍然存在as_default
。
import tensorflow as tf
import numpy as np
with tf.Graph().as_default():
const = tf.constant(3.)
sess = tf.Session()
with sess.as_default():
print(sess.run(const))
print(sess.run(const))
sess.close()
print(sess.run(const))
您可以找到结果:
3.0
3.0
-------------------------------------------------------------
RuntimeError Traceback (most recent call last)
...
...
RuntimeError: Attempted to use a closed Session.
您可以通过以下代码重复该错误:
import tensorflow as tf
import numpy as np
with tf.Graph().as_default():
const = tf.constant(3.)
with tf.Session() as sess:
print("No sess run within with block.")
print(sess.run(const))
sess.close()
print(sess.run(const))
相应的结果是:
No sess run within with block.
3.0
-------------------------------------------------------------
RuntimeError Traceback (most recent call last)
...
...
RuntimeError: Attempted to use a closed Session.