Tensorflow使用队列冻结sess.run调用

时间:2017-03-17 11:31:25

标签: python machine-learning tensorflow

我正在测试tensoprflow队列系统,我有一个简单的tensorflow程序,它使用队列来处理输入。示例程序的代码是

import tensorflow as tf
import numpy as np

def model(example_batch):
    dense1 = tf.layers.dense(inputs=example_batch, units=64, activation=tf.nn.relu)
    dense2 = tf.layers.dense(inputs=dense1, units=2)
    return dense2

x_input_data = tf.random_normal([1024, 16], mean=0, stddev=1)
q = tf.FIFOQueue(capacity=1, dtypes=tf.float32, shapes=[1024, 16])

enqueue_op = q.enqueue(x_input_data)
numberOfThreads = 1

qr = tf.train.QueueRunner(q, [enqueue_op] * numberOfThreads)
tf.train.add_queue_runner(qr)
input = q.dequeue()

sess = tf.Session()
sess.run(tf.global_variables_initializer())

# Start input enqueue threads.
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
example_batch = tf.train.batch([input], batch_size=1, num_threads=numberOfThreads, capacity=1, enqueue_many=False)

for step in range(100):
    print ("step")
    #sess.run(input)
    p = sess.run(model(example_batch))

coord.request_stop()
coord.join(threads)
sess.close()

问题是它在第一个p = sess.run(model2layers(example_batch))冻结,它无限期地停在那里。

示例程序有什么问题?

1 个答案:

答案 0 :(得分:2)

问题在于这些行的顺序:

threads = tf.train.start_queue_runners(sess=sess, coord=coord)
example_batch = tf.train.batch([input], batch_size=1, num_threads=numberOfThreads, capacity=1, enqueue_many=False)

第一行调用tf.train.start_queue_runners()来启动后台线程以填充队列。第二行调用tf.train.batch(),它会添加一个新队列,这需要启动一个额外的后台线程来填充该队列,但该线程没有启动,因此程序挂起。

解决方案非常简单:反转两行,以便在tf.train.start_queue_runners()之后调用tf.train.batch()

example_batch = tf.train.batch([input], batch_size=1, num_threads=numberOfThreads, capacity=1, enqueue_many=False)
threads = tf.train.start_queue_runners(sess=sess, coord=coord)