images, labels = tf.train.batch([image, label], batch_size=32, num_threads=4)
我经常看到使用num_threads
创建的队列,并且据说这些线程用于入队操作。我不太明白设置多线程入队的目的,因为在我看来,入队只是将一个值放在队列末尾。
来自Threading and Queues tutorial :
For example, a typical input architecture is to use a RandomShuffleQueue
to prepare inputs for training a model:
- Multiple threads prepare training examples and push them in the queue.
- A training thread executes a training op that dequeues mini-batches from the queue.
The TensorFlow Session object is multithreaded, so multiple threads can easily use the same session and run ops in parallel.
这个想法是,数据管道通常是 I/O 密集型的:数据可以从磁盘获取,甚至可以从网络流式传输。 GPU 很可能不会成为计算瓶颈,仅仅是因为数据的传输速度不够快,无法使其饱和。
多线程读取解决了这个问题:当一个线程正在等待 I/O 任务时,另一个线程已经有一些数据可供 GPU 使用。处理此数据时,第一个线程有望接收并准备其批处理,依此类推。这就是为什么tf.train.batch
、tf.train.shuffle_batch
等函数支持多线程数据处理。设置num_threads = 1
使批处理具有确定性,但如果有多个线程,则无法保证队列中数据的顺序。
我是一名优秀的程序员,十分优秀!