TensorFlow: lambda use out of session



我正在阅读一段TensorFlow代码(第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)图形和会话关闭后没有抛出错误?

as_default块退出后,GraphSession仍然存在,它们不再是默认值。您可以运行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.

我只是想澄清@Allen和我之间的对话。 Sessionas_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.

相关内容

最新更新