How to count numbers of nan in tensor pytorch

how to count numbers of nan in tensor pytorch

I used to use

assert torch.isnan(myTensor.view(-1)).sum().item()==0

to count whether if there is some nan in my tensor. But I found this way inefficient and may be wrong

Is there any better solution? THx :+1:

You can use torch.nonzero(torch.isnan(myTensor.view(-1)), which might be a bit more efficient.

The probably most efficient way to do so should be

assert not torch.isnan(myTensor).any()

as there is no view included (since it isn’t necessary here) , no dimension has to be inferred, and calling any() on a ByteTensor should be quite efficient itself.

2 Likes

I’d say your solution is brilliant

thx for your idea :+1::+1: