I had never seen float('nan')
before! Thanks for the other answer. To add up to it, I wanted to emphasize that there are different versions of NaN
, defined in different packages. For example, pandas
and numpy
have multiple versions. I wanted to verify that they all represent a similar object.
The takeaways are:
- Equality for torch tensors works, but not when they contain
nan
s,
- All
nan
s can be used when checking for closeness of tensors.
- All
nan
s can be used to create torch tensors. They are all compatible.
Here is the experiment:
import torch
import numpy
tensor_float_nan = torch.tensor([(float('nan'))])
tensor_np_nan = torch.tensor([(numpy.nan)])
tensor_np_nan_var = torch.tensor([(numpy.NaN)])
tensor_np_nan_again = torch.tensor([numpy.nan])
>>> print(f"Check if equality works for tensors: "
f"{(torch.tensor([1.]) == torch.tensor([1.])).item()}.")
True
>>> print(f"Check if float nan is the same as itself: "
f"{(tensor_float_nan == tensor_float_nan).item()}.")
False
>>> print(f"Check if float nan is the same as np nan: "
f"{(tensor_float_nan == tensor_np_nan).item()}.")
False
>>> print(f"Check if float nan is the same as np nan var: "
f"{(tensor_float_nan == tensor_np_nan_var).item()}.")
False
>>> print(f"Check if float nan is the same as np nan again: "
f"{(tensor_float_nan == tensor_np_nan_again).item()}.")
False
>>> print(f"Check if np nan is the same as np nan var: "
f"{(tensor_np_nan == tensor_np_nan_var).item()}.")
False
>>> print(f"Check if np nan is the same as np nan again: "
f"{(tensor_np_nan == tensor_np_nan_again).item()}.")
False
>>> print(f"Check if np nan var is the same as np nan again: "
f"{(tensor_np_nan_var == tensor_np_nan_again).item()}.")
False
>>> print(f"Check all close between float nan and np nan: "
f"{torch.allclose(tensor_float_nan, tensor_np_nan, equal_nan=True)}.")
False
>>> print(f"Check all close between float nan and np nan var: "
f"{torch.allclose(tensor_float_nan, tensor_np_nan_var, equal_nan=True)}.")
True
>>> print(f"Check all close between float nan and np nan again: "
f"{torch.allclose(tensor_float_nan, tensor_np_nan_again, equal_nan=True)}.")
True
>>> print(f"Check all close between np nan and np nan var: "
f"{torch.allclose(tensor_np_nan, tensor_np_nan_var, equal_nan=True)}.")
True
>>> print(f"Check all close between np nan and np nan again: "
f"{torch.allclose(tensor_np_nan, tensor_np_nan_again, equal_nan=True)}.")
True
>>> print(f"Check all close between np nan var and np nan again: "
f"{torch.allclose(tensor_np_nan_var, tensor_np_nan_again, equal_nan=True)}.")
True
Nan
, but your code specifically tries to assignNone
. – Bulge