Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if two Torch tensors or matrices are equal?

Tags:

torch

lua

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 I use in this script instead of EQUIVALENCE_COMMAND ?

I tried simply with == but it does not work.

like image 770
DavideChicco.it Avatar asked Oct 07 '15 15:10

DavideChicco.it


People also ask

How do you know if two tensors are the same?

We can compare two tensors by using the torch. eq() method. This method compares the corresponding elements of tensors. It has to return rue at each location where both tensors have equal value else it will return false.

How do you check if a variable is a torch tensor?

To check if an object is a tensor or not, we can use the torch. is_tensor() method. It returns True if the input is a tensor; False otherwise.

What is the difference between torch tensor and torch tensor?

torch. Tensor(10) will return an uninitialized FloatTensor with 10 values, while torch. tensor(10) will return a LongTensor containing a single value ( 10 ). I would recommend to use the second approach (lowercase t) or any other factory method instead of creating uninitialized tensors via torch.


2 Answers

torch.eq(a, b) 

eq() implements the == operator comparing each element in a with b (if b is a value) or each element in a with its corresponding element in b (if b is a tensor).


Alternative from @deltheil:

torch.all(tens_a.eq(tens_b)) 
like image 168
yutseho Avatar answered Sep 21 '22 15:09

yutseho


This below solution worked for me:

torch.equal(tensorA, tensorB) 

From the documentation:

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

like image 41
Erik Avatar answered Sep 23 '22 15:09

Erik