How can I run a loop with a tensor as its range? (in tensorflow)

若如初见. 提交于 2019-12-20 09:48:41

问题


I want to have a for loop that the number of its iterations is depend on a tensor value. For example:

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?


回答1:


To do this you will need to use the tensorflow while loop (tf.while_loop) as follows:

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])



回答2:


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.

for in in np.range(...):
  # do something


来源:https://stackoverflow.com/questions/35330117/how-can-i-run-a-loop-with-a-tensor-as-its-range-in-tensorflow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!