pythonpytorchtypeerrornantensor

How to assign NaN to tensor element?


I want to assign NaN to a tensor element.

import torch
x = torch.tensor([1, 2, 3])
x[x == 2] = None

I have the error:

TypeError: can't assign a NoneType to a torch.LongTensor

I need it to make sure that some later sophisticated calculations are not made for certain values of x.


Solution

  • The following code will set the desired value to nan:

    import torch
    x = torch.tensor([1, 2, 3]).float()
    x[x == 2] = float('nan')