了解random_shuffle_queue何时耗尽元素并关闭它

时间:2017-07-08 21:35:25

标签: python python-3.x tensorflow tensorflow-gpu

我将100032x32x3张图片存储在dummy.tfrecord文件中。我想迭代数据集两次(2个纪元),所以我指定tf.train.string_input_producer([dummy.tfrecord], num_epochs=2)。对于批量大小100,我希望tf.train.shuffle_batch能够运行2 * 10 = 20次迭代,因为10批次100需要耗尽1000张图像。< / p>

我跟着this answer,它按预期产生了20次迭代。但是,最后,我收到了错误:

RandomShuffleQueue '_1_shuffle_batch/random_shuffle_queue' is closed and has insufficient elements (requested 100, current size 0)

这是有道理的,因为队列中留有0个图像。

如何关闭队列并彻底退出?也就是说,不应该有错误。

这是完整的脚本:

import numpy as np
import tensorflow as tf

NUM_IMGS = 1000
tfrecord_file = 'dummy.tfrecord'

def read_from_tfrecord(filenames):
    tfrecord_file_queue = tf.train.string_input_producer(filenames,
            num_epochs=2)
    reader = tf.TFRecordReader()
    _, tfrecord_serialized = reader.read(tfrecord_file_queue)

    tfrecord_features = tf.parse_single_example(tfrecord_serialized,
                        features={
                            'label': tf.FixedLenFeature([], tf.string),
                            'image': tf.FixedLenFeature([], tf.string),
                        }, name='features')

    image = tf.decode_raw(tfrecord_features['image'], tf.uint8)
    image = tf.reshape(image, shape=(32, 32, 3))

    label = tf.cast(tfrecord_features['label'], tf.string)

    #provide batches
    images, labels = tf.train.shuffle_batch([image, label],
            batch_size=100,
            num_threads=4,
            capacity=50,
            min_after_dequeue=1)

    return images, labels 

imgs, lbls = read_from_tfrecord([tfrecord_file])
init_op = tf.group(tf.global_variables_initializer(),
        tf.local_variables_initializer())

with tf.Session() as sess:
    sess.run(init_op)
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)
    while not coord.should_stop():
        labels, images = sess.run([lbls, imgs])
        print(images.shape) #PRINTED 20 TIMES BUT FAILED AT THE 21ST 
    coord.request_stop()
    coord.join(threads)

以下是生成dummy.tfrecord文件的脚本,如果有人想要重现:

def generate_image_binary():
    images = np.random.randint(0,255, size=(NUM_POINTS, 32, 32, 3),
            dtype=np.uint8)
    labels = np.random.randint(0,2, size=(NUM_POINTS, 1))
    return labels, images

def write_to_tfrecord(labels, images, tfrecord_file):
    writer = tf.python_io.TFRecordWriter(tfrecord_file)

    for i in range(NUM_POINTS):
        example = tf.train.Example(features=tf.train.Features(feature={
                    'label':
                    tf.train.Feature(bytes_list=tf.train.BytesList(value=[labels[i].tobytes()])),
                    'image': 
                    tf.train.Feature(bytes_list=tf.train.BytesList(value=[images[i].tobytes()]))
                    }))
        writer.write(example.SerializeToString())
    writer.close()

tfrecord_file = 'dummy.tfrecord'
labels, images= generate_image_binary()
write_to_tfrecord(labels, images, tfrecord_file)

1 个答案:

答案 0 :(得分:0)

Coordinator可以捕获和处理tf.errors.OutOfRangeError之类的异常,用于报告队列已关闭。 您可以更改代码以处理上述异常:

with tf.Session() as sess:
sess.run(init_op)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)  
try:
    while not coord.should_stop():
        labels, images = sess.run([lbls, imgs])
        print(images.shape) #PRINTED 20 TIMES BUT FAILED AT THE 21ST 
except Exception, e:
    # When done, ask the threads to stop.
    coord.request_stop(e)

finally:
    coord.request_stop()
   # Wait for threads to finish.
coord.join(threads)