'numpy warning with django 4 - 'numpy.float64'> type is zero

I just updated numpy and I get the following warning with Django. How can I fix it?

/usr/local/lib/python3.9/site-packages/numpy/core/getlimits.py:89: UserWarning: The value of the smallest subnormal for <class 'numpy.float64'> type is zero.



Solution 1:[1]

In my case this was some kind of compatability issue between a custom compiled version of opencv and numpy 1.22. The workaround to stop the warnings was the do the following.

import numpy as np

np.finfo(np.dtype("float32"))
np.finfo(np.dtype("float64"))
import cv2

You may find a variation of this will suppress the warnings for you.

I've filed a bug report with numpy but I'm not sure if it's something that's easy to figure out or not. https://github.com/numpy/numpy/issues/20895

Solution 2:[2]

I get the same warning in a virtual environment when using numpy 1.22.1 installed via pip and opencv 4.5.3 compiled from source. Interestingly, using the exact same package versions (installed from conda/conda-forge) in an anaconda environment does not yield the warning.

From the discussion in @Peter's bug report, opencv modifies numpy so that it replaces very small values with zeros. Thus the warning is useful, and may be intended behavior:

OpenCV has the habit of setting the floating point handling to "flush to zero". There is a good reason for wanting to do that: flushing to zero is much faster and all you lose are extremely small values (I had some diffusion simulations once where things would be extremely slow if activity stopped, because the system kept calculating these almost 0 values).

I honestly thought that they had done something about that, we had not had issues opened for a long time ;)... It seems that this is even the case for subnormal == 0 though, flushing the subnormal to zero before the comparison (even though it is returned correctly).

Frankly, giving you a warning here in a sense serves exactly its purpose. That value may not be zero, but it is treated as zero due to cv2 import messing with NumPy. So using the smallest subnormal will be meaningless in many contexts because of that import cv2.

@Peter's solution did not eliminate the numpy warning for me, but downgrading to numpy 1.21 did.

pip install numpy==1.21

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter
Solution 2 RedHand