Torch C++: API to check NAN

Viewed 775

I am using libtorch C++. In python version we can easily check the value of a tensor by calling its numpy value, and in numpy we have np.isnan(). I was wondering if there is a built in function in libtorch C++ to check whether a tensor has any NAN value?

Thanks, Afshin

2 Answers

Adding on to Fábio's answer (my reputation is too low to comment):

If you actually want to use the information about NANs in an assert or if condition you need convert it from a torch::Tensor to a C++ bool like so

torch::Tensor myTensor;
// do something
auto tensorIsNan = at::isnan(myTensor).any().item<bool>(); // will be of type bool

Try at::isnan.

int main() {
  torch::Tensor tensor = torch::rand({2, 3});
  std::cout << tensor << std::endl;
  std::cout << at::isnan(tensor) << std::endl;
  return 0;
}

Note: I had to install the nightly build of libtorch since the stable release did not have isnan.

Related