Repository navigation
_MultimetricScorer deals with _accept_sample_weights inconsistently #31599
Copy link
Copy link
Open
Labels
Description
Describe the bug
When one of the scorers in _MultimetricScorer is not a Scorer object, it is handled incorrectly.
See line here. If the scorers passed to MultimetricScorer are of the following type: [Scorer, function], it raises an error because the attribute _accept_sample_weight does not exist for the second scorer (function in this case). This (possibly) bug is present only in 1.7.0 since before this, the sample_weight kwarg was being passed to all functions without a check of accepting sample weights.
Possible fix: Use if hasattr(scorer, '_accept_sample_weight') or if isinstance(scorer, _BaseScorer) before checking for the _accept_sample_weight attribute.
Steps/Code to Reproduce
import numpy as np
from sklearn.base import BaseEstimator, RegressorMixin
from sklearn.metrics._scorer import _BaseScorer, _MultimetricScorer
# Step 1: Define a simple estimator
class SimpleEstimator(BaseEstimator, RegressorMixin):
def fit(self, X, y):
self.mean_ = np.mean(y)
return self
def predict(self, X):
return np.full(X.shape[0], self.mean_)
# Step 2: Define a custom scorer inheriting from _BaseScorer and a function which estimates score
class SimpleScorer(_BaseScorer):
def _score(self, method_caller, estimator, X, y_true, sample_weight=None):
y_pred = method_caller(estimator, "predict", X)
return self._score_func(y_true, y_pred, **self._kwargs)
def default_score(estimator, X, y, sample_weight=None, **kws):
return estimator.score(X, y, sample_weight=sample_weight)
def mse(y, y_pred):
return np.mean((y - y_pred)**2)
# Step 3: Create a _MultimetricScorer with multiple scorers
scorers = {
"mse": SimpleScorer(mse, sign=1, kwargs={}),
"default": default_score
}
multi_scorer = _MultimetricScorer(scorers=scorers)
# Step 4: Generate sample data
X = np.random.rand(10, 2)
y = np.random.rand(10)
sample_weight = np.random.rand(10)
# Step 5: Fit the estimator and evaluate using the multi-scorer
estimator = SimpleEstimator()
estimator.fit(X, y)
scores = multi_scorer(estimator, X, y, sample_weight=sample_weight)
print("Scores:", scores)Expected Results
Expected result would be scores for each of the scorers without an error being raised.
Actual Results
AttributeError Traceback (most recent call last)
Cell In[6], line 4
2 estimator = SimpleEstimator()
3 estimator.fit(X, y)
----> 4 scores = multi_scorer(estimator, X, y, sample_weight=sample_weight)
6 print("Scores:", scores)
File ~/anaconda3/envs/scoring-311-2/lib/python3.11/site-packages/sklearn/metrics/_scorer.py:144, in _MultimetricScorer.__call__(self, estimator, *args, **kwargs)
142 if "sample_weight" in kwargs:
143 for name, scorer in self._scorers.items():
--> 144 if scorer._accept_sample_weight():
145 routed_params[name].score["sample_weight"] = kwargs[
146 "sample_weight"
147 ]
149 for name, scorer in self._scorers.items():
AttributeError: 'function' object has no attribute '_accept_sample_weight'
Versions
The `***` below is to obscure some personal details.
System:
python: 3.11.13 | packaged by conda-forge | (main, Jun 4 2025, 14:52:34) [Clang 18.1.8 ]
executable: /Users/***/anaconda3/envs/***/bin/python3.11
machine: macOS-15.5-arm64-arm-64bit
Python dependencies:
sklearn: 1.7.0
pip: 25.1.1
setuptools: 80.9.0
numpy: 2.2.6
scipy: 1.15.2
Cython: None
pandas: 2.3.0
matplotlib: None
joblib: 1.5.1
threadpoolctl: 3.6.0
Built with OpenMP: True
threadpoolctl info:
user_api: blas
internal_api: openblas
num_threads: 14
prefix: libopenblas
filepath: /Users/***/anaconda3/envs/***/lib/libopenblas.0.dylib
version: 0.3.29
threading_layer: openmp
architecture: VORTEX
user_api: openmp
internal_api: openmp
num_threads: 14
prefix: libomp
filepath: /Users/***/anaconda3/envs/***/lib/libomp.dylib
version: None
Activity
KoolDrip commentedon Jun 23, 2025
Hi @atharva-kelkar ! I'd like to work on this issue. Could you please assign it to me if it's still available?
atharva-kelkar commentedon Jun 23, 2025
@KoolDrip - I am not a maintainer for scikit-learn. If the developers find this worth pursuing, they can assign it to you. I am also happy to pick it up myself.
lesteve commentedon Jul 30, 2025
Thanks for the issue, I confirm that I can reproduce the behaviour of your snippet. It fails on 1.7 and seems to work fine on 1.6.2.
So I looked a little bit at it and I have only managed to get more confused. Now I am not sure whether this is supposed to work at all ...
I am looking at the Using multiple metric evaluation doc which is not crystal clear about it.
Here is a way to reproduce with
GridSearchCVthat seems to have a similar behaviour 1Traceback
Footnotes
I wanted to make sure this change affected public classes and not only private classes like
_MultimetricScorer. ↩atharva-kelkar commentedon Jul 30, 2025
Thanks @lesteve, what you are seeing makes sense to me. Under the hood,
_get_scorersinGridSearchCVinstantiates a_MultimetricScorerobject to handle scorers when multiple scorers are defined, so we come back to the original issue.As to what the intended behaviour should be -- I am not sure. It might make sense to have something like this check before checking for
_accept_sample_weightas an attribute because any function-scorer will definitely be missing this attribute.lesteve commentedon Jul 30, 2025
I think my snippet with
GridSearchCVis a variant of your issue, since in my case the error happened insklearn/model_selection/_search.py.It certainly looks like a few places in our code assumes that when
scoringis adict, thedictvalues are_BaseScorerobjects with a_accept_sample_weightattribute, which seems like a bug since in some places we have code that handles both_BaseScorerand Python function.@atharva-kelkar mostly out of curiosity, can you give a few more details about the context and how did you bump into this problem (I am guessing that you don't use
_MultimetricScorerdirectly since it's a private class but maybe you do ...)?atharva-kelkar commentedon Jul 30, 2025
I think I ran across it while running hyperparameter tuning like you're seeing (using
GridSearchCV) with multiple scorers of which one is the estimator's default scorer (which is a function, and not a class which inherits fromBaseScorer).Like you say, it's probably a bug because it's being handled inconsistently.
I am happy to pick this issue up if you want.
lesteve commentedon Jul 31, 2025
Thanks, go for it!
Right now I think the simplest fix would be to have a
sklearn.metrics._scorer._accept_sample_weightfunction that handles_MultimetricScorer,_BaseScorerand Python function, roughly something like this:You would also need to add tests.
It seems like the issue has been introduced in #30743 so cc @antoinebaker @ogrisel @adrinjalali for a second opinion.
Edit: looks like there is a
PassthroughScorerto handle as well ...adrinjalali commentedon Jul 31, 2025
First thing, this issue is only there if you don't enable metadata routing, i.e. this script works:
However, as you can see running the script,
score_funcdoes NOT getsample_weight, since it does not implement a correctget_metadata_routing()method. #30859 fixes some issues related to scorers surprisingly not raising whensample_weightis not provided though.As for this issue, when metadata routing is NOT enabled, I would have liked
check_scoringto handle all cases, and return something we know, as in a_BaseScorerof sorts._MultimetricScorershould also runcheck_scoringon all its children, which at the moment it doesn't.That cleans up quite a few places where we have repeated code and places where we accept
scoringas a constructor arg, but the issue here is that we have defined ascorerin our API as a callable with(estimator, X, y, ...)signature, which isn't really true anymore, since a simple function with that signature, does not know how to handle metadata. So ideally, the only way to create a scorer should be amake_scorer(func, ...)wherefuncis of signature(y_pred, y_true, ...), andmake_scorerhandles creating the right class with all required methods.antoinebaker commentedon Aug 5, 2025
Both approaches seem reasonable to me, I don't have a clear nor informed opinion about the best way to deal with the scorer API.
PassthroughScorerand maybe raising an error if not a valid scorer option, egscoringparam is better but more involved as there are several estimators to considerSome have special keywords (eg "loss" in
HistGradientBoostingClassifier), and some can handle a multimetric scorer (GridSearchCV).antoinebaker commentedon Aug 5, 2025
A third option would be to coerce the
self._scorersin_MultimetricScorerto be all_*Scorerobjects, eg converting a callable scorer into a_Scorerat__init__.atharva-kelkar commentedon Aug 5, 2025
I like the third option suggested by @antoinebaker the most because it also makes it easier to harmonize behaviour in the future.
For example: Change the
self._scorershere to beWhat do you think?
adrinjalali commentedon Aug 5, 2025
I thought of that third option. The issue is that we consider a
callablewith(estimator, X, y)signature, a properscorer, which is not really true, since such a function would be missing metadata routing machinery. I think we need to change our docs and mention that a scorer is only when you do amake_scorer(func, ...)and not a single function.atharva-kelkar commentedon Aug 5, 2025
That would be quite a big change, especially given that the default scorer for a lot of estimators is currently a
callable.However, I would be happy with this change in the docs + coercing each scorer in
_MultimetricScorerto be an object of class_Scorer.If you think that sounds ok, I will open a PR for the
make_scorercoercion in the__init__method ofMultimetricScorer.adrinjalali commentedon Aug 7, 2025
Right now there's no way to coerce every object in
MultimetricScorerto be aScorer, since we don't know what to do with a callable of the form(estimator, X, y).We need to have clear API expectations on scorers and metrics, and we don't right now.