TensorFlow tf.equal() operator doesn't work as expected

13,985

The tf.equal() operator is an elementwise operator. Assuming x and y are the same shape (as they are in your example) tf.equal(x, y) will produce a tensor with the same shape, where each element indicates whether the corresponding elements in x and y are equal. Therefore, sess.run(tf.equal(y, y)) in your program will return the array [True, True, True].

In Python, the is operator computes reference equality between two objects, and the array [True, True, True] is not the same object as the (built-in) object True, so the result of the test is False.

The following program would achieve the behavior you're expecting,* by using the tf.reduce_all() operator on the result of tf.equal() to compute a single boolean value:

y  = tf.constant([0, 1, 0])
all_elems_equal = tf.reduce_all(tf.equal(y, y))

with tf.Session() as sess:
    b = sess.run(all_elems_equal)
    if b:
        print 'true'
    else:
        print 'false'

* Note however that tf.equal(x, y) will broadcast its arguments if they have different shapes, so you might get the unexpected result that two tensors with different shapes are "equal" using this program. For example, using this test on the column vector [[11], [22]] and the row vector [11, 22] would indicate that these are equal. If you also need to compare the shapes in your equality test, you should also compare the result of tf.shape(x) and tf.shape(y).

Share:
13,985

Related videos on Youtube

semenbari
Author by

semenbari

Updated on June 13, 2022

Comments

  • semenbari
    semenbari almost 2 years

    I wrote the following code, but it doesn't work like I expect. I expected that 'true' would be printed, but instead 'false' is printed. Can you explain why this happens?

    import tensorflow as tf
    
    #y_ = tf.constant([0, 1, 0])
    y  = tf.constant([0, 1, 0])
    
    with tf.Session() as sess:
        b = sess.run(tf.equal(y, y))
        if b is True:
            print 'true'
        else:
            print 'false'
    
    • JJJ
      JJJ over 7 years
      I removed the second part of the post – one question per post, and it was off-topic anyway.