假设我已经定义了一个从TfRecords文件加载一个标签/功能对的函数,如下所示
def read_one_image(tfrecords_path):
queue = tf.train.string_input_producer([tfrecords_path])
reader = tf.TFRecordReader()
key, value = reader.read(queue)
features = tf.parse_single_example(value,
features={'label': tf.FixedLenFeature([], tf.int64),
'image': tf.FixedLenFeature([784], tf.int64)})
label = features['label']
image = features['image']
return label, image
如果我保持会话打开,在会话中获取图像可以正常工作:
tf.reset_default_graph()
label, image = read_one_image("mnist_train.tfrecords")
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
tf.train.start_queue_runners(sess=sess)
for i in range(10):
one_label, one_image = sess.run([label, image])
print(one_label, one_image.shape)
但是,如果我使用像这样的上下文管理器
g = tf.Graph()
with g.as_default():
label, image = read_one_image("mnist_train.tfrecords")
with tf.Session(graph=g) as sess:
sess.run(tf.global_variables_initializer())
tf.train.start_queue_runners(sess=sess)
for i in range(10):
one_label, one_image = sess.run([label, image])
print(one_label, one_image.shape)
我收到错误:7 ERROR:tensorflow:Exception in QueueRunner: Attempted to use a closed Session.(784,)
也许我误解了队列运行器是如何工作的,但是因为我调用了sess.run
方法,它应该已经获取了10次数据对。现在,有没有办法退出/退出/关闭会话而不会耗尽队列?
答案 0 :(得分:0)
sess.run(tf.global_variables_initializer())
coord = tf.train.Coordinator()
tf.train.start_queue_runners(sess=sess, coord=coord)