Skip to content

FIX add missing random states and cloning in test_response.py - #33221

Merged
jeremiedbb merged 4 commits into
scikit-learn:mainfrom
AnneBeyer:fix_failing_test
Feb 6, 2026
Merged

jeremiedbb merged 4 commits into
scikit-learn:mainfrom
AnneBeyer:fix_failing_test

Conversation

@AnneBeyer

@AnneBeyer AnneBeyer commented Feb 6, 2026 •

Copy link
Copy Markdown
Member

Reference Issues/PRs

Towards #32393 and possibly also #33216

What does this implement/fix? Explain your changes.

I added the missing random_seed to the KMeans test cases and also added clone before fit (as it is done for example in line 240) where it was missing.

@lesteve

AI usage disclosure

I used AI assistance for:

  • Code generation (e.g., when writing an implementation or fixing a bug)
  • Test/benchmark generation
  • Documentation (including examples)
  • Research and understanding

Any other comments?

y = np.array([[0, 1], [1, 0]] * 5)

clf = clone(estimator).fit(X, y)
estimator = clone(estimator).fit(X, y) # clone to make test execution thread-safe

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unrelated small clean-up: changed clf toestimator because different estimators are tested here

And I added the comment on explaining the cloning here as well, because I didn't know this, and it probably doesn't hurt to be expressive on this.

(KMeans(n_clusters=2, n_init=1), "predict", "binary", (10,)),
(KMeans(n_clusters=2, n_init=1), "predict", "multiclass", (10,)),
(KMeans(n_clusters=2), "predict", "binary", (10,)),
(KMeans(n_clusters=4), "predict", "multiclass", (10,)),

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unrelated small clean-up: remove redundant parameter and make test case more consistent

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: Here we also just check response shapes, so random states don't matter for this test.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is changing to n_clusters=4 on purpose ?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, to make explicit that the output shape also doesn't change in the multiclass (or rather, "multicluster") case. I didn't see this in the PR where it was added, but I can also make a separate PR for the cleanu-ps if this is becoming too cluttered now.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the clarification. It's fine to keep it in this PR

(DBSCAN(), "predict"),
(IsolationForest(random_state=0), "predict_proba"),
(IsolationForest(random_state=0), ["predict_proba", "score"]),
(IsolationForest(), "predict_proba"),

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here we just check the attributes, so setting the random_state has no impact. Not sure if we should consistently add or remove it in such cases?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's fine not to have random_state in this case.

"estimator, response_method",
[
(LinearRegression(), "predict"),
(KMeans(n_clusters=2, n_init=1), "predict"),

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

n_init=1 is the default value in this case anyways

"""Check the error message with not supported response method."""
X, y = np.random.RandomState(0).randn(10, 2), np.array([0, 1] * 5)
estimator.fit(X, y)
estimator = clone(estimator).fit(X, y) # clone to make test execution thread-safe

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just curious, you are doing this for free-threaded because you have noticed issues when running the test locally with pytest-run-parallel?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, I saw that this was done like this with this comment on line 240 (added by Olivier) and adapted it for the rest.

@lesteve

lesteve commented Feb 6, 2026 •

Copy link
Copy Markdown
Member

Not sure why, but I am still getting a failure with free-threaded locally with the following command:

pytest sklearn/utils/tests/test_response.py --parallel-threads 4 --iterations 10
PARALLEL FAILED sklearn/utils/tests/test_response.py::test_estimator_get_response_values[True-estimator2-score] - AssertionError: 
PARALLEL FAILED sklearn/utils/tests/test_response.py::test_estimator_get_response_values[False-estimator2-score] - AssertionError: 

Details for one of the errors:

_________________________________________ ERROR at call of test_estimator_get_response_values[False-estimator2-score] _________________________________________

estimator = KMeans(n_clusters=2, random_state=0), response_method = 'score', return_response_method_used = False

    @pytest.mark.parametrize(
        "estimator, response_method",
        [
            (LinearRegression(), "predict"),
            (KMeans(n_clusters=2, random_state=0), "predict"),
            (KMeans(n_clusters=2, random_state=0), "score"),
            (KMeans(n_clusters=2, random_state=0), ["predict", "score"]),
            (IsolationForest(random_state=0), "predict"),
            (IsolationForest(random_state=0), "decision_function"),
            (IsolationForest(random_state=0), ["decision_function", "predict"]),
        ],
    )
    @pytest.mark.parametrize("return_response_method_used", [True, False])
    def test_estimator_get_response_values(
        estimator, response_method, return_response_method_used
    ):
        """Check the behaviour of `_get_response_values`."""
        X, y = np.random.RandomState(0).randn(10, 2), np.array([0, 1] * 5)
        estimator = clone(estimator).fit(X, y)  # clone to make test execution thread-safe
        results = _get_response_values(
            estimator,
            X,
            response_method=response_method,
            return_response_method_used=return_response_method_used,
        )
        chosen_response_method = (
            response_method[0] if isinstance(response_method, list) else response_method
        )
        prediction_method = getattr(estimator, chosen_response_method)
>       assert_array_equal(results[0], prediction_method(X))
E       AssertionError: 
E       Arrays are not equal
E       
E       Mismatched elements: 1 / 1 (100%)
E       Max absolute difference among violations: 8.8817842e-16
E       Max relative difference among violations: 1.39609109e-16
E        ACTUAL: array(-6.361894)
E        DESIRED: array(-6.361894)

sklearn/utils/tests/test_response.py:81: AssertionError

@AnneBeyer

Copy link
Copy Markdown
Member Author
pytest sklearn/utils/tests/test_response.py --parallel-threads 4 --iterations 10

For me this passes locally, but the code on main actually does, too (on Linux) 🤷

@AnneBeyer

AnneBeyer commented Feb 6, 2026 •

Copy link
Copy Markdown
Member Author

Oh, hang on, I also get the following messages when setting PYTEST_RUN_PARALLEL_VERBOSE=1

sklearn/utils/tests/test_response.py::test_estimator_get_response_values[False-estimator2-score] was not run in parallel because it calls thread-unsafe function: warnings.catch_warnings

Do you know how I can overwrite this to test it locally?

@AnneBeyer

Copy link
Copy Markdown
Member Author

Not sure why, but I am still getting a failure with free-threaded locally

So score seems to be the culprit here. It does indeed return a float, so maybe this test doesn't make sense here? I'm not very familiar with the use cases for the different scoring functions yet, but the test for LinearRegression also only checks predict, so maybe we could just remove score here?

@AnneBeyer

Copy link
Copy Markdown
Member Author

Another option would be to see if it is enough to replace assert_array_equal with assert_allclose if prediction_method="score".

@AnneBeyer

Copy link
Copy Markdown
Member Author

Do you know how I can overwrite this to test it locally?

I guess upgrading to Python 3.14 is required, right? I'll give that a try.

@lesteve

lesteve commented Feb 6, 2026 •

Copy link
Copy Markdown
Member

I guess upgrading to Python 3.14 is required, right? I'll give that a try.

In general with free-threaded it's better to use Python 3.14 indeed. The warning you get does ring a bell and I think you will not get it if you use Python 3.14 and you will get the failure instead.

@lesteve

lesteve commented Feb 6, 2026

Copy link
Copy Markdown
Member

Actually, it does not seem to be related to pytest-run-parallel I do get occasional failures with free-threaded

pytest sklearn/utils/tests/test_response.py -k 'test_estimator_get_response_values and estimator2' 

With pytest-repeat you can run the test multiple times and it will fail at one point:

pytest sklearn/utils/tests/test_response.py -k 'test_estimator_get_response_values and estimator2' --count 10

@lesteve

lesteve commented Feb 6, 2026 •

Copy link
Copy Markdown
Member

To be honest, using assert_allclose is probably the right work-around to use, because this is the thing we do to compare floating points ...

The relative difference is close to 1e-16 and so it is close to the float64 resolution, and I don't think we should spend too much time on this. Why it only happens for free-threaded, I don't know, there may be something fishy there, hard to tell ...

@lesteve

lesteve commented Feb 6, 2026

Copy link
Copy Markdown
Member

This is not free-threaded specific I do see a similar thing as #33221 (comment) with vanilla Python 3.14.

@AnneBeyer

Copy link
Copy Markdown
Member Author

Should we still keep the random state and cloning changes or just merge #33225 instead?

@lesteve

lesteve commented Feb 6, 2026

Copy link
Copy Markdown
Member

Let's keep this one I think, because I think it also fixes free-threaded problems.

@lesteve lesteve left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks!

This fixes all the failures on free-threaded locally for me and cleans up a few things.

@jeremiedbb jeremiedbb left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Thanks !

@jeremiedbb
jeremiedbb merged commit bf223d9 into scikit-learn:main Feb 6, 2026
50 of 52 checks passed
@AnneBeyer
AnneBeyer deleted the fix_failing_test branch February 6, 2026 21:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants