How to set 'Inf' in Tensor (Variable) to 0?

Hi all,

How to set ‘Inf’ in Tensor to 0?
I don’t wish to use numpy since that require to set backward when using it in Networks.

Thanks,
Qinqing

x = torch.Tensor([1, float("Inf"), 2, float("Inf")])
x[x == float("Inf")] = 0
x  # should be 1, 0, 2, 0 now
7 Likes

Thanks for the answer! May I know if the masked entry will affect the gradient? For example, if I have a model whose intermediate layer gives an output of:

out = [inf, -3.4, inf, -5.5]

where the inf entries should be masked out, can I do it by:

out[out == float('inf')] = 0

Thanks!