Reputation: 115
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
Upvotes: 7
Views: 24127
Reputation: 5150
Pytorch supports indexing by operators
a = torch.Tensor([1,0,-1])
a[a < 0] = 0
a
tensor([1., 0., 0.])
Upvotes: 7
Reputation: 24701
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)
Upvotes: 7
Reputation: 61
Pytorch takes care of broadcasting here :
x = torch.max(x,torch.tensor([0.]))
Upvotes: 6