【问题标题】:How to use tf.while_loop with eager execution?如何在急切执行中使用 tf.while_loop?
【发布时间】:2019-04-07 15:33:15
【问题描述】:

在文档中,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) 转换为张量

2.0默认是eager execution,不知道是什么问题?!

【问题讨论】:

  • 我认为你的b 函数应该return 一些东西。

标签: python tensorflow tensorflow2.0 eager-execution


【解决方案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-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    • 2019-06-23
    • 2019-03-17
    • 1970-01-01
    • 2020-08-28
    相关资源
    最近更新 更多