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 c
了if 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)
您必须使用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
归档时间: |
|
查看次数: |
13771 次 |
最近记录: |