在文档中,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:尝试将具有不受支持的 type() 的值 (None) 转换为 Tensor
在2.0中,eager execution是默认的,不知道是什么问题?!
请您参考如下方法:
您忘记在函数中添加 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
