火炬张量将负数设置为零

Torch tensor set the negative numbers to zero

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

如何转换 x 以便在不使用循环的情况下将 x 中的所有负值替换为零,这样张量必须看起来像

th>x 1 0 3 0

Pytorch 支持操作符索引

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

张量([1., 0., 0.])

Pytorch 负责这里的广播:

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

实际上,这个操作相当于应用ReLU非线性激活。

只要这样做就可以了

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

您也可以就地进行以加快计算速度:

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