-
-
Notifications
You must be signed in to change notification settings - Fork 26.5k
MAINT refactor scorer using _get_response_values #26037
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
b44dd9d
MAINT refactor scorer using _get_response_values
glemaitre 516f62f
Add __name__ for method of Mock
glemaitre d2fbee0
remove multiclass issue
glemaitre 29e5e87
make response_method a mandatory arg
glemaitre b645ade
Update sklearn/metrics/_scorer.py
glemaitre 3397c56
apply jeremie comments
glemaitre 092689a
Merge branch 'main' into is/18589_restart
glemaitre a33d995
Update sklearn/metrics/_scorer.py
glemaitre 15e9c37
Update sklearn/metrics/_scorer.py
glemaitre 205ecb2
Merge remote-tracking branch 'origin/main' into is/18589_restart
glemaitre 2aa8ab6
TST add new test for the multiclass case
glemaitre File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -18,8 +18,9 @@ | |
| # Arnaud Joly <[email protected]> | ||
| # License: Simplified BSD | ||
|
|
||
| from functools import partial | ||
| from collections import Counter | ||
| from inspect import signature | ||
| from functools import partial | ||
| from traceback import format_exc | ||
|
|
||
| import numpy as np | ||
|
|
@@ -64,20 +65,23 @@ | |
|
|
||
| from ..utils.multiclass import type_of_target | ||
| from ..base import is_regressor | ||
| from ..utils._response import _get_response_values | ||
| from ..utils._param_validation import HasMethods, StrOptions, validate_params | ||
|
|
||
|
|
||
| def _cached_call(cache, estimator, method, *args, **kwargs): | ||
| def _cached_call(cache, estimator, response_method, *args, **kwargs): | ||
| """Call estimator with method and args and kwargs.""" | ||
| if cache is None: | ||
| return getattr(estimator, method)(*args, **kwargs) | ||
| if cache is not None and response_method in cache: | ||
| return cache[response_method] | ||
|
|
||
| result, _ = _get_response_values( | ||
| estimator, *args, response_method=response_method, **kwargs | ||
| ) | ||
|
|
||
| if cache is not None: | ||
| cache[response_method] = result | ||
|
|
||
| try: | ||
| return cache[method] | ||
| except KeyError: | ||
| result = getattr(estimator, method)(*args, **kwargs) | ||
| cache[method] = result | ||
| return result | ||
| return result | ||
|
|
||
|
|
||
| class _MultimetricScorer: | ||
|
|
@@ -162,40 +166,13 @@ def __init__(self, score_func, sign, kwargs): | |
| self._score_func = score_func | ||
| self._sign = sign | ||
|
|
||
| @staticmethod | ||
| def _check_pos_label(pos_label, classes): | ||
| if pos_label not in list(classes): | ||
| raise ValueError(f"pos_label={pos_label} is not a valid label: {classes}") | ||
|
|
||
| def _select_proba_binary(self, y_pred, classes): | ||
| """Select the column of the positive label in `y_pred` when | ||
| probabilities are provided. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| y_pred : ndarray of shape (n_samples, n_classes) | ||
| The prediction given by `predict_proba`. | ||
|
|
||
| classes : ndarray of shape (n_classes,) | ||
| The class labels for the estimator. | ||
|
|
||
| Returns | ||
| ------- | ||
| y_pred : ndarray of shape (n_samples,) | ||
| Probability predictions of the positive class. | ||
| """ | ||
| if y_pred.shape[1] == 2: | ||
| pos_label = self._kwargs.get("pos_label", classes[1]) | ||
| self._check_pos_label(pos_label, classes) | ||
| col_idx = np.flatnonzero(classes == pos_label)[0] | ||
| return y_pred[:, col_idx] | ||
|
|
||
| err_msg = ( | ||
| f"Got predict_proba of shape {y_pred.shape}, but need " | ||
| f"classifier with two classes for {self._score_func.__name__} " | ||
| "scoring" | ||
| ) | ||
| raise ValueError(err_msg) | ||
| def _get_pos_label(self): | ||
| if "pos_label" in self._kwargs: | ||
| return self._kwargs["pos_label"] | ||
| score_func_params = signature(self._score_func).parameters | ||
| if "pos_label" in score_func_params: | ||
| return score_func_params["pos_label"].default | ||
| return None | ||
|
|
||
| def __repr__(self): | ||
| kwargs_string = "".join( | ||
|
|
@@ -311,14 +288,7 @@ def _score(self, method_caller, clf, X, y, sample_weight=None): | |
| score : float | ||
| Score function applied to prediction of estimator on X. | ||
| """ | ||
|
|
||
| y_type = type_of_target(y) | ||
| y_pred = method_caller(clf, "predict_proba", X) | ||
| if y_type == "binary" and y_pred.shape[1] <= 2: | ||
| # `y_type` could be equal to "binary" even in a multi-class | ||
| # problem: (when only 2 class are given to `y_true` during scoring) | ||
| # Thus, we need to check for the shape of `y_pred`. | ||
| y_pred = self._select_proba_binary(y_pred, clf.classes_) | ||
| y_pred = method_caller(clf, "predict_proba", X, pos_label=self._get_pos_label()) | ||
| if sample_weight is not None: | ||
| return self._sign * self._score_func( | ||
| y, y_pred, sample_weight=sample_weight, **self._kwargs | ||
|
|
@@ -369,26 +339,17 @@ def _score(self, method_caller, clf, X, y, sample_weight=None): | |
| if is_regressor(clf): | ||
| y_pred = method_caller(clf, "predict", X) | ||
| else: | ||
| pos_label = self._get_pos_label() | ||
| try: | ||
| y_pred = method_caller(clf, "decision_function", X) | ||
| y_pred = method_caller(clf, "decision_function", X, pos_label=pos_label) | ||
|
|
||
| if isinstance(y_pred, list): | ||
| # For multi-output multi-class estimator | ||
| y_pred = np.vstack([p for p in y_pred]).T | ||
| elif y_type == "binary" and "pos_label" in self._kwargs: | ||
| self._check_pos_label(self._kwargs["pos_label"], clf.classes_) | ||
| if self._kwargs["pos_label"] == clf.classes_[0]: | ||
| # The implicit positive class of the binary classifier | ||
| # does not match `pos_label`: we need to invert the | ||
| # predictions | ||
| y_pred *= -1 | ||
|
|
||
| except (NotImplementedError, AttributeError): | ||
| y_pred = method_caller(clf, "predict_proba", X) | ||
|
|
||
| if y_type == "binary": | ||
| y_pred = self._select_proba_binary(y_pred, clf.classes_) | ||
| elif isinstance(y_pred, list): | ||
| y_pred = method_caller(clf, "predict_proba", X, pos_label=pos_label) | ||
| if isinstance(y_pred, list): | ||
| y_pred = np.vstack([p[:, -1] for p in y_pred]).T | ||
|
|
||
| if sample_weight is not None: | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
why is this not simply replacing
getattrwith_get_response_values?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It is a change requested by @jeremiedbb: #26037 (comment)
It makes the code more readable as @jeremiedbb argued (with a larger diff).