[英]Why does the Tensorflow tf.FIFOQueue close early in the following code?
我想实现一个具有队列enqueue
在后台运行dequeue
在主线程中运行。
目标是循环运行优化器,该优化器取决于存储在缓冲区中的值,并且仅随着优化的每个步骤而变化。 这是一个简单的例子来说明:
VarType = tf.int32
data0 = np.array([1.0])
init = tf.placeholder(VarType, [1])
q = tf.FIFOQueue(capacity=1, shapes=[1], dtypes=VarType)
nq_init = q.enqueue(init)
# I use a Variable intermediary because I will want to access the
# data multiple times, but I do not want the next data point in the
# queue until I initialize the variable again.
data_ = tf.Variable(q.dequeue(), trainable=False, collections=[])
# Notice that data_ is accessed twice, but should be the same
# in a single sess.run
# so "data_ = q.dequeue()" would not be correct
# plus there needs to be access to initial data
data1 = data_ + 1
data2 = data_ * data1
qr = tf.train.QueueRunner(q, [q.enqueue(data2)] * 1)
tf.train.add_queue_runner(qr)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
sess.run(nq_init, feed_dict={init:data0})
# this first initialization works fine
sess.run(data_.initializer)
for n in range(10):
print(sess.run(data2))
# this second initialization errors out:
sess.run(data_.initializer)
coord.request_stop()
coord.join(threads)
print('Done')
这段代码出错了,并带有以下错误:
“ OutOfRangeError(请参阅上面的回溯):FIFOQueue'_0_fifo_queue'已关闭并且元素不足(请求的1,当前大小为0)”
为什么,以及如何解决?
因此,我找到了“如何解决”这一部分,但没有找到原因。
似乎第一个入队/出队必须在将第二个入队/出队放入QUEUE_RUNNERS集合中之前运行-但需要说明的是,我们需要两次运行sess.run(data_.initializer)
:
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
sess.run(nq_init, feed_dict={init:data0})
sess.run(data_.initializer)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
for n in range(10):
print(sess.run(data2))
sess.run(data_.initializer)
sess.run(data_.initializer)
coord.request_stop()
coord.join(threads)
输出是预期的:
[2]; [6]; [42];...
没有两次调用,我得到以下信息:
[2]; [6]; [6]; [42];...
我怀疑q.enqueue
有自己的缓冲区,该缓冲区保存旧的data2
,因此必须调用两次。 这也适合于第一个值不重复,因为那时第二个q.enqueue
仍然为空。 不知道如何克服这一怪癖。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.