Skip to content

ENH Auto-requesting sample_weight on meta-estimators that also consume it - #35095

Merged
ogrisel merged 15 commits into
scikit-learn:mainfrom
StefanieSenger:auto-request_routers
Oct 27, 2026
Merged

ogrisel merged 15 commits into
scikit-learn:mainfrom
StefanieSenger:auto-request_routers

Conversation

@StefanieSenger

@StefanieSenger StefanieSenger commented Oct 7, 2026 •

Copy link
Copy Markdown
Member

Reference Issues/PRs

towards #34901

What does this implement/fix? Explain your changes.

This adds auto-requests for sample_weight to (all of our) 10 meta-estimators that also consume sample_weight internally (in fit and/or score).

#34966 already covers the functionality that we wanted to add here, which is why this PR now only adds the tests and an update to the changelog entry of the other PR.

AI usage disclosure

I used AI assistance for:

  • Test/benchmark generation
  • Research and understanding

@StefanieSenger StefanieSenger added the Metadata Routing all issues related to metadata routing, slep006, sample props label Oct 7, 2026
@StefanieSenger StefanieSenger changed the title ENH Auto-requesting sample_weight on meta-estimators that also consume it ENH Auto-requesting sample_weight on meta-estimators that also consume it Oct 7, 2026
@@ -0,0 +1,14 @@
- |Feature| The following consuming :term:`routers <router>` auto-request

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.

The feature tag appears twice
Image

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.

Thank you, I have fixed this now.

@StefanieSenger

Copy link
Copy Markdown
Member Author

I set the "No Changelog needed" label to prevent the CI from failing. It had passed before but after fixing the changelogs across several PRs in 476420f, it fails because it cannot match the file names with this PR anymore.

@StefanieSenger StefanieSenger added this to the 1.10 milestone Oct 13, 2026

@OmarManzoor OmarManzoor left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Otherwise LGTM. Thank you @StefanieSenger

Comment on lines +2763 to +2801
@config_context(enable_metadata_routing=True)
def test_search_sample_weight_auto_request():
# Check that auto-requesting `sample_weight` works on consuming routers if passed
# through `GridSearchCV`.
X, y = make_classification(random_state=42)
sample_weight = np.ones(len(y))
meta_est = WeightedMetaClassifier(estimator=NonConsumingClassifier())
search = GridSearchCV(meta_est, param_grid={"estimator__alpha": [0.0]}, cv=2)

with config_context(enable_metadata_auto_requests=False):
assert (
get_routing_for_object(search)
._route_mappings["estimator"]
.router._self_request.fit.requests.get("sample_weight")
is None
)
assert (
get_routing_for_object(search)
._route_mappings["estimator"]
.router._self_request.score.requests.get("sample_weight")
is None
)
with pytest.raises(UnsetMetadataPassedError, match="sample_weight"):
search.fit(X, y, sample_weight=sample_weight)

with config_context(enable_metadata_auto_requests=True):
assert (
get_routing_for_object(search)
._route_mappings["estimator"]
.router._self_request.fit.requests.get("sample_weight")
is True
)
assert (
get_routing_for_object(search)
._route_mappings["estimator"]
.router._self_request.score.requests.get("sample_weight")
is True
)
search.fit(X, y, sample_weight=sample_weight)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Might be better to parametrize?

@pytest.mark.parametrize(
    "auto_request, expected",
    [(False, None), (True, True)],
)
@config_context(enable_metadata_routing=True)
def test_search_sample_weight_auto_request(auto_request, expected):
    # Check that auto-requesting `sample_weight` works on consuming routers if passed
    # through `GridSearchCV`.
    X, y = make_classification(random_state=42)
    sample_weight = np.ones(len(y))
    meta_est = WeightedMetaClassifier(estimator=NonConsumingClassifier())
    search = GridSearchCV(meta_est, param_grid={"estimator__alpha": [0.0]}, cv=2)

    with config_context(enable_metadata_auto_requests=auto_request):
        assert (
            get_routing_for_object(search)
            ._route_mappings["estimator"]
            .router._self_request.fit.requests.get("sample_weight")
            is expected
        )
        assert (
            get_routing_for_object(search)
            ._route_mappings["estimator"]
            .router._self_request.score.requests.get("sample_weight")
            is expected
        )

        if auto_request:
            search.fit(X, y, sample_weight=sample_weight)
        else:
            with pytest.raises(UnsetMetadataPassedError, match="sample_weight"):
                search.fit(X, y, sample_weight=sample_weight)

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.

So much cleaner, thanks a lot @OmarManzoor!

@antoinebaker

Copy link
Copy Markdown
Member

Hi @StefanieSenger, thanks for the PR. I have a couple of questions while reviewing:

  1. after the merge of ENH Auto-requesting sample_weight on pure consumers #34966, do we really need to declare the auto requests for the meta-estimators ? I feel that as the meta-estimators also inherit from BaseEstimator, part of the auto request machinery is already there (fit and score probably already auto request sample_weight), and we don't need to declare the auto request again.
  2. in case we really do need to declare the auto request for the meta-estimators, how to make sure that we cover them all ?
  3. For instance if we look at the meta-estimator which have sample_weight in their fit signature and seem to consume it in some way, the BaseBagging estimators (BaggingClassifier, BaggingRegressor, IsolationForest) seem to be missing.
  4. Same for score, in this PR many meta-estimators need to request sample_weight when their default scorer (scoring=None) actually fallbacks to the ClassifierMixin or RegressorMixin score (if the scoring is provided then it's the scorer child that needs to request sample_weight). But this fallback actually happens in many more estimators which are not covered here.

TDLR: do we really need to declare auto request at all ? If so, how to make sure we cover all meta-estimators that need it (and only the ones that need it) ?

@antoinebaker

Copy link
Copy Markdown
Member

For point 4, here's according to cursor the list of meta-estimators that consume sample_weight in this fashion.

score uses the weights for In the pull request Not in the pull request
accuracy, via ClassifierMixin OneVsRestClassifier, OneVsOneClassifier, CalibratedClassifierCV, RidgeClassifierCV BaggingClassifier, VotingClassifier, StackingClassifier, ClassifierChain, OutputCodeClassifier, FixedThresholdClassifier, TunedThresholdClassifierCV, AdaBoostClassifier
R², via RegressorMixin RidgeCV, LassoCV, ElasticNetCV, MultiTaskLassoCV, MultiTaskElasticNetCV BaggingRegressor, VotingRegressor, StackingRegressor, RegressorChain, TransformedTargetRegressor, MultiOutputRegressor, AdaBoostRegressor

@antoinebaker

Copy link
Copy Markdown
Member

Besides I think we need more thorough testing, probably in follow-up PRs.

For now the tests are mainly focused on the declaration part (is this sample_weight request present or not), but we don't yet check the functional part (are sample_weight actually passed to the method when called). I see two ways.

  1. Repeated/weighted equivalence test for sample_weight, we could try this for some elaborate meta-estimators, composed of many sklearn bricks (pipeline, grid search, custom scorers, calibrated classifiers, a cv estimator, ...).
  2. Check the actual sample_weight passed to the different children methods. You call a method on the top level meta -estimator with known sample_weight, and check that each of its children methods is indeed called with the expected sample_weight array.

For 1. if the complex meta-estimator passes, then we will be reassured that the individual components and the metadata routing machinery are working as expected. But if it fails, it will be quite hard to debug ! So that's why I'm proposing 2.

For 2. maybe a callback could be handy, at least for the fit method ? For example a callback which simply registers the arguments passed to fit for each call. WDYT @FrancoisPgm ?

Let me know what you think @StefanieSenger and @ogrisel, I can start to work on some of these tests if you think it's a good idea.

@StefanieSenger

Copy link
Copy Markdown
Member Author

Let me know what you think @StefanieSenger and @ogrisel, I can start to work on some of these tests if you think it's a good idea.

I love your ideas. We already do quite some testing if sample_weight is actually routed in sklearn/tests/test_metaestimators_metadata_routing.py (with check_recorded_metadata), but these tests are simplifications and in the past there had been a few bugs reported that we had obviously missed.

Happy for you to take the lead there, @antoinebaker. I can review your work then.

@StefanieSenger

StefanieSenger commented Oct 15, 2026 •

Copy link
Copy Markdown
Member Author

after the merge of #34966, do we really need to declare the auto requests for the meta-estimators ? I feel that as the meta-estimators also inherit from BaseEstimator, part of the auto request machinery is already there (fit and score probably already auto request sample_weight), and we don't need to declare the auto request again.

I was wondering about the same question. Yes, we had not taken care of the default scorer here (via ClassifierMixin and RegressorMixin) in this PR, but in the meantime with #34966 merged I would think this is covered.

Let me do a through check if we didn't miss anything.

(An exception here is OutputCodeClassifier, where we had forgotten to set the self_request when implementing metadata routing (and we need a bugfix PR for this).

in case we really do need to declare the auto request for the meta-estimators, how to make sure that we cover them all ?

I am actually not sure how we can be sure we covered everything. But surely if we could come up with a test for this, it would be an very valuable test.

@StefanieSenger

StefanieSenger commented Oct 15, 2026 •

Copy link
Copy Markdown
Member Author

For instance if we look at the meta-estimator which have sample_weight in their fit signature and seem to consume it in some way, the BaseBagging estimators (BaggingClassifier, BaggingRegressor, IsolationForest) seem to be missing.

Bagging* is an interesting case, that I hadn't had payed attention to before. Here, metadata routing was implemented first in #28432, then in #31414 we added internal sample_weight usage, but we forgot to add the metadata routing support for this (add_self_request).
We need to .add_self_request(self_request) to the router and add the corresponding test (which I think also lives in sklearn/tests/test_metaestimators_metadata_routing.py).

Once this is done, the Bagging* will need a self_request_sample_weight_methods in the tests, so it will be covered by test_metaestimator_adds_auto_request_to_self_request which is added by the current PR.

And there may be more cases like these.

@FrancoisPgm

Copy link
Copy Markdown
Member

For now the tests are mainly focused on the declaration part (is this sample_weight request present or not), but we don't yet check the functional part (are sample_weight actually passed to the method when called).

I am not sure the additional tests are mandatory. As far as I understand, the auto-request is only about automatically adding the request, but when it is added it is, the estimator is in the same state as if the request had been manually added, and thus uses the same logical path. If that is the case, then the functional part should already be covered by the regular metadatarouting tests and checking that the request is present at the right time should be enough. Although maybe I misunderstood and the auto-request uses a different logical path than manual requests, in which case I agree that the additional functional tests are necessary.

@StefanieSenger

StefanieSenger commented Oct 15, 2026 •

Copy link
Copy Markdown
Member Author

As far as I understand, the auto-request is only about automatically adding the request, but when it is added it is, the estimator is in the same state as if the request had been manually added, and thus uses the same logical path.

This is correct, they use the same logical path. This is why it makes sense to add these tests in a separate PR (because they are unrelated to the auto-requests). But we had really missed some bugs in the past with the tests that we have and a strategic check will be very valuable when we start thinking about moving metadata routing out of experimental (in a future release, not the 1.10 one).

Edit: I forgot to answer to this:

For 2. maybe a callback could be handy, at least for the fit method ?

A callback run by pytest (if I understand correctly) may be a challenge, at least if it uses a different thread. I am not sure if its worth it.

@StefanieSenger StefanieSenger left a comment

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.

Thank you @OmarManzoor for your review and suggestions.

Comment on lines +2763 to +2801
@config_context(enable_metadata_routing=True)
def test_search_sample_weight_auto_request():
# Check that auto-requesting `sample_weight` works on consuming routers if passed
# through `GridSearchCV`.
X, y = make_classification(random_state=42)
sample_weight = np.ones(len(y))
meta_est = WeightedMetaClassifier(estimator=NonConsumingClassifier())
search = GridSearchCV(meta_est, param_grid={"estimator__alpha": [0.0]}, cv=2)

with config_context(enable_metadata_auto_requests=False):
assert (
get_routing_for_object(search)
._route_mappings["estimator"]
.router._self_request.fit.requests.get("sample_weight")
is None
)
assert (
get_routing_for_object(search)
._route_mappings["estimator"]
.router._self_request.score.requests.get("sample_weight")
is None
)
with pytest.raises(UnsetMetadataPassedError, match="sample_weight"):
search.fit(X, y, sample_weight=sample_weight)

with config_context(enable_metadata_auto_requests=True):
assert (
get_routing_for_object(search)
._route_mappings["estimator"]
.router._self_request.fit.requests.get("sample_weight")
is True
)
assert (
get_routing_for_object(search)
._route_mappings["estimator"]
.router._self_request.score.requests.get("sample_weight")
is True
)
search.fit(X, y, sample_weight=sample_weight)

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.

So much cleaner, thanks a lot @OmarManzoor!

@StefanieSenger

StefanieSenger commented Oct 15, 2026 •

Copy link
Copy Markdown
Member Author

I've now checked and it is clear that #34966 already covers any sample_weight in any method of any scikit-learn class that inherits from BaseEstimator. I have re-purposed this PR to only add the tests for meta-estimators and to take care to update the changelog entry. Happy for you to take another look, @antoinebaker.

Even though process_routing adds add_auto_requests for any sample_weight everywhere now, auto-requests can only be actualised if this method participates in metadata routing.

Happy to review if someone wants to add self_requests and auto-request-tests for Bagging*, Isolationforest and OutputCodeClassifier. If there is any other meta-estimator that consumes sample_weight but doesn't self-request it, we should do the same here.

Adding auto-requests to scorers is still a different beast since they don't inherit from BaseEstimator.

@antoinebaker

Copy link
Copy Markdown
Member

As far as I understand, the auto-request is only about automatically adding the request, but when it is added it is, the estimator is in the same state as if the request had been manually added, and thus uses the same logical path.

This is correct, they use the same logical path. This is why it makes sense to add these tests in a separate PR (because they are unrelated to the auto-requests). But we had really missed some bugs in the past with the tests that we have and a strategic check will be very valuable when we start thinking about moving metadata routing out of experimental (in a future release, not the 1.10 one).

Thanks @FrancoisPgm, that's indeed a good point. The functional tests will check the metadata routing machinery and sample weight consistency as a whole, not the way the requests are made. To elaborate on @StefanieSenger answer, we were a bit discouraged in the past to try out sophisticated meta estimators, precisely because of the difficulty of manually writing all the sample_weight requests (it was very verbose and easy to forget one). Hopefully this PR will make the creation of such tests much easier with the auto-requests !

@antoinebaker

antoinebaker commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

Happy to review if someone wants to add self_requests and auto-request-tests for Bagging*, Isolationforest and OutputCodeClassifier. If there is any other meta-estimator that consumes sample_weight but doesn't self-request it, we should do the same here.

Could you please try in this PR ? I think it could be as simple as setting the add_self_request in BaseBagging.get_metadata_routing, and edit the self_request_sample_weight_methods entry for bagging estimators to check that they pass test_metaestimator_adds_auto_request_to_self_request. Then I think we cover all metaestimators for the fit method.

Adding auto-requests to scorers is still a different beast since they don't inherit from BaseEstimator.

For score missing auto requests I agree we should postpone for now and wait for the scorers PR #35099.

@antoinebaker antoinebaker 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.

Hi @StefanieSenger, thanks for the PR !

I think it would be good to fix the bagging estimators in this PR, as said in the previous comment.

But otherwise, LGMT !

Comment on lines +2781 to +2792
assert (
get_routing_for_object(search)
._route_mappings["estimator"]
.router._self_request.fit.requests.get("sample_weight")
is expected
)
assert (
get_routing_for_object(search)
._route_mappings["estimator"]
.router._self_request.score.requests.get("sample_weight")
is expected
)

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.

The path to get to the meta_est self_request is quite intricate. Is there a simpler way ? Maybe

routing = get_routing_for_object(meta_est)
assert routing._self_request.fit.requests.get("sample_weight") is expected
assert routing._self_request.score.requests.get("sample_weight") is expected

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.

That's nice. Thanks. :)

@StefanieSenger StefanieSenger left a comment

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.

Could you please try in this PR ? I think it could be as simple as setting the add_self_request in BaseBagging.get_metadata_routing, and edit the self_request_sample_weight_methods entry for bagging estimators to check that they pass test_metaestimator_adds_auto_request_to_self_request. Then I think we cover all metaestimators for the fit method.

Yes, it's as simple as that. I did add all this to the current PR, so we have all the modifications in one place.

Comment on lines +2781 to +2792
assert (
get_routing_for_object(search)
._route_mappings["estimator"]
.router._self_request.fit.requests.get("sample_weight")
is expected
)
assert (
get_routing_for_object(search)
._route_mappings["estimator"]
.router._self_request.score.requests.get("sample_weight")
is expected
)

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.

That's nice. Thanks. :)

@StefanieSenger

StefanieSenger commented Oct 20, 2026 •

Copy link
Copy Markdown
Member Author

I think we can merge this PR, is that alright for you, @OmarManzoor?

@ogrisel ogrisel 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 as well. Thanks @StefanieSenger and reviewers.

@ogrisel
ogrisel merged commit 42981ef into scikit-learn:main Oct 27, 2026
38 checks passed
@github-project-automation github-project-automation Bot moved this from PR waiting for reviews to Done in Labs Oct 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants