Anubhav Pandey
Anubhav Pandey

Reputation: 1295

How to check if a tensor is present in another tensor?

What I want to do is check if the tensor t1 = [[[1. , 2. , 3.4]]] is present in another tensor t2 = [[[1. , 5. , 3.4], [1. , 2. , 3.4]]]. I tried using tf.equal() for this but it returns this

tf.equal(t2, t1) # Output : [[[True False True] [True True True]]]

What I want is a single bool value (True or False) telling whether t1 is present in t2 or not. Something like

if your_method(t2, t1):
  print("Yes, t1 is contained in t2.")

Is there a completely pythonic way to do this?
Also, I checked it, tf.listdiff() is not supported anymore.

Edit:

Ok, I found a tf.math.reduce_all() method which can be applied to the above output tensor of

[[[True False True] [True True True]]]

to reduce it to a tensor like

[[[True False True]]]

But I still don't know how to obtain the correct answer (which would be a single bool value of True) out of this.
Also if I apply tf.math.reduce_any() to

[[[True False True] [True True True]]]

it can be reduced to

[[[True True True]]]

(again giving me a tensor and not a single bool value) and then if I assume that the answer will be True as all the elements of the resultant tensor are True then this won't be correct as tf.math.reduce_all() also gives a similar result for the case when tf.equal()'s output would have been

[[[True False True] [False True False]]]

that is, if for example t1 = [[[1., 2., 3.4]]] and t2 = [[[1., 5., 3.4], [6., 2., 7.8]]].
Hope this helps.

Upvotes: 3

Views: 6956

Answers (1)

Mitiku
Mitiku

Reputation: 5412

There are two options you have.

  1. Using numpy

First evaluate the tensors to get numpy arrays for respective tensors and use in operator.

t1_array = t1.eval()
t2_array = t2.eval()
t1_array in t2_array # this will be true if t2 contians t1.

2. Using tensorflow equal, reduce_any and reduce_all methods.

# check equality of array in t1 for each array in t2 element by element. This is possible because the equal function supports broadcasting. 
equal =  tf.math.equal(t1, t2)
# checking if all elements from  t1 match for all elements of some array in t2
equal_all = tf.reduce_all(equal, axis=2)
contains = tf.reduce_any(equal_all)

Edit

If eager execution is enabled

contains = t1.numpy() in t2.numpy() # this will be true if t2 contians t1.

Upvotes: 2

Related Questions