What Does the "Greater Than" Operator ">" Mean for Pytorch Tensors?

I have a tensor it defined as:

import torch
it = torch.tensor([0,  0,  0,  0,  0,  0,  0,  0,  0,  0], device='cuda:0')

Given this definition, what does it > 0 then mean?

1

2 Answers

Using the > operator is the same as using the torch.gt() function.

In other words,

it > 0

is the same as

torch.gt(it, 0)

and it returns a ByteTensor (a Boolean tensor) of the same shape as it where out[i] is True if it[i] > 0 and False otherwise.

As seen from the question it is a 1-d tensor consisting of 10 elements. When we write it > 0 each element of the tensor it is compared with 0 and the output is set as True or False depending upon whether the number is greater than 0 or not. The result is also a 1-d boolean tensor consisting of True and False values. In your case, you will get a 1-d tensor like this: [False, False, False, False, False, False, False, False, False, False,] as none of the elements in it is equal to 0.

In more simpler terms,

If result is a variable (actually a 1-d tenosr) to store the output having the same shape as it then the equation result= it > 0 can be written as:

if it[i]>0:
    result[i]= True
else:
    result[i]= False 

But when it's performed as result= it > 0, the execution is much faster than writing our own for/while loop.

Hope this helps you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest