2

在文档中, tf.while_loop 的主体需要是 python 可调用的。

i = tf.constant(0)
b = lambda i: tf.add(i,1)
c = lambda i: tf.less(i,10)
tf.while_loop(c,b, [i])

有效,但

def b(i):
    tf.add(i,1)

i = tf.constant(0)
c = lambda i: tf.less(i,10)
tf.while_loop(c,b, [i])

抛出 ValueError: Attempt to convert a value (None) with an unsupported type() to a Tensor

在 2.0 中,eager execution 是默认的,我想知道这是什么问题?!

4

1 回答 1

1

您忘记在函数中添加 return 语句:

import tensorflow as tf

def b(i):
    return tf.add(i, 1)

i = tf.constant(0)
c = lambda i: tf.less(i, 10)
tf.while_loop(c, b, [i]) # <tf.Tensor: id=51, shape=(), dtype=int32, numpy=10>

请注意,在您的第一个示例函数b中确实返回增量值:

i = tf.constant(0)
b = lambda i: tf.add(i,1)
c = lambda i: tf.less(i,10)
tf.while_loop(c,b, [i])
print(b(1).numpy()) # 2
于 2019-04-07T16:03:42.127 回答