如何运行以张量为范围的循环?(在tensorflow中)

2024-09-27 07:36:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我想要一个for循环,它的迭代次数取决于张量值。例如:

for i in tf.range(input_placeholder[1,1]):
  # do something

但是,我得到以下错误:

“TypeError:”Tensor“对象不可iterable”

我该怎么办?


Tags: 对象inforinputtf错误rangeiterable
2条回答

为此,需要使用tensorflow while循环(^{}),如下所示:

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

TensorFlow Python API函数的返回值类型,包括tf.range^{}Tensor是表示计算的图中节点的符号句柄。通过调用Tensor上的eval方法或将对象传递给Sessionrun方法来执行实际计算。在您的例子中,您可能只想遍历numpyrange

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

相关问题 更多 >

    热门问题