tensorflow:检查标量布尔张量是否为True

Tu *_*Bui 4 python boolean-operations tensorflow

我想使用占位符控制函数的执行,但不断收到错误"不允许使用tf.Tensor作为Python bool".以下是产生此错误的代码:

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()
Run Code Online (Sandbox Code Playgroud)

我没有运气就改变if cif c is not None.如何foo通过打开和关闭占位符来控制a呢?

更新:正如@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() 
Run Code Online (Sandbox Code Playgroud)

nes*_*uno 6

您必须使用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)
Run Code Online (Sandbox Code Playgroud)

10

  • 您只需要定义在评估条件时要执行的两个不同函数。唯一的限制是两者必须返回相同数量和类型的值。因此,您可以定义自己的函数并使用它们,而不是 lambda (2认同)