Repository navigation
FEAT (alt3) allow setting auto routed strategy on objects - #31413
Conversation
There was a problem hiding this comment.
I have looked through this PR and commented a bit, some questions, some suggestions for improvement.
As I think I have missed this: What is the difference in usage for the users between this PR, and the previous version of defining an auto request strategy (#31401)? Edit from 5 days later: I of cause meant the difference between this PR and what #31401 was supposed to become, not what it is.
| def actualize_auto_requests(self): | ||
| for method in SIMPLE_METHODS: | ||
| getattr(self, method).actualize_auto_requests() | ||
| return self |
There was a problem hiding this comment.
For simplicity, could this be a private method instead?
I don't think many people would really want to use such a low-level method.
I believe making it possible to use get_metadata_routing().{method_name}.add_auto_request() in combination with get_routing_for_object(obj) gives enough room for any fine tuning and inspection and exposing this intermediate step could be confusing and requires too much explaining of when it's useful.
There was a problem hiding this comment.
I don't think it matters. We have documented in the example file how people should be using it anyways.
There was a problem hiding this comment.
I might be misunderstanding, but I don’t see actualize_auto_requests documented in the example file.
My thought was that when third party developers call add_auto_request() and also use get_routing_for_object() (which internally calls actualize_auto_requests()) there’s no clear external use case for calling this method directly.
There was a problem hiding this comment.
I don't see actualize_auto_requests in plot_metadata_routing.py either, or is it documented elsewhere ?
If it's public we should add a docstring I guess.
| elif isinstance(obj, MetadataRouter): | ||
| self._self_request = deepcopy(obj._self_request) |
There was a problem hiding this comment.
Could you please explain this part, @adrinjalali:
elif isinstance(obj, MetadataRouter):
self._self_request = deepcopy(obj._self_request)If a MetadataRouter object is passed to another MetadataRouter object' add_self_request method, the latter overtakes the former's _self_request attribute? In which case would this happen?
There was a problem hiding this comment.
it really shouldn't happen. This only happens in our tests and here it covers the edge case if it happens; but I don't think it would.
There was a problem hiding this comment.
I guess this why the test case above was removed.
I find a method clearer to understand when there is "only one way" to call it and strict about the argument type. If I understand correctly here obj should be a router (eg meta-estimator) instance, so maybe only implement this case and raise error otherwise ?
There was a problem hiding this comment.
I agree, @antoinebaker, but also I don't really understand the impact of this addition.
For now, I have added a TODO comment to remind us to clean this up.
Also, _self_request may be None and I added a condition here to guard against this in d450338.
There was a problem hiding this comment.
I have seen this all fails on codecov, so we don't even user it internally and can probably safely remove it, which I did in f0b5c4e.
| # 1. Class-level defaults using `__metadata_request__method` class attributes, | ||
| # which set default request values for all instances of a class, and can even | ||
| # remove a metadata from the metadata routing machinery if necessary. | ||
| # 2. Instance-level defaults via the `add_auto_request` method, which would only | ||
| # request the metadata if ``set_config(metadata_request_policy="auto")`` is | ||
| # set. |
There was a problem hiding this comment.
Let's also document right here that the instance level requests will overwrite the class level requests and can be overwritten by user-set requests.
Co-authored-by: Stefanie Senger <[email protected]>
adrinjalali
left a comment
There was a problem hiding this comment.
As I think I have missed this: What is the difference in usage for the users between this PR, and the previous version of defining an auto request strategy (#31401)?
There's no difference for users. The difference is only on how it's implemented.
| def actualize_auto_requests(self): | ||
| for method in SIMPLE_METHODS: | ||
| getattr(self, method).actualize_auto_requests() | ||
| return self |
There was a problem hiding this comment.
I don't think it matters. We have documented in the example file how people should be using it anyways.
| elif isinstance(obj, MetadataRouter): | ||
| self._self_request = deepcopy(obj._self_request) |
There was a problem hiding this comment.
it really shouldn't happen. This only happens in our tests and here it covers the edge case if it happens; but I don't think it would.
|
Hello @adrinjalali and @StefanieSenger ! Sorry I think I'm a bit lost ;) How does this new mechanism allow to solve the original intent of #30887, ie to have a config where scorers and estimators always request For example, how could we implement a |
The idea is not to have something that automatically requests |
| if _auto_routing_enabled(): | ||
| if hasattr(requests, "actualize_auto_requests"): | ||
| requests.actualize_auto_requests() | ||
| if getattr(requests, "_self_request", None): | ||
| requests._self_request.actualize_auto_requests() |
There was a problem hiding this comment.
I guess here is where all the magic happens :)
The auto requests, defined at the instance level inside obj.get_metadata_routing(), are taken into consideration only when the auto request policy is enabled, and then added to the "default" requests, possibly overriding the class requests. The user can still specify requests afterwards. Did I get this right ?
There was a problem hiding this comment.
I believe so. This is at least how I also understood it.
There was a problem hiding this comment.
Thanks for your clarifications, @adrinjalali.
For example, how could we implement a Mixin so that for all sklearn estimators, if the fit method has sample_weight in its signature, and the metadata_request_policy="auto" config is enabled, then it will automatically add sample_weight to the fit request ?
I was thinking maybe something like combining available_if(_estimator_has("fit")) with inspect.signature(func) to set the class requests in a mixin could work? And maybe use the instance-level requests for a transition period until auto routing would be the default?
@antoinebaker I might be missing some context, but it seems you where asking whether setting class requests via mixins would be possible while auto metadata routing is not the default yet. Is such a roadmap existing, @adrinjalali?
| def actualize_auto_requests(self): | ||
| for method in SIMPLE_METHODS: | ||
| getattr(self, method).actualize_auto_requests() | ||
| return self |
There was a problem hiding this comment.
I might be misunderstanding, but I don’t see actualize_auto_requests documented in the example file.
My thought was that when third party developers call add_auto_request() and also use get_routing_for_object() (which internally calls actualize_auto_requests()) there’s no clear external use case for calling this method directly.
| if _auto_routing_enabled(): | ||
| if hasattr(requests, "actualize_auto_requests"): | ||
| requests.actualize_auto_requests() | ||
| if getattr(requests, "_self_request", None): | ||
| requests._self_request.actualize_auto_requests() |
There was a problem hiding this comment.
I believe so. This is at least how I also understood it.
It's certainly possible to inspect during runtime and do the magic, but I'd be opposed to the idea. I rather have the mixin be included only when we want to add the request, instead of checking the signature. If we want to check the signature and request metadata, then we can have a very different approach where metadata is always requested, no matter which metadata. I'm not opposed to that option, but that's a very different approach. I just don't want to special case |
|
Thanks for the clarification @adrinjalali and @StefanieSenger, I was confused about the goal of the auto request policy.
If I understand correctly, would you suggest the following plan to tackle #30887 ?
class AutoRequestSampleWeightFit():
def get_metadata_routing(self):
requests = super().get_metadata_routing()
requests.fit.add_auto_request("sample_weight")
return requests
# current policy: need the verbose requests
sklearn.set_config(enable_metadata_routing=True, metadata_request_policy="empty")
scaler.set_fit_request(sample_weight=True)
spline.set_fit_request(sample_weight=True)
logistic.set_fit_request(sample_weight=True)
logistic.set_score_request(sample_weight=True)
pipe.set_score_request(sample_weight=True)
# new policy: no need for requests, `sample_weight` in meta-estimator works out of the box
sklearn.set_config(enable_metadata_routing=True, metadata_request_policy="auto") |
|
Yep, that's how I see it @antoinebaker . |
StefanieSenger
left a comment
There was a problem hiding this comment.
I've applied your latest review comments, @antoinebaker. Thanks again.
From my side, this PR is ready to merge, approving.
Let's wait for @adrinjalali's final look at this.
| @pytest.mark.parametrize( | ||
| "metadata_request_policy, default_routing", | ||
| [ | ||
| ("auto", True), | ||
| ("class-level", False), | ||
| ], | ||
| ) | ||
| def test_auto_requests_disabled(metadata_request_policy, default_routing): | ||
| """Check correctness of _auto_requests_enabled.""" | ||
| with config_context(metadata_request_policy=metadata_request_policy): | ||
| assert _auto_requests_enabled() == default_routing |
There was a problem hiding this comment.
Certainly, good you caught this. :)
| def test_auto_requests_override_class_level_requests(): | ||
| """Test that instance-level auto requests override class-level default requests.""" | ||
|
|
||
| class DefaultRoutingEstimator(BaseEstimator): |
|
This is already over a year old. Let me know if you need a hand to finish review and finally merge. |
Thanks @lorentzenchr! This is in its final stages, ready to merge after @adrinjalali had a chance to react on my latest commits. |
|
I didn't see this before, but in the current implementation, auto-requests aren't really instance-level (even though we document that they are). The requests can be switched on and off on the same instance depending on the config. So they are not instance level like from sklearn import config_context
from sklearn.base import BaseEstimator
from sklearn.utils.metadata_routing import get_routing_for_object
class Est(BaseEstimator):
def fit(self, X, y, prop=None):
return self
def get_metadata_routing(self):
requests = super().get_metadata_routing()
requests.fit.add_auto_request("prop")
return requests
est = Est()
with config_context(metadata_request_policy="class-level"):
print("class-level:", get_routing_for_object(est).fit.requests.get("prop"))
# class-level: None
with config_context(metadata_request_policy="auto"):
print("auto:", get_routing_for_object(est).fit.requests.get("prop"))
# auto: TrueNow the question is, do we want to
Let's this not be a blocker. Let's merge and figure this out later in a follow-up PR. |
Updated the author credit in the metadata-routing feature documentation to include Stefanie Senger.
adrinjalali
left a comment
There was a problem hiding this comment.
Looks pretty good to me, with minor edits.
I like the new config name we came up with @StefanieSenger and going through the PR, it's very consistent with how we formulate the feature in the docs and docstrings.
| # %% | ||
| # Note that setting auto-requests on *composite* methods such as `fit_transform` or | ||
| # `fit_predict` will not have an effect. Their requests are the union of the underlying | ||
| # simple methods (`fit`+`transform`, `fit`+`predict`). Call `add_auto_request` (or | ||
| # `set_*_request`) on the simple methods instead. |
There was a problem hiding this comment.
I don't think this is true now, since we've merged this: https://github.com/scikit-learn/scikit-learn/pull/30869/changes
need to be double checked and verified
| return new | ||
|
|
||
| def actualize_auto_requests(self): | ||
| for method in SIMPLE_METHODS: |
There was a problem hiding this comment.
So TargetEncoder has:
router.add(
# This works, since none of {None, int, iterable} request any metadata
# and the machinery here would assign an empty MetadataRequest
# to it.
splitter=self.cv,
method_mapping=MethodMapping().add(caller="fit_transform", callee="split"),
)which makes me wonder, what to do here!!!
Also note the PR where we fixed the composite methods, and we fixed an issue where requests are also directly set on composite methods
adrinjalali
left a comment
There was a problem hiding this comment.
Thanks for taking this over @StefanieSenger . LGTM.
|
OMG it is finally merged! 🍾 Also many thanks to @antoinebaker for your reviews. |
This alternative allows the case for
DefaultRoutingClassifier4in the following script. I think I prefer this alternative to the other ones.cc @StefanieSenger @ogrisel @antoinebaker