Skip to content

_MultimetricScorer deals with _accept_sample_weights inconsistently #31599

Open

Description

@atharva-kelkar

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

  1. KoolDrip commented on Jun 23, 2025

    @KoolDrip

    Hi @atharva-kelkar ! I'd like to work on this issue. Could you please assign it to me if it's still available?

  2. atharva-kelkar commented on Jun 23, 2025

    @atharva-kelkar
    Author

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

  3. lesteve commented on Jul 30, 2025

    @lesteve
    Member

    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 GridSearchCV that seems to have a similar behaviour 1

    import numpy as np
    from sklearn.metrics import make_scorer, mean_squared_error
    from sklearn.linear_model import Ridge
    from sklearn.model_selection import GridSearchCV
    
    def score_func(estimator, X, y, sample_weight=None, **kws):
        return 1
    
    scorers = {
        "mse": make_scorer(mean_squared_error, greater_is_better=False),
        "default": score_func
    }
    
    rng = np.random.RandomState(0)
    X = rng.rand(10, 2)
    y = rng.rand(10)
    sample_weight = rng.rand(10)
    
    gs = GridSearchCV(Ridge(), scoring=scorers, param_grid={'alpha': [0.1, 1, 10]}, refit=False)
    gs.fit(X, y, sample_weight=sample_weight)
    Traceback
    ---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
    File /tmp/test.py:20
         17 sample_weight = rng.rand(10)
         19 gs = GridSearchCV(Ridge(), scoring=scorers, param_grid={'alpha': [0.1, 1, 10]}, refit=False)
    ---> 20 gs.fit(X, y, sample_weight=sample_weight)
    
    File ~/dev/scikit-learn/sklearn/base.py:1365, in _fit_context.<locals>.decorator.<locals>.wrapper(estimator, *args, **kwargs)
       1358     estimator._validate_params()
       1360 with config_context(
       1361     skip_parameter_validation=(
       1362         prefer_skip_nested_validation or global_skip_validation
       1363     )
       1364 ):
    -> 1365     return fit_method(estimator, *args, **kwargs)
    
    File ~/dev/scikit-learn/sklearn/model_selection/_search.py:964, in BaseSearchCV.fit(self, X, y, **params)
        961 X, y = indexable(X, y)
        962 params = _check_method_params(X, params=params)
    --> 964 routed_params = self._get_routed_params_for_fit(params)
        966 cv_orig = check_cv(self.cv, y, classifier=is_classifier(estimator))
        967 n_splits = cv_orig.get_n_splits(X, y, **routed_params.splitter.split)
    
    File ~/dev/scikit-learn/sklearn/model_selection/_search.py:915, in BaseSearchCV._get_routed_params_for_fit(self, params)
        905     routed_params = Bunch(
        906         estimator=Bunch(fit=params),
        907         splitter=Bunch(split={"groups": groups}),
        908         scorer=Bunch(score={}),
        909     )
        910     # NOTE: sample_weight is forwarded to the scorer if sample_weight
        911     # is not None and scorers accept sample_weight. For _MultimetricScorer,
        912     # sample_weight is forwarded if any scorer accepts sample_weight
        913     if (
        914         params.get("sample_weight") is not None
    --> 915         and self._check_scorers_accept_sample_weight()
        916     ):
        917         routed_params.scorer.score["sample_weight"] = params["sample_weight"]
        918 return routed_params
    
    File ~/dev/scikit-learn/sklearn/model_selection/_search.py:873, in BaseSearchCV._check_scorers_accept_sample_weight(self)
        871 if isinstance(scorers, _MultimetricScorer):
        872     for name, scorer in scorers._scorers.items():
    --> 873         if not scorer._accept_sample_weight():
        874             warnings.warn(
        875                 f"The scoring {name}={scorer} does not support sample_weight, "
        876                 "which may lead to statistically incorrect results when "
        877                 f"fitting {self} with sample_weight. "
        878             )
        879     return scorers._accept_sample_weight()
    
    AttributeError: 'function' object has no attribute '_accept_sample_weight'
    

    Footnotes

    1. I wanted to make sure this change affected public classes and not only private classes like _MultimetricScorer. ↩

  4. added
    Needs Investigation
    and removed
    Needs Triage
    on Jul 30, 2025
  5. atharva-kelkar commented on Jul 30, 2025

    @atharva-kelkar
    Author

    Thanks @lesteve, what you are seeing makes sense to me. Under the hood, _get_scorers in GridSearchCV instantiates a _MultimetricScorer object 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_weight as an attribute because any function-scorer will definitely be missing this attribute.

  6. lesteve commented on Jul 30, 2025

    @lesteve
    Member

    I think my snippet with GridSearchCV is a variant of your issue, since in my case the error happened in sklearn/model_selection/_search.py.

    It certainly looks like a few places in our code assumes that when scoring is a dict, the dict values are _BaseScorer objects with a _accept_sample_weight attribute, which seems like a bug since in some places we have code that handles both _BaseScorer and 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 _MultimetricScorer directly since it's a private class but maybe you do ...)?

  7. atharva-kelkar commented on Jul 30, 2025

    @atharva-kelkar
    Author

    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 from BaseScorer).

    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.

  8. lesteve commented on Jul 31, 2025

    @lesteve
    Member

    I am happy to pick this issue up if you want.

    Thanks, go for it!

    Right now I think the simplest fix would be to have a sklearn.metrics._scorer._accept_sample_weight function that handles _MultimetricScorer, _BaseScorer and Python function, roughly something like this:

    def _accept_sample_weight(scorer):
        if isinstance(scorer, _MultimetricScorer):
            return any(_accept_sample_weight(each) for each in scorer.values())
        elif isinstance(scorer, _BaseScorer):
            return "sample_weight" in signature(self._score_func).parameters
        else:
            return "sample_weight" in signature(score).parameters

    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 PassthroughScorer to handle as well ...

  9. adrinjalali commented on Jul 31, 2025

    @adrinjalali
    Member

    First thing, this issue is only there if you don't enable metadata routing, i.e. this script works:

    import numpy as np
    from sklearn.metrics import make_scorer, mean_squared_error
    from sklearn.linear_model import Ridge
    from sklearn.model_selection import GridSearchCV
    import sklearn
    
    sklearn.set_config(enable_metadata_routing=True)
    
    def score_func(estimator, X, y, sample_weight=None, **kws):
        print(f"sample_weight is None? {sample_weight is None}")
        return 1
    
    
    scorers = {
        "mse": make_scorer(mean_squared_error, greater_is_better=False).set_score_request(
            sample_weight=True
        ),
        "default": score_func,
    }
    
    rng = np.random.RandomState(0)
    X = rng.rand(10, 2)
    y = rng.rand(10)
    sample_weight = rng.rand(10)
    
    gs = GridSearchCV(
        Ridge().set_fit_request(sample_weight=True),
        scoring=scorers,
        param_grid={"alpha": [0.1, 1, 10]},
        refit=False,
    )
    gs.fit(X, y, sample_weight=sample_weight)

    However, as you can see running the script, score_func does NOT get sample_weight, since it does not implement a correct get_metadata_routing() method. #30859 fixes some issues related to scorers surprisingly not raising when sample_weight is not provided though.

    As for this issue, when metadata routing is NOT enabled, I would have liked check_scoring to handle all cases, and return something we know, as in a _BaseScorer of sorts. _MultimetricScorer should also run check_scoring on 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 scoring as a constructor arg, but the issue here is that we have defined a scorer in 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 a make_scorer(func, ...) where func is of signature (y_pred, y_true, ...), and make_scorer handles creating the right class with all required methods.

  10. antoinebaker commented on Aug 5, 2025

    @antoinebaker
    Member

    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.

    1. @lesteve seems a more straightforward and easy way to fix the issue on the short term, indeed adding PassthroughScorer and maybe raising an error if not a valid scorer option, eg
    def _accept_sample_weight(scorer):
        if isinstance(scorer, _MultimetricScorer):
            return any(_accept_sample_weight(each) for each in scorer.values())
        elif isinstance(scorer, _BaseScorer):
            return "sample_weight" in signature(self._score_func).parameters
        elif isinstance(scorer, _PassthroughScorer):
            return "sample_weight" in signature(self._estimator.score).parameters
        elif callable(scorer): # or maybe isinstance(scorer, FunctionType) ?
            return "sample_weight" in signature(score).parameters
        else:
           raise ValueError(f"{scorer=} should be a _MultimetricScorer, _BaseScorer, _PassthroughScorer or a callable. ")
    1. @adrinjalali on harmonizing and validating the scoring param is better but more involved as there are several estimators to consider
    from sklearn.utils import all_estimators
    from inspect import signature
    [name for name, klass in all_estimators() if "scoring" in signature(klass).parameters]
    ['GridSearchCV',
     'HistGradientBoostingClassifier',
     'HistGradientBoostingRegressor',
     'LogisticRegressionCV',
     'RFECV',
     'RandomizedSearchCV',
     'RidgeCV',
     'RidgeClassifierCV',
     'SequentialFeatureSelector',
     'TunedThresholdClassifierCV']
    

    Some have special keywords (eg "loss" in HistGradientBoostingClassifier), and some can handle a multimetric scorer (GridSearchCV).

  11. antoinebaker commented on Aug 5, 2025

    @antoinebaker
    Member

    A third option would be to coerce the self._scorers in _MultimetricScorer to be all _*Scorer objects, eg converting a callable scorer into a _Scorer at __init__.

  12. atharva-kelkar commented on Aug 5, 2025

    @atharva-kelkar
    Author

    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._scorers here to be

    self._scorers = self._make_consistent_scorers(scorers)
    
    @staticmethod
    def _make_consistent_scorers(scorers: dict) -> dict:
        for key, scorer in scorers.items():
            scorers[key] = make_scorer(scorer)
       return scorers
    

    What do you think?

  13. adrinjalali commented on Aug 5, 2025

    @adrinjalali
    Member

    I thought of that third option. The issue is that we consider a callable with (estimator, X, y) signature, a proper scorer, 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 a make_scorer(func, ...) and not a single function.

  14. atharva-kelkar commented on Aug 5, 2025

    @atharva-kelkar
    Author

    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 _MultimetricScorer to be an object of class _Scorer.

    If you think that sounds ok, I will open a PR for the make_scorer coercion in the __init__ method of MultimetricScorer.

  15. adrinjalali commented on Aug 7, 2025

    @adrinjalali
    Member

    Right now there's no way to coerce every object in MultimetricScorer to be a Scorer, 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.

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

    BugNeeds Investigationmodule:metrics

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions