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