Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intersection between two tensors of different lengths

Tags:

tensorflow

I have a tensorflow situation. I want to find the intersection of two 2-D tensors which have different shapes.

Example:

object_ids_  [[0 0]
              [0 1]
              [1 1]]

object_ids_more_07_  [[0 0]
                      [0 1]
                      [0 2]
                      [1 0]
                      [1 2]]

The output I am looking for is:

[[0,0], 
 [0,1]]

I came across "tf.sets.set_intersection", tensorflow page: https://www.tensorflow.org/api_docs/python/tf/sets/set_intersection

But couldn't perform it for tensors with different shapes. Another implementation I found is at:

Find the intersection of two tensors. Return the sorted, unique values that are in both of the input tensors

but had a hard time replicating it for 2D tensors.

Any help would be appreciated , thanks

like image 825
Sam Avatar asked Oct 23 '25 18:10

Sam


1 Answers

One way to do is to subtract->abs->sum of all the combinations and then get indices where it matches zero. Can be achieved using broadcasting.

a = tf.constant([[0,0],[0,1],[1,1]])
b = tf.constant([[0, 0],[0, 1],[0,2],[1, 0],[1, 2]])

find_match = tf.reduce_sum(tf.abs(tf.expand_dims(b,0) - tf.expand_dims(a,1)),2)

indices = tf.transpose(tf.where(tf.equal(find_match, tf.zeros_like(find_match))))[0]

out = tf.gather(a, indices)

with tf.Session() as sess:
   print(sess.run(out))
#Output
#[[0 0]
#[0 1]]
like image 153
vijay m Avatar answered Oct 26 '25 11:10

vijay m



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!