Repository navigation
Description
Describe the bug
We have a custom estimator class that inherits from sklearn.base.BaseEstimator and RegressorMixin. We run automated unit tests in Azure DevOps pipelines on both Windows Server 2022 and Ubuntu 22.04.1. All the tests pass on Windows. On Python 3.12.6 in Linux the test with the stacktrace shown below fails with:
RuntimeWarning: invalid value encountered in cast
This causes the test and hence build to fail because we set PYTHONWARNINGS=error before running the tests. On Python 3.11.10 in Linux this test actually passes; but a different test using the same custom estimator fails with an identical stacktrace. And yet this latter test passes on Python 3.12 in Linux!
Note this change in numpy 1.24.0: https://numpy.org/doc/stable/release/1.24.0-notes.html#numpy-now-gives-floating-point-errors-in-casts; especially this bit:
The precise behavior is subject to the C99 standard and its implementation in both software and hardware.
I can probably work around this error in our tests by using a numpy.errstate context manager, but could there be a bug in sklearn?
I don't know if this issue is related to #25319. AFAIK the test data has no nan values; the feature data columns are all float64.
Steps/Code to Reproduce
Sorry, this is proprietary code which I didn't write and don't understand!
Expected Results
The call to fit() succeeds without throwing a RuntimeWarning.
Actual Results
Stacktrace from Python 3.12.6 x64 on Linux (Ubuntu 22.04.1):
Traceback (most recent call last):
File "/home/vsts/work/1/tests/<our_test_module>", line 76, in test_gen_data
grid_search.fit(data[features].values)
File "/opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12/site-packages/sklearn/base.py", line 1473, in wrapper
return fit_method(estimator, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12/site-packages/sklearn/model_selection/_search.py", line 1019, in fit
self._run_search(evaluate_candidates)
File "/opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12/site-packages/sklearn/model_selection/_search.py", line 1573, in _run_search
evaluate_candidates(ParameterGrid(self.param_grid))
File "/opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12/site-packages/sklearn/model_selection/_search.py", line 1013, in evaluate_candidates
results = self._format_results(
^^^^^^^^^^^^^^^^^^^^^
File "/opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12/site-packages/sklearn/model_selection/_search.py", line 1137, in _format_results
for param, ma in _yield_masked_array_for_each_param(candidate_params):
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12/site-packages/sklearn/model_selection/_search.py", line 429, in _yield_masked_array_for_each_param
ma = MaskedArray(np.empty(n_candidates), mask=True, dtype=arr_dtype)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/hostedtoolcache/Python/3.12.6/x64/lib/python3.12/site-packages/numpy/ma/core.py", line 2820, in __new__
_data = np.array(data, dtype=dtype, copy=copy,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeWarning: invalid value encountered in cast
Versions
Relevant pip-installed package versions, which were all the same in Python 3.11 and 3.12 in both Linux and Windows on Azure DevOps:
numpy 1.26.4
pandas 2.2.3
scikit-learn 1.5.2
scipy 1.14.1
Activity
cacti77 commentedon Sep 26, 2024
Annoyingly, I've just noticed that these tests weren't setting a pseudo-random number seed. So some/all of the differences between OS and Python version may be due to differences in the implementation of the random number generator rather than software/hardware differences affecting numpy, as I implied above. Sorry about that. But I still think sklearn ought to know about this RuntimeWarning sometimes occurring via fit().
lesteve commentedon Sep 27, 2024
Without a snippet to reproduce it's hard to help ...
cacti77 commentedon Sep 27, 2024
@lesteve - I appreciate that and I'm sorry. The custom estimator has complicated, proprietary logic I don't understand and didn't write. I've managed to work around it in the automated tests by a combination of setting the seed for generating the test data and running the estimator; and also by use of
np.errstatelike this, for example:However I thought the sklearn community should know about this anyway in case anyone else runs into the same problem and does manage to create a reproducible code snippet.
Note I only noticed this when running the tests on Python 3.11 and 3.12 on Linux (they pass on Windows). These same tests passed regularly on Python 3.7 and 3.8 on both Windows and Linux.
(In the example above
grid_searchis an instance ofsklearn.model_selection.GridSearchCVinto which the custom estimator has been passed.)lesteve commentedon Sep 27, 2024
Would it be possible to run pytest with
--showlocalsso that we can see the value ofarr_dtypein the following line of your traceback:I am guessing it should be a kind of integer dtype.
Maybe a possible fix would be something like:
Locally on a Linux machine I can get the warning with something like below. The warning is because we create a
np.emptywithnp.float64dtype and convert it to an int dtype afterwards and sincenp.emptyuses uninitialized memory I guess you can have values that trigger the warning (either too big, too small or NaN):cacti77 commentedon Sep 27, 2024
Thanks! Is there a unittest equivalent of that pytest
--showlocalsoption we could use please? Our tests are run with the standard unittest library, not pytest. I'll be out for a few days, but hopefully I'll be able to try your suggestion (with unittest) when I'm back later next week...lesteve commentedon Sep 30, 2024
I don't know but I think it's not necessary, I am pretty sure this is what is happening.
I think it's fine to use your work-around from of ignoring the warning from #29929 (comment), since even if there is some undefined behaviour the array is going to be filled with valid values later.
We should still fix it in scikit-learn.
cacti77 commentedon Oct 2, 2024
Thanks @lesteve for putting in your fix! Once it's gone into a release of scikit-learn, please let me know, and I can create a branch to try your fix out on our tests without the
np.errstatesafety net in place; just to confirm this is what was happening for us too.cacti77 commentedon Oct 8, 2024
@lesteve: I see #29977 was merged into main recently. Are you able to tell me what release of scikit-learn this will appear in please (1.5.3?), and when? Thanks!
lesteve commentedon Oct 8, 2024
This will be in 1.6 which is scheduled around mid-November for now