gpt4 book ai didi

python - 如何使用 tf.while_loop 进行急切执行?

转载 作者:太空宇宙 更新时间:2023-11-04 04:15:21 25 4
gpt4 key购买 nike

在文档中,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

关于python - 如何使用 tf.while_loop 进行急切执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55560676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com