Search code examples
luatorch

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

  • Pytorch supports indexing by operators

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

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