'Torch tensor set the negative numbers to zero

x=torch.Tensor({1,-1,3,-8})

How to convert x such that all the negative values in x are replaced with zero without using a loop such that the tensor must look like

th>x 1 0 3 0



Solution 1:[1]

Pytorch supports indexing by operators

a = torch.Tensor([1,0,-1])
a[a < 0] = 0
a

tensor([1., 0., 0.])

Solution 2:[2]

Actually, this operation is equivalent to applying ReLU non-linear activation.

Just do this and you're good to go

output = torch.nn.functional.relu(a)

You can also do it in-place for faster computations:

torch.nn.functional.relu(a, inplace=True)

Solution 3:[3]

Pytorch takes care of broadcasting here :

x = torch.max(x,torch.tensor([0.]))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 David Buck