Skip to content

sample_weight is silently ignored in LogisticRegressionCV.score when metadata routing is enabled #30817

Closed

Description

@antoinebaker

Describe the bug

I'm not sure if it is a proper bug, or my lack of understanding of the metadata routing API ;)

When enable_metadata_routing=True, the score method of a LogisticRegressionCV estimator will ignore sample_weight.

set_config(enable_metadata_routing=True)
logreg_cv = LogisticRegressionCV().fit(X, y)
logreg_cv.score(X, y, sample_weight=sw)==logreg_cv.score(X, y) #unweighted accuracy

I found it surprising, because the score method works fine when enable_metadata_routing=False, so the same piece of code behaves differently depending on the metadata routing config.

set_config(enable_metadata_routing=False)
logreg_cv = LogisticRegressionCV().fit(X, y)
logreg_cv.score(X, y, sample_weight=sw) #weighted accuracy

If I understood the metadata routing API correctly, to make the score method sample_weight aware we need to explicitly pass a scorer that request it:

set_config(enable_metadata_routing=True)
weighted_accuracy = make_scorer(accuracy_score).set_score_request(sample_weight=True)
logreg_cv = LogisticRegressionCV(scoring=weighted_accuracy).fit(X, y)
logreg_cv.score(X, y, sample_weight=sw) #weighted accuracy

If it's the intended behavior of the metadata routing API, maybe we should warn the user or raise an error in the first case, instead of silently ignoring sample_weight ?

Steps/Code to Reproduce

from sklearn import set_config
from sklearn.metrics import make_scorer, accuracy_score
from sklearn.linear_model import LogisticRegressionCV
import numpy as np

rng = np.random.RandomState(22)
n_samples, n_features = 10, 4
X = rng.rand(n_samples, n_features)
y = rng.randint(0, 2, size=n_samples)
sw = rng.randint(0, 5, size=n_samples)

set_config(enable_metadata_routing=True)
logreg_cv = LogisticRegressionCV()
logreg_cv.fit(X, y)
# sample_weight is silently ignored in logreg_cv.score
assert logreg_cv.score(X, y) == logreg_cv.score(X, y, sample_weight=sw) 
assert not logreg_cv.score(X, y, sample_weight=sw)==accuracy_score(logreg_cv.predict(X),y, sample_weight=sw)

Expected Results

Either logreg_cv.score(X, y, sample_weight=sw) raises an error/warning or the assertions are false.

Actual Results

The assertions are true.

Versions

sklearn: 1.7.dev0

Activity

  1. added
    Needs Triage
    on Feb 12, 2025
  2. adrinjalali commented on Feb 13, 2025

    @adrinjalali
    Member

    I confirm it's a bug, trying to figure out a fix.

  3. added
    Metadata Routing
    and removed
    Needs Triage
    on Feb 13, 2025
  4. added this to the 1.7 milestone on Feb 13, 2025
  5. Dalesrox commented on Feb 14, 2025

    @Dalesrox

    /take

  6. adrinjalali commented on Feb 14, 2025

    @adrinjalali
    Member

    @Dalesrox do you know how to fix this?

  7. Dalesrox commented on Feb 16, 2025

    @Dalesrox

    @adrinjalali I was reading about the problem, and it lies in the way the score function works. It calls process_routing, passing the sample_weights in the **kwargs of the function. However, inside that function, the **kwargs are not processed properly. The easy (and lazy) solution is simply to add:

    if sample_weight is not None: 
        routed_params.scorer.score["sample_weight"] = sample_weight

    in the score method for the LogisticRegressionCV class. It looks like this in the full conditional:

    if _routing_enabled():
        routed_params = process_routing(
            self,
            "score",
            sample_weight=sample_weight,
            **score_params,
        )
        if sample_weight is not None: 
            routed_params.scorer.score["sample_weight"] = sample_weight # Add sample_weight in the MetadataRouter
    else:
        routed_params = Bunch()
        routed_params.scorer = Bunch(score={})
        if sample_weight is not None:
            routed_params.scorer.score["sample_weight"] = sample_weight

    But this is only a solution for the current variable "sample_weight" in the "score" function for this specific class (LogisticRegressionCV). This means other classes and functions using metadata routing might have the same problem.

    I suggest implementing this change for correct behavior in this class. However, I'm also exploring a way to fix this inside the "process_routing" function, because that affects more classes than LogisticRegressionCV (like ridge, omp, ransac, etc.). For example, if you call the process_routing function directly on the LogisticRegressionCV object for the "score" method like this:

    from sklearn import set_config, get_config
    from sklearn.metrics import make_scorer, accuracy_score
    from sklearn.linear_model import LogisticRegressionCV
    from sklearn.utils.metadata_routing import (
        process_routing,
    )
    import numpy as np
    
    rng = np.random.RandomState(22)
    n_samples, n_features = 10, 4
    X = rng.rand(n_samples, n_features)
    y = rng.randint(0, 2, size=n_samples)
    sw = rng.randint(0, 5, size=n_samples)
    
    set_config(enable_metadata_routing=True)
    logreg_cv = LogisticRegressionCV()
    logreg_cv.fit(X, y)
    
    process_routing(logreg_cv, "score", sample_weight = sw) # call routing for score method

    It currently returns:

    {'splitter': {}, 'scorer': {'score': {}}}

    but the expected result is:

    'splitter': {}, 'scorer': {'score': {'sample_weight': sw}}}

    I suspect that is related to the "get_metadata_routing" function, that is called in this way:

    process_routing (from _metadata_routing.py) calls:
    get_routing_for_object (from _metadata_routing.py), which calls:
    get_metadata_routing (a method of the MetadataRouter object). Therefore, this is where process_routing's behavior is inheritable by all MetadataRouter objects (i.e., LogisticRegressionCV, RidgeCV, etc.).

    That function is responsible for assigning the scorer (and other **kwargs) values in the Router object.

    def get_metadata_routing(self):
            """Get metadata routing of this object.
    
            Please check :ref:`User Guide <metadata_routing>` on how the routing
            mechanism works.
    
            .. versionadded:: 1.4
    
            Returns
            -------
            routing : MetadataRouter
                A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating
                routing information.
            """
    
            router = (
                MetadataRouter(owner=self.__class__.__name__)
                .add_self_request(self)
                .add(
                    splitter=self.cv,
                    method_mapping=MethodMapping().add(caller="fit", callee="split"),
                )
                .add(
                    scorer=self._get_scorer(),
                    method_mapping=MethodMapping()
                    .add(caller="score", callee="score")
                    .add(caller="fit", callee="score"),
                )
            )
            return router

    And probably there is the source of the real problem.

    Currently, RidgeCV handles this error with a similar method to the one I suggested here.
    I just checked, and it uses a method named set_score_request that essentially does the same thing as what I'm doing:

    def set_score_request(self, **kwargs):
           """Set requested parameters by the scorer.
    
           Please see :ref:`User Guide <metadata_routing>` on how the routing
           mechanism works.
    
           .. versionadded:: 1.5
    
           Parameters
           ----------
           kwargs : dict
               Arguments should be of the form ``param_name=alias``, and `alias`
               can be one of ``{True, False, None, str}``.
           """
           if not _routing_enabled():
               raise RuntimeError(
                   "This method is only available when metadata routing is enabled."
                   " You can enable it using"
                   " sklearn.set_config(enable_metadata_routing=True)."
               )
    
           for param, alias in kwargs.items():
               self._metadata_request.score.add_request(param=param, alias=alias) 
           return self

    This is similar to routed_params.scorer.score["sample_weight"] = sample_weight, but it forces the passing of a sample_weight value, as stated in a comment inside _ridge.py:

           if _routing_enabled() and self.scoring is None:
               # This estimator passes an array of 1s as sample_weight even if
               # sample_weight is not provided by the user. Therefore we need to
               # always request it. But we don't set it if it's passed explicitly
               # by the user.
               scorer.set_score_request(sample_weight=True)
           return scorer

    I will create a pull request with the "quick fix," but I think it's necessary to unify the way methods handle these metadata requests. (Sorry for all the text, but I consider this relevant for improving future code maintenance.)

  8. Dalesrox commented on Feb 16, 2025

    @Dalesrox

    A change is also needed in test_lr_cv_scores_differ_when_sample_weight_is_requested. Currently, as the description states, that test looks for different behavior in the .fit and .score methods when sample_weight is requested. However, the arguments passed to both scorers are the same (including sample_weight). Due to the current bug, the test succeeds, but the actual testing scenario should involve different scorers: one with sample_weight and the other without it. This is necessary to verify that sample_weight is correctly passed.

    @config_context(enable_metadata_routing=True)`
    def test_lr_cv_scores_differ_when_sample_weight_is_requested():
        """Test that `sample_weight` is correctly passed to the scorer in
        `LogisticRegressionCV.fit` and `LogisticRegressionCV.score` by
        checking the difference in scores with the case when `sample_weight`
        is not requested.
        """
        rng = np.random.RandomState(10)
        X, y = make_classification(n_samples=10, random_state=rng)
        X_t, y_t = make_classification(n_samples=10, random_state=rng)
        sample_weight = np.ones(len(y))
        sample_weight[: len(y) // 2] = 2
        kwargs = {"sample_weight": sample_weight}
    
        scorer1 = get_scorer("accuracy")
        lr_cv1 = LogisticRegressionCV(scoring=scorer1)
        lr_cv1.fit(X, y) # Don't pass the sample_weight, we are testing differences, we cant pass the same arguments in both scorers
    
        scorer2 = get_scorer("accuracy")
        scorer2.set_score_request(sample_weight=True)
        lr_cv2 = LogisticRegressionCV(scoring=scorer2)
        lr_cv2.fit(X, y, **kwargs)
    
        assert not np.allclose(lr_cv1.scores_[1], lr_cv2.scores_[1])
    
        score_1 = lr_cv1.score(X_t, y_t) # Same here, don't pass sample_weight for test differences
        score_2 = lr_cv2.score(X_t, y_t, **kwargs)
    
        assert not np.allclose(score_1, score_2)
  9. modified the milestones: 1.7, 1.8 on Jul 1, 2025
  10. 5 remaining items

  11. moved this from Todo to In progress in Labson Dec 10, 2025
  12. moved this from In progress to Todo in Labson Dec 11, 2025
  13. removed their assignment
    on Dec 11, 2025
  14. lorentzenchr commented on Mar 24, 2026

    @lorentzenchr
    Member

    I can't reproduce the error. Maybe, it was fixed (accidentally) in #32828. If so, what remains is a test, maybe also an added FIX in the whatsnew.

  15. jeremiedbb commented on Apr 3, 2026

    @jeremiedbb
    Member

    I can still reproduce the bug in main. The PR that should fix it is #30859

  16. lorentzenchr commented on Apr 12, 2026

    @lorentzenchr
    Member

    It also means that the following test needs to be improved (it should currently fail):

    @config_context(enable_metadata_routing=True)
    def test_lr_cv_scores_differ_when_sample_weight_is_requested(global_random_seed):
    """Test that `sample_weight` is correctly passed to the scorer in
    `LogisticRegressionCV.fit` and `LogisticRegressionCV.score` by
    checking the difference in scores with the case when `sample_weight`
    is not requested.
    """

  17. removed this from the 1.9 milestone on May 5, 2026
  18. moved this from Todo to In progress in Labson May 13, 2026
  19. moved this from In Progress to Done in Metadata routingon May 19, 2026
  20. moved this from In progress to Done in Labson May 19, 2026
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

    BugMetadata Routing

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions