How to check if two torch or matrix tensors are equal?

I need a Torch command that checks if two tensors have the same content, and returns TRUE if they have the same content.

For example:

local tens_a = torch.Tensor({9,8,7,6}); local tens_b = torch.Tensor({9,8,7,6}); if (tens_a EQUIVALENCE_COMMAND tens_b) then ... end 

What should be used in this script instead of EQUIVALENCE_COMMAND ?

I tried just with == , but that didn't work.

+25
lua torch pytorch
source share
5 answers

https://github.com/torch/torch7/blob/master/doc/maths.md#torcheqa-b

 torch.eq(a, b) 

Executes the operator == comparing each element of b with b (if b is a number) or each element of b with the corresponding element of b.

- UPDATE

by @deltheil

 torch.all(torch.eq(tens_a, tens_b)) 

or even easier

 torch.all(tens_a:eq(tens_b)) 
+30
source share

This solution below works for me:

 torch.equal(tensorA, tensorB) 

From the documentation :

True , if two tensors have the same size and elements, False otherwise.

+14
source share

Try this if you want to ignore the small differences in accuracy that are common to floating

 torch.all(torch.lt(torch.abs(torch.add(tens_a, -tens_b)), 1e-12)) 
+5
source share

For comparing tensors you can do elemental:

torch.eq :

 torch.eq(torch.tensor([[1., 2.], [3., 4.]]), torch.tensor([[1., 1.], [4., 4.]])) tensor([[True, False], [False, True]]) 

Or torch.equal for the whole tensor:

 torch.equal(torch.tensor([[1., 2.], [3, 4.]]), torch.tensor([[1., 1.], [4., 4.]])) # False torch.equal(torch.tensor([[1., 2.], [3., 4.]]), torch.tensor([[1., 2.], [3., 4.]])) # True 

But then you can get lost, because at some point there are small differences that you would like to ignore. For example, floats 1.0 and 1.0000000001 pretty close, and you can assume that they are equal. For such a comparison, you have torch.allclose .

 torch.allclose(torch.tensor([[1., 2.], [3., 4.]]), torch.tensor([[1., 2.000000001], [3., 4.]])) # True 

At some point, it may be important to check how many elements are equal compared to the total number of elements. If you have two tensors dt1 and dt2 , you will get the number of dt1 elements as dt1.nelement()

And with this formula you will get a percentage:

 print(torch.sum(torch.eq(dt1, dt2)).item()/dt1.nelement()) 
+3
source share

This solution also works well for me and seems more natural.

 torch.all(tensorA == tensorB) 

gives a conclusion like:

if the equivalent gives an output like tensor(1, device='cuda:0', dtype=torch.uint8) otherwise: tensor(0, device='cuda:0', dtype=torch.uint8)

0
source share

All Articles