Confusing output of Logical AND with two binary tensors in Tensorflow

375 Views Asked by At

I have two binary tensors in tensorflow. I want to convert both of them to boolean tensors (element-wise) and basically get an "intersection", a logical AND. However something seems to go wrong in the conversion to boolean, as well as in the logical_and part. What do I do wrong?

sess = tf.InteractiveSession()
x = tf.random_uniform([1, 10], dtype=tf.int32, maxval=2))
y = tf.random_uniform([1, 10], dtype=tf.int32, maxval=2))
print(x.eval())
print(y.eval())
x = tf.cast(x, tf.bool)
y = tf.cast(y, tf.bool)
print(x.eval())
print(y.eval())
intersect = tf.logical_and(x, y)
print(intersect.eval())

This produces the following ouptut:

[[0 0 1 1 0 1 0 0 1 1]]
[[0 1 0 0 1 0 1 0 0 1]]
[[False  True  True  True  True False False  True  True  True]]
[[False  True  True  True  True  True  True False  True  True]]
[[False False  True  True False False False False False  True]]
1

There are 1 best solutions below

0
On BEST ANSWER

tf.random_normal generates a new random tensor every time intersect is evaluated.

Try this:

sess = tf.Session()
x = tf.random_uniform([1, 10], dtype=tf.int32, maxval=2)
sess.run([x, tf.cast(x, tf.bool)])

Output:

[array([[0, 1, 0, 0, 0, 0, 0, 0, 1, 1]], dtype=int32), 
 array([[False,  True, False, False, False, False, False, False,  True,
     True]])]

So if you run both the ops at the same time, you'll get the same output. Consider storing x and y as tf.constant