Home > Back-end >  How to compare two tensors of different shapes in one pass at a same time in tensorflow?
How to compare two tensors of different shapes in one pass at a same time in tensorflow?

Time:10-26

>> A = tf.Tensor([4135047. 1193752.], shape=(2,), dtype=float32)
>> B = tf.Tensor(
          [1226019. 4135047. 4135047. 4169911. 1193752. 4135047. 4135047. 4135047.],
          shape=(8,), dtype=float32
       )

>> compare_1 = tf.math.equal(B, A[0])
tf.Tensor([False  True  True False False  True  True  True], shape=(8,), dtype=bool)

>> compare_2 = tf.math.equal(B, A[1])
tf.Tensor([False False False False  True False False False], shape=(8,), dtype=bool)

# final results
>> tf.math.logical_or(compare_1, compare_2)
tf.Tensor([False  True  True False  True  True  True  True], shape=(8,), dtype=bool)

What I want is to compare two tensors of different shape in one pass without using tf.map() function.

More precisely, I would like to compare each element of tensor B with all elements of tensor A. Result should be set to True if any element from tensor A matches with the element that we are comparing from tensor B

Expected outcome:

>> compare(B, A)
tf.Tensor([False  True  True False  True  True  True  True])

# logic:
- 1st element from B, 1226019 doesn't match with any elements of A => False
- 2nd element from B, 4135047 match with an element in A => True
...
...
...

It looks like tf.math.equal can't compare two tensors of different shapes so right now I have to compare it in n-pass (for each element of tensor A) with tensor B and then apply the logical_or() on those results.

CodePudding user response:

To rephrase your question (in a way that I find more understandable), it seems that you want a 1-D tensor with the same length as B, whose elements are True if the corresponding element of B appears in A and false otherwise.

Assuming I've understood correctly, here's one way to get this result. Note that because I replaced logical_or with reduce_any, this approach can be applied arrays A and B of arbitrary length. Note that this only works when A and B are one dimensional arrays.

import tensorflow as tf
A = tf.constant([4135047., 1193752.])
B = tf.constant([1226019., 4135047., 4135047., 4169911., 1193752., 4135047., 4135047., 4135047.])

m = len(A)
n = len(B)
result = tf.math.reduce_any(
    tf.math.equal(
        tf.broadcast_to(A[:,None],[m,n]),tf.broadcast_to(B,[m,n])
    ), axis = 0
)
print(result)

The result:

tf.Tensor([False  True  True False  True  True  True  True], shape=(8,), dtype=bool)

CodePudding user response:

Fundamentally, there's no difference in what it does. But you can have the code a lot cleaner than the other answer.

c = tf.math.reduce_any(B[:, None]==A[None, :], axis=1)

returns,

tf.Tensor([False  True  True False  True  True  True  True], shape=(8,), dtype=bool)
  • Related