How to Compare two Tensors in PyTorch?

Published January 03, 2022

For various reasons, you may wish to compare two PyTorch sensors. To make these comparisons, we often use the torch.eq() function. This method compares the matching items and returns "True" when they are equal and "False" when they are not.

In this article, we will look at comparing two sensors in PyTorch.

 

How to compare Two PyTorch Sensors

To compare between two PyTorch tensors, just follow the  following steps:

Step 1: Install the required libraries. In this process, we  need to install a torch library

Step 2: Now, create the PyTorch  tensor  and output it

Step 3: Now compute torch.eq(input1, input 2).  It will return a “True” or “False” depending  on the comparison performed

Step 4: Now output the results

 

Example

The following  Program  compares between  two  PyTorch tensors

import torch

a = torch.Tensor([2.4,5.4,-3.44,-5.43,43.5])

b = torch.Tensor([2.4,5.5,-3.44,-5.43, 43])

print("Tensor1:", a)

print("Tensor2:", b)

print(torch.eq(a, b))

 

 

Output:

Tensor1: tensor([ 2.4000, 5.4000, -3.4400, -5.4300, 43.5000])

Tensor2: tensor([ 2.4000, 5.5000, -3.4400, -5.4300, 43.0000])

tensor([ True, False, True, True, False])

 

 

 

Download Source code

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

479 Views