I. *_*. A 6 for-loop tensorflow
我有以下功能:
import random
lst = []
for i in range(100):
lst.append(random.randint(1, 10))
print(lst)
buffer = []
# This is the peace of code which I am interested to convert into tensorflow.
for a in lst:
buffer.append(a)
if len(buffer) > 5:
buffer.pop(0)
if len(buffer) == 5:
print(buffer)
Run Code Online (Sandbox Code Playgroud)
所以,从代码中,我需要创建一个缓冲区(可能是张量流中的变量).此缓冲区应保留最后提取的要素conv layer.在我的案例中,这variable将是一个输入RNN.
这种方法的优点是,当我们有大图像时,以及当我们需要用一个RNN提供RNN时(batch of images) * (sequence length) * (size of 1 image),这将需要将大量图像加载到主存储器中.另一方面,根据上面的代码,我们将使用Datasetsfrom张量流或一个input queue或任何其他替代方案一次馈送1个图像.因此,我们将在内存中存储大小的特征:batch_size * sequence_length * feature space.此外,我们可以说:
if len(buffer) == n:
# empty out the buffer after using its elements
buffer = [] # Or any other alternative way
Run Code Online (Sandbox Code Playgroud)
我知道我可以提供我batches的图像网络,但我需要根据一些文献完成上述代码.
任何帮助深表感谢!!
我尝试使用tf.FIFOQueue(https://www.tensorflow.org/api_docs/python/tf/FIFOQueue)重新生成您的输出。我在下面给出了我的代码,并在必要时添加了注释。
BATCH_SIZE = 20
lst = []
for i in range(BATCH_SIZE):
lst.append(random.randint(1, 10))
print(lst)
curr_data = np.reshape(lst, (BATCH_SIZE, 1)) # reshape the tensor so that [BATCH_SIZE 1]
# queue starts here
queue_input_data = tf.placeholder(tf.int32, shape=[1]) # Placeholder for feed the data
queue = tf.FIFOQueue(capacity=50, dtypes=[tf.int32], shapes=[1]) # Queue define here
enqueue_op = queue.enqueue([queue_input_data]) # enqueue operation
len_op = queue.size() # chek the queue size
#check the length of the queue and dequeue one if greater than 5
dequeue_one = tf.cond(tf.greater(len_op, 5), lambda: queue.dequeue(), lambda: 0)
#check the length of the queue and dequeue five elemts if equals to 5
dequeue_many = tf.cond(tf.equal(len_op, 5), lambda:queue.dequeue_many(5), lambda: 0)
with tf.Session() as session:
for i in range(BATCH_SIZE):
_ = session.run(enqueue_op, feed_dict={queue_input_data: curr_data[i]}) # enqueue one element each ietaration
len = session.run(len_op) # check the legth of the queue
print(len)
element = session.run(dequeue_one) # dequeue the first element
print(element)
Run Code Online (Sandbox Code Playgroud)
但是,上述代码存在以下两个问题:
只有出列一个和出列许多操作可用,并且您看不到队列内的元素(我认为您不需要这个,因为您看起来像管道)。
我认为tf.cond是实现条件操作的唯一方法(我找不到任何其他类似的合适函数)。然而,由于它类似于if-then-else 语句,因此当语句为 false 时也必须定义一个操作(不仅仅是只有if 语句而没有else)。由于Tensorflow就是构建一个图,我认为有必要包含两个分支(当条件为 true 和 false 时)。
此外,可以在这里找到有关 Tensorflow输入管道的详细解释( http://ischlag.github.io/2016/11/07/tensorflow-input-pipeline-for-large-datasets/)。
希望这可以帮助。
| 归档时间: |
|
| 查看次数: |
409 次 |
| 最近记录: |