How to compare two tensors in PyTorch?
Last Updated :
21 Feb, 2022
In this article, we are going to see how we can compare two tensors in Pytorch.
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.
torch.eq() function:
Syntax: torch.eq( First_tensor, Second_tensor, out=None )
Parameters: torch.eq() accept tensors that are we want to compare as parameters.
Return: It return a boolean value. true if tensors are equals else it will return false.
Example 1:
In this example, we are comparing two 1-D tensors using the torch.eq() function in the python programming language .
Python3
import torch
first = torch.Tensor([ 4.4 , 2.4 , - 9.1 ,
- 5.31 , 5.3 ])
second = torch.Tensor([ 4.4 , 5.5 , - 9.1 ,
- 5.31 , 43 ])
print ( "First Tensor:" , first)
print ( "Second Tensor:" , second)
print (torch.eq(first, second))
|
Output:
Example 2:
Under this example, we are comparing 2D tensors PyTorch using the torch.eq() function.
Python3
import torch
first = torch.Tensor([[ 7 , - 2 , 3 ],
[ 29 , 9 , - 5 ],
[ 2 , - 8 , 34 ],
[ 24 , 62 , 98 ]])
second = torch.Tensor([[ 7 , - 5 , 3 ],
[ 26 , 9 , - 4 ],
[ 3 , - 8 , 43 ],
[ 23 , - 62 , 98 ]])
print ( "First Tensor:" , first)
print ( "Second Tensor:\n" , second)
print ( "After Comparing Both Tensors" )
print (torch.eq(first, second))
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...