python-3.x - 从python迭代器填充队列

标签 python-3.x tensorflow

我想创建一个从迭代器填充的队列。然而,在以下 MWE 中,总是将相同的值排入队列:

import tensorflow as tf
import numpy as np

# data
imgs = [np.random.randn(i,i) for i in [2,3,4,5]]

# iterate through data infinitly
def data_iterator():
    while True:
        for img in imgs:
            yield img

it = data_iterator()

# create queue for data
q = tf.FIFOQueue(capacity=5, dtypes=[tf.float64])

# feed next element from iterator
enqueue_op = q.enqueue(list(next(it)))

# setup queue runner
numberOfThreads = 1 
qr = tf.train.QueueRunner(q, [enqueue_op] * numberOfThreads)
tf.train.add_queue_runner(qr) 

# dequeue
dequeue_op  = q.dequeue() 
dequeue_op = tf.Print(dequeue_op, data=[dequeue_op], message="dequeue()")

# We start the session as usual ...
with tf.Session() as sess:
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)

    for i in range(10):
        data = sess.run(dequeue_op)
        print(data)
.
    coord.request_stop()
    coord.join(threads)

我是否必须使用 feed_dict ?如果是,我必须如何将它与 QueueRunner 结合使用?

最佳答案

运行时

enqueue_op = q.enqueue(list(next(it)))

tensorflow 将只执行一次 list(next(it)) 。此后,它将保存第一个列表并将其添加到 q 每次运行 enqueue_op .为避免这种情况,您必须使用占位符。馈送占位符与 tf.train.QueueRunner 不兼容.而是使用这个:
import tensorflow as tf
import numpy as np
import threading

# data
imgs = [np.random.randn(i,i) for i in [2,3,4,5]]

# iterate through data infinitly
def data_iterator():
    while True:
        for img in imgs:
            yield img

it = data_iterator()

# create queue for data
q = tf.FIFOQueue(capacity=5, dtypes=[tf.float64])

# feed next element from iterator

img_p = tf.placeholder(tf.float64, [None, None])
enqueue_op = q.enqueue(img_p)

dequeue_op  = q.dequeue()


with tf.Session() as sess:
    coord = tf.train.Coordinator()

    def enqueue_thread():
        with coord.stop_on_exception():
            while not coord.should_stop():
                sess.run(enqueue_op, feed_dict={img_p: list(next(it))})

    numberOfThreads = 1
    for i in range(numberOfThreads):
      threading.Thread(target=enqueue_thread).start()



    for i in range(3):
        data = sess.run(dequeue_op)
        print(data)

关于python-3.x - 从python迭代器填充队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43231958/

相关文章:

python - 大于 21 个字符的 CPython 字符串 - 内存分配

python - 成员函数装饰器和 self 参数

python - 我使用 TFLiteConvert post_training_quantize=True 但我的模型仍然太大,无法托管在 Firebase ML Kit 的自定义服务器中

python - Tensorflow:恢复图形和模型,然后在单个图像上运行评估

Tensorflow,有没有办法指定沿轴的填充?

python - 深度学习中max运算的逆向过程是什么?

c++ - 如何从 Python 使用 Microsoft MIP SDK?

python - 如何查找列表中句子列表中每个单词的引理和频率计数?

python-3.x - 如何使用boto和python3在CloudFront中使对象无效?

python - 没有名为 pond.tensor 的模块