Skip to content

Scoring functions don't know classes_ #6231

Open

Description

@pkch

Moving the discussion with @amueller from pydata/patsy#77 (comment).

Proposing to:

  • add an optional 'labels' argument to log_loss
  • add an argument to make_scorer to enable passing labels argument to the custom loss function

Related to this - perhaps also allow make_scorer's need_threshold = True to be used for non-binary classification problems. Not sure why it's limited to binary. Totally meaningful for multi-class situations, where the metric might use the decision function to evaluate based on the rank order or something (for example, SVC doesn't have a cheap predict_proba, but has a cheap decision_function, so it would allow it to be used with rank-based metris). From make_scorer perspective, it just seems like a completely arbitrary restriction because it shouldn't care about what the custom loss function does with the decision_function output.

Activity

  1. jnothman commented on Jan 26, 2016

    @jnothman
    Member

    Responding to that second dot point only, make_scorer will automatically
    pass on any additional kwargs.

    On 26 January 2016 at 15:32, pkch [email protected] wrote:

    Moving the discussion from github/pydata/77.

    Proposing to:

    • add an optional 'labels' argument to log_loss
    • add an argument to make_scorer to enable passing labels argument to
      the custom loss function

    Related to this - perhaps also allow make_scorer's need_threshold = True
    to be used for non-binary classification problems. Not sure why it's
    limited to binary. Totally meaningful for multi-class situations, where the
    metric might use the decision function to evaluate based on the rank order
    or something (for example, SVC doesn't have a cheap predict_proba, but
    has a cheap decision_function, so it would allow it to be used with
    rank-based metris). From make_scorer perspective, it just seems like a
    completely arbitrary restriction because it shouldn't care about what the
    custom loss function does with the decision_function output.

    —
    Reply to this email directly or view it on GitHub
    #6231.

  2. pkch commented on Jan 28, 2016

    @pkch
    Author

    @jnothman - I don't see how it would work. I meant that the when the classifier finishes training, its classes_ attribute should be passed to the custom loss function. This would help avoid calling LabelEncoder inside the custom loss function (which is required to match the unlabeled np.ndarray returned by predict_proba with the labels in the true y).

    make_scorer can only pass additional kwargs to the custom loss function if these arguments are known at the time make_scorer is called. But make_scorer is called to create a scorer, which is to be used on arbitrary future datasets, with arbitrary future classifiers. The class labels won't be known until the classifier is trained on a particular dataset.

    On another thought, if sklearn were to return DataFrame instead of np.ndarray this would be unnecessary. But I doubt it's in the plans?

  3. amueller commented on Oct 7, 2016

    @amueller
    Member

    +1 on adding labels to all metrics.

    And I agree this is an issue with the current design of the scorers. I think the classifiers should actually pass the classes_ to the scorer. There is even more issues with this, if this happens in cross-validation, for example, as different folds might have different classes, so we might want to tell all classifiers what the classes are (but that proposal was rejected a while ago because it really clutters the API).

    I'm fine with a fix on the scorer level, though. The scorers could actually inspect the classes_ attribute and act accordingly. This is somewhat of a big API change though. I'd be happy to see a test and PRs though.

    This relates closely to how we compute the R^2 by the way, but that is harder to fix. The R^2 should use the training set mean, not the test set mean, but that's unknown to the scorer. Getting classes_ in the call from scorer is easy, but the R^2 computation is hard, as the model doesn't actually store the class mean :-(

    Ideally I'd fix both issues in one go, but I'm not sure how to do that.

  4. changed the title [-]Scoring functions[/-] [+]Scoring functions don't know classes_[/+] on Oct 7, 2016
  5. added this to the 0.19 milestone on Oct 7, 2016
  6. amueller commented on Oct 7, 2016

    @amueller
    Member

    I feel this is pretty important, as currently results can be pretty wrong if not all classes are present in a test set.

    On second thought, I'm not sure what the right way to handle this is, though. Should we warn or error if macro-average is requested and not all classes are present?

  7. jnothman commented on Oct 8, 2016

    @jnothman
    Member

    I'd be interested in seeing scorers access classes_ to pass that on to
    capable metrics...

    On 8 October 2016 at 05:30, Andreas Mueller [email protected]
    wrote:

    +1 on adding labels to all metrics.

    And I agree this is an issue with the current design of the scorers. I
    think the classifiers should actually pass the classes_ to the scorer.
    There is even more issues with this, if this happens in cross-validation,
    for example, as different folds might have different classes, so we might
    want to tell all classifiers what the classes are (but that proposal was
    rejected a while ago because it really clutters the API).

    I'm fine with a fix on the scorer level, though. The scorers could
    actually inspect the classes_ attribute and act accordingly. This is
    somewhat of a big API change though. I'd be happy to see a test and PRs
    though.

    —
    You are receiving this because you were mentioned.
    Reply to this email directly, view it on GitHub
    #6231 (comment),
    or mute the thread
    https://github.com/notifications/unsubscribe-auth/AAEz6-Xq3GVCuOYch82zcOeF0dOtVBZ6ks5qxo_fgaJpZM4HMN5L
    .

  8. modified the milestones: 0.19, 0.20 on Jun 12, 2017
  9. jnothman commented on Jun 19, 2017

    @jnothman
    Member

    Re my comment at #9144 that scorer objects should look at the set of classes before cv, we should also consider how this might work with nested CV...

  10. amueller commented on Jun 20, 2017

    @amueller
    Member

    Hm so we make labels a required parameter (with deprecation)?

    and do we want to store the labels in the scorer actually? we can also just make it a required argument of the __call__ and always provide it in GridSearchCV and cross_val_score etc.

    In general this problem also happens for the score method of GridSearchCV, where we don't have labels... but we stored them in fit... but these where the training labels. But I guess that's the best we can do?

  11. amueller commented on Jun 20, 2017

    @amueller
    Member

    If we don't pass the labels along with X and y, then doing it for the built-in ones and the make_scorer ones would be quite different.

  12. 18 remaining items

  13. modified the milestones: 0.22, 1.0 on Oct 17, 2019
  14. adrinjalali commented on Aug 22, 2021

    @adrinjalali
    Member

    Moving this to 2.0, this needs somebody to pay attention to it though.

  15. modified the milestones: 1.0, 2.0 on Aug 22, 2021
  16. nsp121 commented on Jun 7, 2024

    @nsp121

    Hi all,
    I am recently reading Advances in Financial Machine Learning and this bug is discussed here. I cannot find any links to '2.0' mentioned above. I wanted to ask the community, has a smarter person than me come up with a solution to this yet?

    Context:

    1. Scoring functions do not know classes_, as a consequence of sklearn’s reliance on numpy arrays rather than pandas series: https://github.com/scikit- learn/scikit-learn/issues/6231
    2. cross_val_score will give different results because it passes weights to the fit method, but not to the log_loss method: https://github.com/scikit- learn/scikit-learn/issues/9144
  17. adrinjalali commented on Jun 10, 2024

    @adrinjalali
    Member

    @glemaitre as for the scorers, don't we support labels in some cases now? I guess the scorer can now use classes_ to pass as labels?

  18. glemaitre commented on Jun 10, 2024

    @glemaitre
    Member

    If the function support labels then we can pass it when calling make_scorer. However, we are not consistent regarding the labels parameter in the different scoring functions.

  19. adrinjalali commented on Jun 10, 2024

    @adrinjalali
    Member

    So I guess a next step here is to add labels to all scoring functions where it can be relevant?

  20. amueller commented on Jun 13, 2024

    @amueller
    Member

    Hm that would fix the issue in cross-validation with different classes in different test sets, but if there are different classes in the training set, it's still tricky, right?

  21. nelsonpeaceAB commented on Jun 25, 2024

    @nelsonpeaceAB

    Hi folks
    Sorry to chase, just wanted to keep this issue active. Let me know if I can assist. Seems like an important one to me. (correct me if I am wrong)

    Nels

  22. nsp121 commented on Jul 22, 2024

    @nsp121
  23. AhmedThahir commented on Jan 26, 2025

    @AhmedThahir

    Any updates?

  24. nsp121 commented on Jan 26, 2025

    @nsp121
  25. lorentzenchr commented on Mar 16, 2026

    @lorentzenchr
    Member
    from inspect import signature
    from sklearn.metrics.tests.test_common import CLASSIFICATION_METRICS, CONTINUOUS_CLASSIFICATION_METRICS
    
    [s for s in CMETRICS.values() if len({"labels", "pos_label"} & set(signature(s).parameters.keys()))==0]

    gives

    [<function sklearn.metrics._classification.accuracy_score(y_true, y_pred, *, normalize=True, sample_weight=None)>,
     <function sklearn.metrics._classification.balanced_accuracy_score(y_true, y_pred, *, sample_weight=None, adjusted=False)>,
     functools.partial(<function balanced_accuracy_score at 0x121f7ee80>, adjusted=True),
     functools.partial(<function accuracy_score at 0x121f7dc60>, normalize=False),
     <function sklearn.metrics.tests.test_common.<lambda>(*args, **kwargs)>,
     <function sklearn.metrics._classification.hamming_loss(y_true, y_pred, *, sample_weight=None)>,
     <function sklearn.metrics._classification.zero_one_loss(y_true, y_pred, *, normalize=True, sample_weight=None)>,
     functools.partial(<function zero_one_loss at 0x121f7e3e0>, normalize=False),
     <function sklearn.metrics._classification.matthews_corrcoef(y_true, y_pred, *, sample_weight=None)>,
     <function sklearn.metrics._ranking.coverage_error(y_true, y_score, *, sample_weight=None)>,
     <function sklearn.metrics._ranking.label_ranking_loss(y_true, y_score, *, sample_weight=None)>,
     <function sklearn.metrics._ranking.label_ranking_average_precision_score(y_true, y_score, *, sample_weight=None)>,
     <function sklearn.metrics._ranking.ndcg_score(y_true, y_score, *, k=None, sample_weight=None, ignore_ties=False)>,
     <function sklearn.metrics._ranking.dcg_score(y_true, y_score, *, k=None, log_base=2, sample_weight=None, ignore_ties=False)>]
    

    Accuracy does not need a label argument.

    Hm that would fix the issue in cross-validation with different classes in different test sets, but if there are different classes in the training set, it's still tricky, right?

    I think a general *CV meta-estimator won't work in that case. Specialized ones, like LogisticRegressionCV, are now able to do that.

    What is left to do for this issue?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions