【问题标题】:tensorflow: check if a scalar boolean tensor is Truetensorflow:检查标量布尔张量是否为真
【发布时间】:2017-04-06 19:14:26
【问题描述】:

我想使用占位符控制函数的执行,但不断收到错误消息“不允许使用 tf.Tensor 作为 Python 布尔值”。以下是产生此错误的代码:

import tensorflow as tf
def foo(c):
  if c:
    print('This is true')
    #heavy code here
    return 10
  else:
    print('This is false')
    #different code here
    return 0

a = tf.placeholder(tf.bool)  #placeholder for a single boolean value
b = foo(a)
sess = tf.InteractiveSession()
res = sess.run(b, feed_dict = {a: True})
sess.close()

我将if c 更改为if c is not None 没有运气。那么如何通过打开和关闭占位符a来控制foo呢?

更新:正如@nessuno 和@nemo 指出的那样,我们必须使用tf.cond 而不是if..else。我的问题的答案是像这样重新设计我的功能:

import tensorflow as tf
def foo(c):
  return tf.cond(c, func1, func2)

a = tf.placeholder(tf.bool)  #placeholder for a single boolean value
b = foo(a)
sess = tf.InteractiveSession()
res = sess.run(b, feed_dict = {a: True})
sess.close() 

【问题讨论】:

    标签: python tensorflow boolean-operations


    【解决方案1】:

    您必须使用tf.cond 在图中定义条件操作并更改张量流。

    import tensorflow as tf
    
    a = tf.placeholder(tf.bool)  #placeholder for a single boolean value
    b = tf.cond(tf.equal(a, tf.constant(True)), lambda: tf.constant(10), lambda: tf.constant(0))
    sess = tf.InteractiveSession()
    res = sess.run(b, feed_dict = {a: True})
    sess.close()
    print(res)
    

    10

    【讨论】:

    • foo 函数在实践中非常复杂。我只想通过打开/关闭a 来更改该功能中的一些操作。如何保留foo 功能?我怀疑问题出在{a: True}if c:
    • 您只需要定义两个不同的函数来在评估条件时执行。唯一的限制是两者必须返回相同数量和类型的值。因此,您可以定义自己的函数并使用它们来代替 lambdas
    【解决方案2】:

    实际执行不是在 Python 中完成,而是在 TensorFlow 后端完成,您提供的计算图应该执行。这意味着您要应用的每个条件和流量控制都必须被表述为计算图中的一个节点。

    对于if 条件,有cond 操作:

    b = tf.cond(c, 
               lambda: tf.constant(10), 
               lambda: tf.constant(0))
    

    【讨论】:

      【解决方案3】:

      更简单的解决方法:

      In [50]: a = tf.placeholder(tf.bool)                                                                                                                                                                                 
      
      In [51]: is_true = tf.count_nonzero([a])                                                                                                                                                                             
      
      In [52]: sess.run(is_true, {a: True})                                                                                                                                                                                
      Out[52]: 1
      
      In [53]: sess.run(is_true, {a: False})
      Out[53]: 0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-31
        • 2019-08-07
        • 1970-01-01
        • 1970-01-01
        • 2016-04-08
        • 1970-01-01
        相关资源
        最近更新 更多