Tensorflow: check if scalar boolean tensor is True

I want to control the execution of a function using a placeholder, but I keep getting the error "Using tf.Tensor as Python bool is not allowed". Here is the code that is causing this error:

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()

      

I changed if c

to if c is not None

with no luck. How can I manage foo

turning the placeholder on and off a

, then?

Update: As @nessuno and @nemo indicate, we should use tf.cond

instead if..else

. The answer to my question is to redesign my function like this:

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() 

      

+3


source to share


3 answers


You should use tf.cond

to define a conditional operation within the graph and thus change the tensor flow.

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)

      



ten

+6


source


The actual execution is not done in Python, but in the TensorFlow backend, which you supply with a graph of the computation that it must execute. This means that every condition and flow control you want to apply must be formulated as a node in the computation graph.

There if

is an operation for conditions cond

:



b = tf.cond(c, 
           lambda: tf.constant(10), 
           lambda: tf.constant(0))

      

+1


source


The simplest way to deal with this is:

In [50]: a = tf.placeholder(tf.bool)                                                                                                                                                                                 

In [51]: is_true = tf.count_nonzero([a])                                                                                                                                                                             

In [52]: sess.run(is_true, {a: True})                                                                                                                                                                                
Out[52]: 1

In [53]: sess.run(is_true, {a: False})
Out[53]: 0

      

0


source







All Articles