Repository navigation
FIX LogisticRegressionCV.score and _BaseScorer metadata routing - #30859
Conversation
| err_msg = re.escape( | ||
| "[sample_weight] are passed but are not explicitly set as requested or not" | ||
| " requested for _Scorer.score, which is used within test.score. Call" | ||
| " `_Scorer.set_score_request({metadata}=True/False)` for each" |
There was a problem hiding this comment.
we can replace _Scorer with __repr__ once #30946 is merged.
| """ | ||
|
|
||
| # TODO(1.9): remove this when sample_weight is removed from the `score` signature | ||
| __metadata_request__score = {"sample_weight": metadata_routing.UNUSED} |
There was a problem hiding this comment.
this is to avoid set_score_request be present on this class
There was a problem hiding this comment.
Do you mean that a LogisticRegressionCV instance would not have a set_score_request method ?
I probably misunderstand because in this PR:
logreg = LogisticRegressionCV()
hasattr(logreg, "set_score_request") # TrueThere was a problem hiding this comment.
#32111 solves the related issue. The method is not removed (cause it can't be since it exists in the parent class), but it will raise with any input with that PR.
There was a problem hiding this comment.
Ah okay!
But currently in this PR, set_score_request does not raise if we pass sample_weight:
model = LogisticRegressionCV(cv=5, max_iter=1000)
model.set_score_request(sample_weight=True)
get_routing_for_object(model)
{'$self_request': {'fit': {'sample_weight': None}, 'score': {'sample_weight': True}}, ...}I would have assumed that the __metadata_request__score class default was to prevent sample_weight from showing up in the LogisticRegressionCV.set_score_request signature (and thus raising if we provided sample_weight) ?
There was a problem hiding this comment.
Here, model.set_score_request(sample_weight=True) still adds the self request to the router ('score': {'sample_weight': True), and also to fit.
But LogisticRegressionCV.fit (as score) also only routes sample_weight. It doesn't use it itself.
So maybe the consistent action would be to remove the self request from the router and also deprecate sample_weight as a positional argument from fit?
There was a problem hiding this comment.
@antoinebaker yes, but the fix for this is in #32111 , which I'll finish to move to "ready for review"
@StefanieSenger yes, happy to have that in a separate PR though, didn't want to expand this PR to concerns on fit
There was a problem hiding this comment.
But LogisticRegressionCV.fit (as score) also only routes sample_weight
No, I don't know anymore why I thought this. It uses sample_weight internally. No need for a new PR.
| score_method=self._score_func, | ||
| ignore_params={"y_true", "y_pred"}, |
There was a problem hiding this comment.
we explicitly pass the _score_func so that the right metadata can be deducted from its signature.
And we need to ignore y_true and y_pred in that process.
There was a problem hiding this comment.
Do we need to ignore y_prob, y_proba, y_score, labels_true, labels_pred, pred_decision as well ? (Some of the various names the first two args of a score function can have). Maybe an easier way to skip them all would be to ignore the first two positional arguments of the score function ?
There was a problem hiding this comment.
I don't feel safe skipping the first 2 params. but adding some more to the list.
|
@OmarManzoor @antoinebaker this is ready for review now. |
OmarManzoor
left a comment
There was a problem hiding this comment.
Thank you for the PR @adrinjalali
antoinebaker
left a comment
There was a problem hiding this comment.
A first round of reviews, but from my limited understanding of the metadata routing API, I probably don't get all the logic right 😉
| score_method=self._score_func, | ||
| ignore_params={"y_true", "y_pred"}, |
There was a problem hiding this comment.
Do we need to ignore y_prob, y_proba, y_score, labels_true, labels_pred, pred_decision as well ? (Some of the various names the first two args of a score function can have). Maybe an easier way to skip them all would be to ignore the first two positional arguments of the score function ?
| cls._build_request_for_signature( | ||
| method_name=method, | ||
| method_obj=score_method if score_method != "score" else None, | ||
| ignore_params=ignore_params, | ||
| ), |
There was a problem hiding this comment.
Out of curiosity, why the generic _get_default_requests and _build_request_for_signature need to be modified specifically for scorers ? Is it because in general we rely on the method signature, but here for scorers we instead rely on the scorer._scorer_func signature ?
There was a problem hiding this comment.
If so, I am wondering if we should rather redefine _get_default_requests and _build_request_for_signature in _BaseScorer (instead of changing the _MetadataRequestermixin).
There was a problem hiding this comment.
we could do that, but then we'd be having quite a bit of copy/pasted code, and I think we rather not? But this makes me realise we should override _get_metadata_request in _BaseScorer instead.
There was a problem hiding this comment.
Perhaps we could modify _BaseScorer._get_metadata_request
if hasattr(self, "_metadata_request"):
requests = get_routing_for_object(self._metadata_request)
else:
requests = _get_default_requests_scorer(self)where the helper _get_default_requests_scorer would build the specific default requests for a scorer.
If I understand correctly, these would be simply pname=None for all valid pname in score_func signature, because they are no __metadata_request__* class default in scorers ?
But maybe it leads to too much duplicated code as you said.
| # TODO (1.9): remove in 1.9 | ||
| @_deprecate_positional_args(version="1.9") | ||
| def __call__(self, estimator, X, y_true, *, sample_weight=None, **kwargs): |
There was a problem hiding this comment.
Out of curiosity, why do we need to deprecate sample_weight as a positional arg ? Is it directly related to this PR or is it a general guideline ?
There was a problem hiding this comment.
sample_weight is nothing special here, it's just metadata passed down the line. There's no reason to have it explicitly in the signature, since it only complicates code.
|
From a sync discussion with @lesteve , related to #31599 This code should fail with the expected error message (to be checked against this PR) 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_1(y_pred, y_true, sample_weight=None):
print(f"sample_weight is None? {sample_weight is None}")
return 1
custom_scorer = make_scorer(score_func_1)
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=custom_scorer,
param_grid={"alpha": [0.1, 1, 10]},
refit=False,
)
gs.fit(X, y, sample_weight=sample_weight)EDIT The above code here gives: raise UnsetMetadataPassedError(
sklearn.exceptions.UnsetMetadataPassedError: [sample_weight] are passed but are not explicitly set as requested or not requested for _Scorer.score, which is used within GridSearchCV.fit. Call `_Scorer.set_score_request({metadata}=True/False)` for each metadata you want to request/ignore. See the Metadata Routing User guide <https://scikit-learn.org/stable/metadata_routing.html> for more information. |
| scorer1 = get_scorer("accuracy").set_score_request(sample_weight=False) | ||
| lr_cv1 = LogisticRegressionCV(scoring=scorer1, tol=3e-6, use_legacy_attributes=True) | ||
| lr_cv1.fit(X, y, **kwargs) | ||
|
|
||
| scorer2 = get_scorer("accuracy") | ||
| scorer2.set_score_request(sample_weight=True) | ||
| lr_cv2 = LogisticRegressionCV( | ||
| scoring=scorer2, | ||
| tol=3e-6, | ||
| use_legacy_attributes=True, | ||
| ) | ||
| scorer2 = get_scorer("accuracy").set_score_request(sample_weight=True) | ||
| lr_cv2 = LogisticRegressionCV(scoring=scorer2, tol=3e-6, use_legacy_attributes=True) |
There was a problem hiding this comment.
I think that we also need a test for the original snippet:
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 accuracyWhat's the behavior now with the default scorer ?
There was a problem hiding this comment.
In this case logreg_cv.score(X, y, sample_weight=sw) would raise since there are no requests set but sample weight is passed.
There was a problem hiding this comment.
Ah okay because LogisticRegressionCV.score uses the provided scoring. It actually behaves differently than all other CV estimators from linear_model: they all respect sample_weight at score time, regardless of metadata routing.
- RidgeCV inherits
scorefrom RegressorMixin and so always use R2 - RidgeClassifierCV inerit
scorefrom ClassifierMixin and so always use accuracy - LassoCV, ElasticNetCV, MultiTaskLassoCV, MultiTaskElasticNetCV, LarsCV, LassoLarsCV, OrthogonalMatchingPursuitCV don't expose a
scoringparameter (they optimize for a hardcoded objective). They all inheritscorefrom RegressorMixin and so always use R2
Actually I think that what LogisticRegressionCV does is better than Ridge(Classifier)CV . I think it's fair to expect that score uses what was provided as scoring. All other kind of CV meta-estimators do that.
Ridge(Classifier)CV doesn't because it's not really treated as meta-estimator, but it kind of is. So imo it should also use what was provided as scoring at score time. @adrinjalali what do you think ? I you agree I can open a dedicated issue and fixing that should make sure that the behavior is then the same as LogisticRegressionCV.
For the other linear model CV estimators there's nothing to be done since they don't have a scoring param. Arguably they maybe should have scoring, but that's another topic.
There was a problem hiding this comment.
It actually behaves differently than all other CV estimators from linear_model: they all respect sample_weight at score time, regardless of metadata routing.
At one point, when metadata routing is enabled by default, we don't need sample_weight to be passed the old way and we'll deprecate it from all the score methods and we can then only pass it via **score_params. In the course of this deprecation the other linear CV classes I think will resemble what LogisticRegressionCV is turning into with the current PR.
I think it's fair to expect that score uses what was provided as scoring.
These kind of expectations are very valuable for the discussion in #31413, if you want to engage there, @jeremiedbb. Having these kind of ideas will help refine what default routing should look like and move this endeavour forwards.
There was a problem hiding this comment.
yeah to me it'd make sense for the other CV objects to follow the same path as here, but as @StefanieSenger says, we shouldn't focus too much on the sample_weight parameter itself.
| model = TunedThresholdClassifierCV( | ||
| estimator, | ||
| cv="prefit", | ||
| refit=False, | ||
| scoring=get_scorer("balanced_accuracy").set_score_request(sample_weight=True), | ||
| ).fit(X, y, sample_weight=sample_weight) |
There was a problem hiding this comment.
same here: what happens with the default scorer ?
There was a problem hiding this comment.
same here, default scorer doesn't request sample weight, hence passing it would raise.
There was a problem hiding this comment.
The issue is that the scoring is used in the internal CV split of TunedThresholdClassifierCV.fit so the request for it needs to be set directly on it, even if the user needs to re-create the default logic to pass the scoring. This is annoying only for now. Once we have defined a default routing of metadata, we'd set this internally.
There was a problem hiding this comment.
Thanks @adrinjalali! I haven't reviewed the whole PR yet, but here are a few comments. I'll come back to this PR in the next few days (since it is scheduled as a milestone for the 1.9 release).
Edit: Now I've reviewed the whole PR. Apart from a few smaller comments, it looks fine to me.
| inspect.signature(getattr(cls, method)).parameters.items() | ||
| )[1:] | ||
|
|
||
| resolved_method: Callable = ( |
There was a problem hiding this comment.
Do we really need these type hints here, in the middle of the function code?
There was a problem hiding this comment.
this makes the code more readable, the type checker would detect if we accidentally would use a string instead of a callable etc. So I'd leave it. In general, I don't think we should argue against type hints, it's just that we don't have a policy of enforcing them. But I've never had a situation where I'd regret typehints.
| scorer1 = get_scorer("accuracy").set_score_request(sample_weight=False) | ||
| lr_cv1 = LogisticRegressionCV(scoring=scorer1, tol=3e-6, use_legacy_attributes=True) | ||
| lr_cv1.fit(X, y, **kwargs) | ||
|
|
||
| scorer2 = get_scorer("accuracy") | ||
| scorer2.set_score_request(sample_weight=True) | ||
| lr_cv2 = LogisticRegressionCV( | ||
| scoring=scorer2, | ||
| tol=3e-6, | ||
| use_legacy_attributes=True, | ||
| ) | ||
| scorer2 = get_scorer("accuracy").set_score_request(sample_weight=True) | ||
| lr_cv2 = LogisticRegressionCV(scoring=scorer2, tol=3e-6, use_legacy_attributes=True) |
There was a problem hiding this comment.
It actually behaves differently than all other CV estimators from linear_model: they all respect sample_weight at score time, regardless of metadata routing.
At one point, when metadata routing is enabled by default, we don't need sample_weight to be passed the old way and we'll deprecate it from all the score methods and we can then only pass it via **score_params. In the course of this deprecation the other linear CV classes I think will resemble what LogisticRegressionCV is turning into with the current PR.
I think it's fair to expect that score uses what was provided as scoring.
These kind of expectations are very valuable for the discussion in #31413, if you want to engage there, @jeremiedbb. Having these kind of ideas will help refine what default routing should look like and move this endeavour forwards.
| ignore_params={ | ||
| "y_true", | ||
| "y_pred", | ||
| "y_prob", | ||
| "y_proba", | ||
| "y_score", | ||
| "labels_true", | ||
| "labels_pred", | ||
| }, |
There was a problem hiding this comment.
I think we should document these param names are excluded from the routing mechanism in custom scorers in examples/miscellaneous/plot_metadata_routing.py.
There was a problem hiding this comment.
I think that would add it to the "official API". We haven't had an issue regarding this so far, and if we make this public API, we should also expose this as a configurable thing, which we can do, but probably not here, and not until it's needed.
| """ | ||
|
|
||
| # TODO(1.9): remove this when sample_weight is removed from the `score` signature | ||
| __metadata_request__score = {"sample_weight": metadata_routing.UNUSED} |
There was a problem hiding this comment.
Here, model.set_score_request(sample_weight=True) still adds the self request to the router ('score': {'sample_weight': True), and also to fit.
But LogisticRegressionCV.fit (as score) also only routes sample_weight. It doesn't use it itself.
So maybe the consistent action would be to remove the self request from the router and also deprecate sample_weight as a positional argument from fit?
| model = TunedThresholdClassifierCV( | ||
| estimator, | ||
| cv="prefit", | ||
| refit=False, | ||
| scoring=get_scorer("balanced_accuracy").set_score_request(sample_weight=True), | ||
| ).fit(X, y, sample_weight=sample_weight) |
There was a problem hiding this comment.
The issue is that the scoring is used in the internal CV split of TunedThresholdClassifierCV.fit so the request for it needs to be set directly on it, even if the user needs to re-create the default logic to pass the scoring. This is annoying only for now. Once we have defined a default routing of metadata, we'd set this internally.
| def _get_class_level_metadata_request_values( | ||
| cls, | ||
| method_name: str, | ||
| method: Callable | None = None, | ||
| ignore_params: Iterable[str] | None = None, | ||
| ): |
There was a problem hiding this comment.
Can we add a dedicated unit test for _get_class_level_metadata_request_values with a little dummy class?
| ) | ||
| # transfer the metadata request | ||
| instance._metadata_request = scorer._get_metadata_request() | ||
| instance._metadata_request = scorer.get_metadata_routing() |
There was a problem hiding this comment.
For simplicity, can we leave this as is? We also have #31695 where we try to de-tangle this logic for readability.
There was a problem hiding this comment.
They have different meanings semantically, and as long as we don't have #31395 I think we should stick to what makes more sense here, even though they're identical in this particular case.
There was a problem hiding this comment.
| requests = cls._get_class_level_metadata_request_values(method_name) |
This diff doesn't render correctly. What I mean is to replace method with method_name, since this positional arg has changed its param name.
Also below.
There was a problem hiding this comment.
| requests=self._get_class_level_metadata_request_values(method_name), |
| kwargs, (_, _), (scorer, _), (_, _) = get_init_args( | ||
| metaestimator, sub_estimator_consumes=True | ||
| ) | ||
| if scorer is not None: | ||
| scorer.set_score_request(sample_weight=True) |
There was a problem hiding this comment.
I think we don't need to extract and set a request on this scorer, since it is not the scorer used in cross_validate below. Should we remove it from here for simplicity?
Co-authored-by: Stefanie Senger <[email protected]>
…into logregcv_score
adrinjalali
left a comment
There was a problem hiding this comment.
Thanks for the reviews, I've applied them.
| scorer1 = get_scorer("accuracy").set_score_request(sample_weight=False) | ||
| lr_cv1 = LogisticRegressionCV(scoring=scorer1, tol=3e-6, use_legacy_attributes=True) | ||
| lr_cv1.fit(X, y, **kwargs) | ||
|
|
||
| scorer2 = get_scorer("accuracy") | ||
| scorer2.set_score_request(sample_weight=True) | ||
| lr_cv2 = LogisticRegressionCV( | ||
| scoring=scorer2, | ||
| tol=3e-6, | ||
| use_legacy_attributes=True, | ||
| ) | ||
| scorer2 = get_scorer("accuracy").set_score_request(sample_weight=True) | ||
| lr_cv2 = LogisticRegressionCV(scoring=scorer2, tol=3e-6, use_legacy_attributes=True) |
There was a problem hiding this comment.
yeah to me it'd make sense for the other CV objects to follow the same path as here, but as @StefanieSenger says, we shouldn't focus too much on the sample_weight parameter itself.
| """ | ||
|
|
||
| # TODO(1.9): remove this when sample_weight is removed from the `score` signature | ||
| __metadata_request__score = {"sample_weight": metadata_routing.UNUSED} |
There was a problem hiding this comment.
@antoinebaker yes, but the fix for this is in #32111 , which I'll finish to move to "ready for review"
@StefanieSenger yes, happy to have that in a separate PR though, didn't want to expand this PR to concerns on fit
| ignore_params={ | ||
| "y_true", | ||
| "y_pred", | ||
| "y_prob", | ||
| "y_proba", | ||
| "y_score", | ||
| "labels_true", | ||
| "labels_pred", | ||
| }, |
There was a problem hiding this comment.
I think that would add it to the "official API". We haven't had an issue regarding this so far, and if we make this public API, we should also expose this as a configurable thing, which we can do, but probably not here, and not until it's needed.
| ) | ||
| # transfer the metadata request | ||
| instance._metadata_request = scorer._get_metadata_request() | ||
| instance._metadata_request = scorer.get_metadata_routing() |
There was a problem hiding this comment.
They have different meanings semantically, and as long as we don't have #31395 I think we should stick to what makes more sense here, even though they're identical in this particular case.
| inspect.signature(getattr(cls, method)).parameters.items() | ||
| )[1:] | ||
|
|
||
| resolved_method: Callable = ( |
There was a problem hiding this comment.
this makes the code more readable, the type checker would detect if we accidentally would use a string instead of a callable etc. So I'd leave it. In general, I don't think we should argue against type hints, it's just that we don't have a policy of enforcing them. But I've never had a situation where I'd regret typehints.
StefanieSenger
left a comment
There was a problem hiding this comment.
Nice, thanks for the improvements, @adrinjalali!
I've only got one nit comment. Apart from this that looks good. Approving.
Co-authored-by: Stefanie Senger <[email protected]>
…30859) Co-authored-by: Omar Salman <[email protected]> Co-authored-by: Stefanie Senger <[email protected]>
Fixes #30817
Depends on #31891, #31898
Two issues fixed in this PR:
LogisticRegressionCVhad asample_weightarg in itsscore, which makes it a consumer of it, while being a router. This PR removessample_weightas a consumer arg from that method_BaseScorerwasn't implementing aget_metadata_routingand as a result the default implementation wasn't correctly detectingsample_weightin the__call__signature of those scorersNeeds tests and refining the error message regarding
scorer.__call__cc @Dalesrox, @antoinebaker