tensorflow.python.framework.errors_impl.InvalidArgumentError: Incompatible shapes: [1,85,85,9] vs. [1,85,85] [Op:GreaterEqual]

Issue

I have a 4 dimensional x matrix. I want to compare the median element of the elements in the x matrix with the elements in the row of the matrix. but i am getting error

x >= x[:,:,:,4]

when i run the above process
tensorflow.python.framework.errors_impl.InvalidArgumentError: Incompatible shapes: [1,85,85,9] vs. [1,85,85] [Op:GreaterEqual]
i am getting the error.

example

print(x[:,0:1.0:1,])

[21.398438 20.5625 20.433594 20.03125 25.220703 25.798828 19.097656 17.792969 21.001953]]]

I want to compare the median element "25.220703" from the sample data above with all the data in this row. and finally
[[[[False False False False True True False False False]]]]

i need to get it. But I am getting the above error

Solution

Instead of taking the 5th element, take a slice with just that element. Then the number of dimensions doesn’t change: the shape of x[:, :, :, 4:5] will be in your case (1, 85, 85, 1), and it can be broadcasted into (1, 85, 85, 9).

x >= x[:, :, :, 4:5]

For example:

x = tf.constant(np.random.randint(0, 9, (1, 2, 2, 9)))

Output:

<tf.Tensor: shape=(1, 2, 2, 9), dtype=int64, numpy=
array([[[[5, 0, 8, 2, 6, 0, 6, 2, 2],
         [1, 4, 3, 5, 4, 0, 3, 1, 3]],

        [[0, 3, 5, 5, 0, 1, 2, 8, 5],
         [8, 5, 0, 1, 8, 7, 7, 8, 1]]]])>

Then:

x >= x[:, :, :, 4:5]

Output:

<tf.Tensor: shape=(1, 2, 2, 9), dtype=bool, numpy=
array([[[[False, False,  True, False,  True, False,  True, False,
          False],
         [False,  True, False,  True,  True, False, False, False,
          False]],

        [[ True,  True,  True,  True,  True,  True,  True,  True,
           True],
         [ True, False, False, False,  True, False, False,  True,
          False]]]])>

The difference between x[:, :, :, 4] and x[:, :, :, 4:5] is just the shape:

x[:, :, :, 4]

Output:

<tf.Tensor: shape=(1, 2, 2), dtype=int64, numpy=
array([[[6, 4],
        [0, 8]]])>

Compare with slice:

x[:, :, :, 4:5]

Output:

<tf.Tensor: shape=(1, 2, 2, 1), dtype=int64, numpy=
array([[[[6],
         [4]],

        [[0],
         [8]]]])>

Answered By – AndrzejO

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published