Learn practical skills, build real-world projects, and advance your career

Usefulness of Comparison Ops in Pytorch Tensors

In this notebook, I'll introduce and try to explain to the best of my knowledge 5 torch.tensor functions that will enhance your ease of work with Pytorch Tensors.

PyTorch is an opensource Deep Learning Library which consists of a vast variety of data structures and methods that have been helping Deep learning practioners around the world make their work easier and readily available for others to benefit from.

Here are the five functions that I will be describing below with few examples to give you enough experience that you can start using htem in your own deep learning models.

  • torch.eq()
  • torch.max()
  • torch.sort()
  • torch.topk()
  • torch.kthvalue()
# Import torch and other required modules
import torch
import numpy as np

Function 1 - torch.eq(input, other, out=None)

This torch function allows to compute element-wise equality of two broadcastable tensors and returns a tensor of dtype = torch.bool.

# Example 1 
a = torch.tensor([[1., 2, 3, 4], [5, 6, 7, 8]])
b = torch.tensor([[5., 1, 3, 3], [5, 6, 1, 3]])
ans = torch.eq(a, b)
print(ans)
ans.shape
tensor([[False, False, True, False], [ True, True, False, False]])
torch.Size([2, 4])

Both tensors a and b were of the same size, hence the torch.eq() performed an element-wise equality check and returned with a tensor with size (2, 4) same as the tensors above.