循环张量 [英] Looping over a tensor
问题描述
我正在尝试以类似于以下内容的 Python 方式处理可变大小的张量:
I am trying to process a tensor of variable size, in a python way that would be something like:
# X is of shape [m, n]
for x in X:
process(x)
我尝试使用 tf.scan,问题是我想处理每个子张量,所以我尝试使用嵌套的 scan,但是我可以这样做,因为 tf.scan 与累加器一起工作,如果没有找到,它会将 elems 的第一个条目作为初始值设定项,我不这样做想做.例如,假设我想为张量的每个元素添加一个(这只是一个示例),并且我想逐个元素地处理它.如果我运行下面的代码,我只会将一个添加到子张量,因为 scan 将第一个张量视为初始化器,以及每个子张量的第一个元素.
I have tried to use tf.scan, the thing is that I want to process every sub-tensor, so I have tried to use a nested scan, but I was enable to do it, because tf.scan work with the accumulator, if not found it will take the first entry of the elems as initializer, which I don't want to do. As an example, suppose I want to add one to every element of my tensor (this is just an example), and I want to process it element by element. If I run the code bellow, I will only have one added to a sub-tensor, because scan consider the first tensor as initializer, along with the first element of every sub-tensor.
import numpy as np
import tensorflow as tf
batch_x = np.random.randint(0, 10, size=(5, 10))
x = tf.placeholder(tf.float32, shape=[None, 10])
def inner_loop(x_in):
return tf.scan(lambda _, x_: x_ + 1, x_in)
outer_loop = tf.scan(lambda _, input_: inner_loop(input_), x, back_prop=True)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
rs = sess.run(outer_loop, feed_dict={x: batch_x})
有什么建议吗?
推荐答案
大多数 tensorflow 内置函数都可以按元素应用.因此,您可以将张量传递给函数.喜欢:
Most of tensorflow built-in functions could be applied elementwise. So you could just pass a tensor into a function. Like:
outer_loop = inner_loop(x)
但是,如果您有一些无法以这种方式应用的功能(看到该功能真的很诱人),您可以使用 map_fn
.
However, if you have some function that could not be applied this way (it's really tempting to see that function), you could use map_fn
.
比如说,你的函数只是给张量(或其他)的每个元素加 1:
Say, your function simply adds 1 to every element of a tensor (or whatever):
inputs = tf.placeholder...
def my_elementwise_func(x):
return x + 1
def recursive_map(inputs):
if tf.shape(inputs).ndims > 0:
return tf.map_fn(recursive_map, inputs)
else:
return my_elementwise_func(inputs)
result = recursive_map(inputs)
这篇关于循环张量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!