Count how many elements of one tensor exists in another tensor

I have two tensors:

A = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
B = torch.tensor([2, 5, 6, 8, 12, 15, 16])

The tensors are different in size, random, and not in sequence. I want to get the count of the number of elements of B that (i) exists in A (ii) do not exist in A. So the output will be:

Exists: 4
Do not exist: 3

How to do this efficiently?

1 Like

If your tensors are small and thus memory is not a concern this should work:

A = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
B = torch.tensor([2, 5, 6, 8, 12, 15, 16])

exist = len((A.unsqueeze(1) == B).any(1).nonzero())
not_exist = len(B) - exist

print("exist {}, not exist {}".format(exist, not_exist))
# exist 4, not exist 3
1 Like

@ptrblck Thank you for your help. Unfortunately, the tensors are extremely large, and I have to do this inside a loop. That’s why I need a fast and efficient approach.

Not sure how inefficient is this, but seems to work in this example.

import torch

A = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

B = torch.tensor([2, 5, 6, 8, 12, 15, 16])

# Check if elements of B exist in A

mask = torch.isin(B, A)

# Count the number of elements of B that exist in A

exists = mask.sum().item()

# Count the number of elements of B that do not exist in A

not_exists = (~mask).sum().item()

print(f"Exists: {exists}")

print(f"Do not exist: {not_exists}")

probably @ptrblck easily realises if it’s too bad, or just test.

We use Indexing and Slicing to access the values of a tensor. Indexing is used to access the value of a single element of the tensor, whereasSlicing is used to access the values of a sequence of elements. My Balance Now We use the assignment operator to modify the values of a tensor.

1 Like