【发布时间】:2022-01-17 18:43:51
【问题描述】:
假设我有一个函数,它在输入(给定维度)中接受一个张量,并在输出中返回另一个张量。我想在一批输入上使用该函数,并希望它返回一批输出。所以输入和输出都会多一维。
我可以写一个 tf.while_loop 来对批处理中的所有输入执行我的函数,但我不确定如何在批处理中存储单个元素的输出。
我有一个关于如何做到这一点的想法,它也应该澄清我正在尝试做的事情,但我不确定它是否是最佳的。
batch = tf.random.uniform([4,3,2]) #batch of size 4 of (3,2) shaped tensors
output = tf.zeros([0,5]) #let's say that the output should be a batch of 4 (4,5) shaped tensors.
#I will concatenate the single outputs to this tensor and then reshape it
for i in tf.range(len(batch)):
output = tf.concat((output,MyVeryNiceFunction(batch[i])),0) #MyVeryNiceFunction returns a (4,5) shaped tensor
output = tf.reshape(output,(4,4,5)) #(batch_size,(shape of tensor))
return output
这段代码肯定给出了我想要的输出,但它允许并行循环的每次执行吗? 有一个更好的方法吗?是否有适当的数据结构可以让我存储每个循环执行的输出,然后从中有效地构建输出张量?
【问题讨论】:
标签: python tensorflow