Catch the moment I get a NaN in my calculations

2019-08-03 02:41发布

问题:

I am running loops with linear regression and got calculations going where I often end up with infinities. When I check the variable output, I note that things crash when I start getting "NaNs". I've tried a lot of different ways of dealing with infinities but my program still ends up crashing. I've done things like replace NaNs with very large or very small values, but now I'm thinking this is all no use. I shouldn't be treating all NaNs equally - apparently some NaNs come about while playing with positive infinities, and some with negative infinities.

I really need to know at WHICH point exactly does my code suddenly produce a NaN, and whether it was a negative infinity that produced it, or a positive one. How can I do this, before the program crashes?

Edit

I know how to check for NaN. I can simply use numpy.isnan, and I have used it. But I want to know when it happens. Isn't there an exception or something that can be called or throw a warning when it happens?

回答1:

If you want to trap a numeric exception using numpy, your best bet is probably to use numpy.seterr:

For example, to raise an exception on invalid operation (leading to NaN):

import numpy as np

np.seterr(invalid='raise')
np.float64(0)/0.

Producing that display on the console:

Traceback (most recent call last):
  File "h.py", line 4, in <module>
    np.float64(0)/0.
FloatingPointError: invalid value encountered in double_scalars