【问题标题】:Tensorflow: If statement with tensorTensorflow:带有张量的If语句
【发布时间】: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 类型的对象,它不等于 01。这可能就是为什么if 的真正分支的内容没有被执行的原因。在第二个 sn-p 中,rand_int 被重新定义为session.run() 的输出,并且将是01。所以,if 的真正分支的内容可能以 50% 的概率执行。
  • 是的,这是真的。但我想知道是否有办法在 tensorflow 中执行 if 语句,允许第一个 sn-p。
  • 有趣。我还没有遇到过这个用例。我认为定义像one = tf.constant(1, dtype=tf.int32)zero = tf.constant(0, dtype=tf.int32) 这样的张量流常量可能很有用。因为onezero 也是张量,所以is_zero = rand_int == zero 也将是张量。但是,我们可能仍然无法按预期执行if is_zero。我们需要tf.cond 之类的东西stackoverflow.com/questions/35833011/…

标签: python tensorflow keras tensorflow2.0


【解决方案1】:

如果您切换到 TensorFlow (TF) 2.X 版本,您可以避免使用会话。 TF 2 默认使用急切执行,因此您不需要 Session 来执行您的图表。此外,张量的内容在运行时被评估并且可以被访问。 以下代码使用最新稳定的 TF 2.4.0 版本进行测试。

import tensorflow as tf 
rand_int = tf.random.uniform((), 0, 2, dtype=tf.int32)
#rand_int = tf.compat.v1.Session().run(rand_int)
if rand_int == 0:
    print('Inside If Block')

#Output:
Inside If Block

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-27
    • 2016-08-15
    • 2014-10-26
    • 2018-02-20
    • 2018-09-27
    • 1970-01-01
    相关资源
    最近更新 更多