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

Exploring PyTorch Tensor functions

Pytorch is Torch based machine learning Python library. It is similar to NumPy but uses advantages of CUDA-capable Nvidia GPUs.

Tensor in pytorch is a multidimensional array containing elements of a single data type.

import torch

Comparison operators

Among lots of function in pytorch there are functions that implement logical comparison operators. In general, these functions take as input a tensor and another tensor or a number. And return a tensor in which each element is 1 or 0 indicating if the comparison for the inputs was True or False.

torch.lt(a, b) - implements < operator comparing each element in a with b (if b is a number) or each element in a with corresponding element in b.

torch.le(a, b) - <= operator

torch.gt(a, b) - > operator

torch.ge(a, b) - >= operator

torch.eq(a, b) - == operator

torch.ne(a, b) - != operator

Tensors must be of the same size or one of size 0

a = torch.tensor([[1., 2, 3], [4, 5, 6], [7, 8 ,9]])
b = 5
print(a)
tensor([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]])
#Comparing matrix with number
torch.lt(a,b)
tensor([[ True,  True,  True],
        [ True, False, False],
        [False, False, False]])