首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >了解random_shuffle_queue何时耗尽元素并关闭它

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

Stack Overflow用户
提问于 2017-07-08 21:35:24
回答 1查看 284关注 0票数 0

我有1000图像,大小为32x32x3,存储在dummy.tfrecord文件中。我希望对数据集进行两次迭代(2期),因此我指定了tf.train.string_input_producer([dummy.tfrecord], num_epochs=2)。对于批处理大小的100,我希望tf.train.shuffle_batch运行2 * 10 = 20迭代,因为需要10批的100才能耗尽1000映像。

我跟踪了this answer,它确实产生了预期的20迭代。但是,最后,我收到了错误:

代码语言:javascript
复制
RandomShuffleQueue '_1_shuffle_batch/random_shuffle_queue' is closed and has insufficient elements (requested 100, current size 0)

这是有意义的,因为队列中保留了0图像。

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

下面是完整的脚本:

代码语言:javascript
复制
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文件的脚本,如果有人想要复制的话:

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-08 22:04:07

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

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44990939

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档