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

我想使用占位符控制函数的执行,但不断收到错误“不允许使用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()

我改变了,如果c,如果c不是没有运气没有.如何通过打开和关闭占位符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() 

最佳答案 您必须使用
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

点赞