【发布时间】: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