【发布时间】:2021-04-21 00:26:40
【问题描述】:
我正在尝试检查 if 语句中的张量流张量 rand_int=0 是否。在下面的代码中,当rand_int=0时,不执行if语句。
rand_int = tf.random.uniform((), 0, 2, dtype=tf.int32)
if rand_int == 0:
# Lots of lines of code
...
但是,在下面的代码中,执行的是 if 语句。
rand_int = tf.random.uniform((), 0, 2, dtype=tf.int32)
rand_int = tf.Session().run(rand_int)
if rand_int == 0:
...
如果没有tf.Session(),我将如何在第一个块中执行 if 语句?
【问题讨论】:
-
在第一个 sn-p 中,
rand_int是一个Tensor类型的对象,它不等于0或1。这可能就是为什么if的真正分支的内容没有被执行的原因。在第二个 sn-p 中,rand_int被重新定义为session.run()的输出,并且将是0或1。所以,if的真正分支的内容可能以 50% 的概率执行。 -
是的,这是真的。但我想知道是否有办法在 tensorflow 中执行 if 语句,允许第一个 sn-p。
-
有趣。我还没有遇到过这个用例。我认为定义像
one = tf.constant(1, dtype=tf.int32)和zero = tf.constant(0, dtype=tf.int32)这样的张量流常量可能很有用。因为one和zero也是张量,所以is_zero = rand_int == zero也将是张量。但是,我们可能仍然无法按预期执行if is_zero。我们需要tf.cond之类的东西stackoverflow.com/questions/35833011/…
标签: python tensorflow keras tensorflow2.0