Vimlan.G
Vimlan.G

Reputation: 193

Boolean check is not working Tensorflow

I am trying to perform boolean check

num = tf.placeholder(tf.int32)

in the session section, using feed_dict num is set from 0 to 10

if(num != 0):
   ...perform action...

The above boolean check outputs always true even through num is 0.

Upvotes: 1

Views: 235

Answers (1)

MiniQuark
MiniQuark

Reputation: 48525

A TensorFlow program is composed of two parts: the construction phase and the execution phase:

  • In the construction phase, you build a computation graph. No computation is actually executed in that phase. When you create the placeholder, you are just creating a node in the (default) graph.
  • Then in the execution phase (using a tf.Session()), you run the graph (typically multiple times). The placeholder num itself is just a node in the graph, so it will always be "True". However, if you want to run the graph to compute its value, then you must call num.eval() (or equivalently session.run(num)). When evaluating a node, if it depends (directly or not) on a placeholder, then you must specify that placeholder's value using a feed_dict.

So here is the proper program:

>>> import tensorflow as tf
>>> num = tf.placeholder(tf.int32)
>>> with tf.Session():
...   for val in range(11):
...     if num.eval(feed_dict={num: val}):
...       print(val, "is True")
...     else:
...       print(val, "is False")
... 
0 is False
1 is True
2 is True
3 is True
4 is True
5 is True
6 is True
7 is True
8 is True
9 is True
10 is True

As you can see, everything works as expected, in particular 0 is False and the rest is True.

Edit

If you want to have a condition in the graph itself, you can use tf.cond(), for example:

>>> import tensorflow as tf
>>> num = tf.placeholder(tf.int32)
>>> a = tf.constant(3)
>>> b = tf.constant(5)
>>> calc = tf.cond(num > 0, lambda: a+b, lambda: a*b)
>>> with tf.Session():
...   print(calc.eval(feed_dict={num: +10}))
...   print(calc.eval(feed_dict={num: -10}))
8
15

Upvotes: 2

Related Questions