torch.nan_to_num — PyTorch 2.7 documentation (original) (raw)

torch.nan_to_num(input, nan=0.0, posinf=None, neginf=None, *, out=None) → Tensor

Replaces NaN, positive infinity, and negative infinity values in inputwith the values specified by nan, posinf, and neginf, respectively. By default, NaNs are replaced with zero, positive infinity is replaced with the greatest finite value representable by input’s dtype, and negative infinity is replaced with the least finite value representable by input’s dtype.

Parameters

Keyword Arguments

out (Tensor, optional) – the output tensor.

Example:

x = torch.tensor([float('nan'), float('inf'), -float('inf'), 3.14]) torch.nan_to_num(x) tensor([ 0.0000e+00, 3.4028e+38, -3.4028e+38, 3.1400e+00]) torch.nan_to_num(x, nan=2.0) tensor([ 2.0000e+00, 3.4028e+38, -3.4028e+38, 3.1400e+00]) torch.nan_to_num(x, nan=2.0, posinf=1.0) tensor([ 2.0000e+00, 1.0000e+00, -3.4028e+38, 3.1400e+00])