You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
sample_weight is silently ignored in LogisticRegressionCV.score when metadata routing is enabled #30817
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
fromsklearnimportset_configfromsklearn.metricsimportmake_scorer, accuracy_scorefromsklearn.linear_modelimportLogisticRegressionCVimportnumpyasnprng=np.random.RandomState(22)
n_samples, n_features=10, 4X=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.scoreassertlogreg_cv.score(X, y) ==logreg_cv.score(X, y, sample_weight=sw)
assertnotlogreg_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.
@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:
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,
)
ifsample_weightisnotNone:
routed_params.scorer.score["sample_weight"] =sample_weight# Add sample_weight in the MetadataRouterelse:
routed_params=Bunch()
routed_params.scorer=Bunch(score={})
ifsample_weightisnotNone:
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:
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.
defget_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"),
)
)
returnrouter
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:
defset_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}``. """ifnot_routing_enabled():
raiseRuntimeError(
"This method is only available when metadata routing is enabled."" You can enable it using"" sklearn.set_config(enable_metadata_routing=True)."
)
forparam, aliasinkwargs.items():
self._metadata_request.score.add_request(param=param, alias=alias)
returnself
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() andself.scoringisNone:
# 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)
returnscorer
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.)
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)`deftest_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] =2kwargs= {"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 scorersscorer2=get_scorer("accuracy")
scorer2.set_score_request(sample_weight=True)
lr_cv2=LogisticRegressionCV(scoring=scorer2)
lr_cv2.fit(X, y, **kwargs)
assertnotnp.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 differencesscore_2=lr_cv2.score(X_t, y_t, **kwargs)
assertnotnp.allclose(score_1, score_2)
Activity
adrinjalali commentedon Feb 13, 2025
I confirm it's a bug, trying to figure out a fix.
Dalesrox commentedon Feb 14, 2025
/take
adrinjalali commentedon Feb 14, 2025
@Dalesrox do you know how to fix this?
Dalesrox commentedon Feb 16, 2025
@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:
in the score method for the LogisticRegressionCV class. It looks like this in the full conditional:
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:
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.
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:
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:
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.)
Dalesrox commentedon Feb 16, 2025
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.fitand.scoremethods when sample_weight is requested. However, the arguments passed to both scorers are the same (includingsample_weight). Due to the current bug, the test succeeds, but the actual testing scenario should involve different scorers: one withsample_weightand the other without it. This is necessary to verify thatsample_weightis correctly passed.5 remaining items
lorentzenchr commentedon Mar 24, 2026
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.
jeremiedbb commentedon Apr 3, 2026
I can still reproduce the bug in main. The PR that should fix it is #30859
lorentzenchr commentedon Apr 12, 2026
It also means that the following test needs to be improved (it should currently fail):
scikit-learn/sklearn/linear_model/tests/test_logistic.py
Lines 2454 to 2460 in f318298