Skip to content

Custom estimator's fit() method throws "RuntimeWarning: invalid value encountered in cast" in Linux Python 3.11/3.12 #29929

Closed

Description

@cacti77

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

  1. added
    Needs Triage
    on Sep 25, 2024
  2. cacti77 commented on Sep 26, 2024

    @cacti77
    Author

    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().

  3. added
    Needs Reproducible Code
    and removed
    Needs Triage
    on Sep 27, 2024
  4. lesteve commented on Sep 27, 2024

    @lesteve
    Member

    Without a snippet to reproduce it's hard to help ...

  5. cacti77 commented on Sep 27, 2024

    @cacti77
    Author

    @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.errstate like this, for example:

           with np.errstate(invalid='ignore'):
               grid_search.fit(data[features].values)
    

    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_search is an instance of sklearn.model_selection.GridSearchCV into which the custom estimator has been passed.)

  6. lesteve commented on Sep 27, 2024

    @lesteve
    Member

    Would it be possible to run pytest with --showlocals so that we can see the value of arr_dtype in the following line of your traceback:

    ma = MaskedArray(np.empty(n_candidates), mask=True, dtype=arr_dtype)

    I am guessing it should be a kind of integer dtype.

    Maybe a possible fix would be something like:

    ma = MaskedArray(np.empty(n_candidates, dtype=arr_dtype), mask=True)

    Locally on a Linux machine I can get the warning with something like below. The warning is because we create a np.empty with np.float64 dtype and convert it to an int dtype afterwards and since np.empty uses uninitialized memory I guess you can have values that trigger the warning (either too big, too small or NaN):

    import numpy as np
    
    np.ma.MaskedArray(np.empty(1000), dtype=np.int64)
    /home/lesteve/micromamba/lib/python3.11/site-packages/numpy/ma/core.py:2820: RuntimeWarning: invalid value encountered in cast
      _data = np.array(data, dtype=dtype, copy=copy,
    
  7. cacti77 commented on Sep 27, 2024

    @cacti77
    Author

    Thanks! Is there a unittest equivalent of that pytest --showlocals option 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...

  8. lesteve commented on Sep 30, 2024

    @lesteve
    Member

    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.

  9. cacti77 commented on Oct 2, 2024

    @cacti77
    Author

    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.errstate safety net in place; just to confirm this is what was happening for us too.

  10. cacti77 commented on Oct 8, 2024

    @cacti77
    Author

    @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!

  11. lesteve commented on Oct 8, 2024

    @lesteve
    Member

    This will be in 1.6 which is scheduled around mid-November for now

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugNeeds Reproducible Code

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions