Python 如何以张量为范围运行循环?(在张量流中)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35330117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I run a loop with a tensor as its range? (in tensorflow)
提问by Poorya Pzm
I want to have a for loop that the number of its iterations is depend on a tensor value. For example:
我想要一个 for 循环,它的迭代次数取决于张量值。例如:
for i in tf.range(input_placeholder[1,1]):
# do something
However I get the following error:
但是我收到以下错误:
"TypeError: 'Tensor' object is not iterable"
“类型错误:‘张量’对象不可迭代”
What should I do?
我该怎么办?
回答by keveman
The type of the return value of TensorFlow Python API functions, including tf.range
is a Tensor
. A Tensor
is a symbolic handle to node in a graph that represents computation. You perform the actual computation by calling the eval
method on a Tensor
, or by passing the object to run
method of a Session
. In your case, perhaps what you intended to do was simply iterate over numpy
's range
.
的类型的TensorFlow Python的API函数的返回值的,包括tf.range
是一个Tensor
。ATensor
是表示计算的图中节点的符号句柄。您可以通过调用执行实际的计算eval
上的方法Tensor
,或通过将对象run
的方法Session
。在您的情况下,也许您打算做的只是迭代numpy
's range
。
for in in np.range(...):
# do something
回答by patapouf_ai
To do this you will need to use the tensorflow while loop (tf.while_loop
) as follows:
为此,您需要使用 tensorflow while 循环 ( tf.while_loop
),如下所示:
i = tf.constant(0)
while_condition = lambda i: tf.less(i, input_placeholder[1, 1])
def body(i):
# do something here which you want to do in your loop
# increment i
return [tf.add(i, 1)]
# do the loop:
r = tf.while_loop(while_condition, body, [i])