Repository navigation
MNT Refactor and deprecate get_metadata_routing method in _MetadataRequester - #31695
StefanieSenger wants to merge 27 commits into
Conversation
| with pytest.warns(UserWarning, match="`transform` method which consumes metadata"): | ||
| rct = RoutingCustomTransformer( | ||
| estimator=CustomTransformer() | ||
| .set_fit_request(metadata=True) | ||
| .set_transform_request(metadata=True) | ||
| ) | ||
| rct.fit_transform(X=[[1]], metadata="metadata") |
There was a problem hiding this comment.
This test was added to make sure the warning is also shown when a transformer is not a pure consumer (but also a router). It refers to the change in sklearn.base.TransformerMixin.fit_transform.
| def test_default_requests(): | ||
| class OddEstimator(BaseEstimator): | ||
| def test_class_level_requests(): | ||
| class StubEstimator(BaseEstimator): |
There was a problem hiding this comment.
I'm renaming OddEstimator because the old naming implies we are intentionally demonstrating wrong usage, but that's not our purpose here.
| @config_context(enable_metadata_routing=True) | ||
| def test_default_requests(): | ||
| class OddEstimator(BaseEstimator): | ||
| def test_class_level_requests(): |
There was a problem hiding this comment.
I'm renaming test_default_requests because the term "default" is not referring to default / auto routing here and could be mis-understood. What is meant are the class level requests.
|
Log of my though process (that hopefully helps me move forwards): The de-coupeling of I wonder if we want to fully automate the setting of self requests, or if it should be integrated in Since then I need to pass an object into But potentially, those could both be merged into the same param, since passing |
|
I understood that this PR cannot do much about the double-handling of |
|
I've experimented with my above idea to add a self-request automatically to routers, but it fails for routers that are pure routers but not also consumers. Given that, I no longer see a benefit in removing or refining the If that input is done by calling Also, the original change of this PR, the de-tangling of At this point, I am tempted to think this refactoring is complete, unless there is some specific thing that we want to do with This PR makes the code more readable, because we can clearly see if we deal with a consumer based on the method called on an object. It also adds some improvements to the internal and the API docs and personally, it has given me more insights and more ideas for refactorings (which I will open separate PRs for). What is left that I will go through our docs and examples to check whether the right method is used everywhere. I will do that and then un-draft this PR. Do you consider it complete, @adrinjalali? |
| MetadataRouter | ||
| ~~~~~~~~~~~~~~ | ||
|
|
||
| The ``MetadataRouter`` objects are constructed via a `get_metadata_routing` method, |
There was a problem hiding this comment.
The
MetadataRouterobjects are constructed via aget_metadata_routingmethod
@adrinjalali, Do you think it makes sense to rename get_metadata_routing into get_metadata_router?
That would be more precise and we spare people to wonder about whether there is a difference between "metadata router" and "metadata routing". In fact, this method returns a MetadataRouter object.
That would be for a new PR and could be done without deprecation (because we are still in experimental stage), I believe?
There was a problem hiding this comment.
I wouldn't mind the rename, but needs to go through a deprecation cycle. Maybe a different PR.
There was a problem hiding this comment.
I think the renaming would be very useful for people unfamiliar with metadata routing like me: _get_metadata_request returns a MetadataRequest, get_metadata_router returns a MetadataRouter, all is clear. So +1 for a follow-up PR with the renaming !
| Consumer-only classes such as simple estimators return a serialized | ||
| version of this class as the output of `get_metadata_routing()`. | ||
|
|
There was a problem hiding this comment.
That's not true (anymore).
get_routing_for_object(), _get_metadata_request() and get_metadata_routing() all return unserialised output.
|
|
||
| return requests | ||
|
|
||
| def get_metadata_routing(self): |
There was a problem hiding this comment.
A side effect of this change is that this method won't be displayed in the docs for the consumers anymore. I don't think it's too bad, since we want users to use get_routing_for_object anyways.
There was a problem hiding this comment.
I think we should also do a single release deprecation cycle for this (shorter than usual).
…/scikit-learn into refactor_router_requester
StefanieSenger
left a comment
There was a problem hiding this comment.
Thanks for reviewing, @antoinebaker! I have modified a bit according to your review. Awaiting the next pass. :)
| ``_MetadataRequester`` class, and ``BaseEstimator`` inherits from this mixin. | ||
| This mixin also implements the ``get_metadata_routing``, which meta-estimators | ||
| need to override, but it works for simple consumers as is. | ||
| This mixin also implements a ``_get_metadata_request`` method. |
There was a problem hiding this comment.
Yes, I think you are right. However, returning the self requests is not the primary purpose of having _get_metadata_request for pure routers.
I will try to explain to the best of my current understanding:
All estimator objects have their own _get_metadata_request method. I think it is easier to just have the method than to define some distinction between routers and consumers, because many can be both, pure routers are seldom and being a consumer depends on whether a set_{method}_request method is set on them or not.
When set_fit_request is called for instance, _get_metadata_request method is used to check whether they could potentially consume metadata by checking the signatures of their methods and adding class level settings (see _get_class_level_metadata_request_values therefore). And thewhile, the estimator builds a _metadata_request attribute that stores all that information. If I understand correctly, this is identical to the self requests.
When we call _get_metadata_request on a router, it returns that stored object. It might have been updated via the user code in the meantime.
So _get_metadata_request can serve two different purposes, and the first one is needed for any estimator, the second one is actually only interesing for consumers.
I also find that very confusing. I wonder if a solution could be to make the if-else distinction in _get_metadata_request in other places instead and reduce the functionality of _get_metadata_request to either only build the MetadataRequest object or to retrieve it. In that case, we could also rename it. What do you think, @antoinebaker and @adrinjalali? (I am thinking about a future PR of cause.)
| # for other reasons. | ||
| if hasattr(obj, "get_metadata_routing"): | ||
|
|
||
| # TODO(1.9): remove when get_metadata_routing is removed |
There was a problem hiding this comment.
Yes, I will add that. Thanks!
| ): | ||
| raise AttributeError( | ||
| f"The given object ({_obj.__class__.__name__!r}) needs to either" | ||
| " implement the routing method `get_metadata_routing` or be a" |
There was a problem hiding this comment.
Oh my, when I added that condition, it had made sense to me and now I cannot explain it anymore ... 😅
I now think you are right and I have removed the new condition, @antoinebaker.
On the question whether we ever call process_routing on MetadataRouter instances: It seems we do that in some of the tests in the test_metaestimators_metadata_routing.py module. But we shouldn't modify code just to match a test. Instead, I think the tests would need to be different / less abstract.
No, unfortunately, we won't be able to do that, since both objects will have the It might be that pure routers (that do not have self requests), don't need it and in this case, they could maybe not inherit from the |
antoinebaker
left a comment
There was a problem hiding this comment.
Here a second pass with minor comments / suggestions !
| assert not len(get_routing_for_object(NonConsumingClassifier()).fit.requests) | ||
| assert_request_is_empty(NonConsumingClassifier().get_metadata_routing()) | ||
| assert_request_is_empty(NonConsumingClassifier()._get_metadata_request()) |
There was a problem hiding this comment.
Maybe the following is clearer
ncc_request = get_routing_for_object(NonConsumingClassifier())
assert ncc_request.fit.requests == {}
assert_request_is_empty(ncc_request)
| @pytest.mark.parametrize("cv", ALL_SPLITTERS, ids=[str(cv) for cv in ALL_SPLITTERS]) | ||
| def test_splitter_get_metadata_routing(cv): | ||
| """Check get_metadata_routing returns the correct MetadataRouter.""" | ||
| assert hasattr(cv, "get_metadata_routing") | ||
| metadata = cv.get_metadata_routing() | ||
| assert hasattr(cv, "_get_metadata_request") | ||
| metadata = cv._get_metadata_request() |
There was a problem hiding this comment.
In line with the other test modifications maybe rename:
test_splitter_get_metadata_routing->test_splitter__get_metadata_request- "Check _get_metadata_request returns the correct MetadataRequest."
metadata->cv_request
| if ( | ||
| hasattr(method_obj, "__call__") or isinstance(method_obj, property) | ||
| ) and not _is_deprecated(method_obj): |
There was a problem hiding this comment.
Does this mean that we will no longer test the docstrings of deprecated methods ?
| ): | ||
| ConsumingRegressor().get_metadata_routing() | ||
|
|
||
| MetaRegressor(estimator=ConsumingRegressor()).get_metadata_routing() |
There was a problem hiding this comment.
Shouldn't we test here that it does not raise a FutureWarning. Not sure about the best way to check but maybe something like that:
| MetaRegressor(estimator=ConsumingRegressor()).get_metadata_routing() | |
| with warnings.catch_warnings(record=True) as record: | |
| MetaRegressor(estimator=ConsumingRegressor()).get_metadata_routing() | |
| assert len(record) == 0 |
| ``_MetadataRequester`` class, and ``BaseEstimator`` inherits from this mixin. | ||
| This mixin also implements the ``get_metadata_routing``, which meta-estimators | ||
| need to override, but it works for simple consumers as is. | ||
| This mixin also implements a ``_get_metadata_request`` method. |
There was a problem hiding this comment.
Not a pb ! Here is the call stack if I understand correctly 🤷
- Estimator instance created.
_metadata_requestdoes not exist yet. - User first calls
set_{method}_requestwith some keyword arguments. - Descriptor calls
_get_metadata_request(). _metadata_requestis missing, calls_get_default_requests()._get_default_requests()builds and returns a MetadataRequest (the class level "default" requests).- The MetadataRequest is updated for the keyword arguments provided by the user.
- The MetadataRequest is stored on the
_metadata_requestattribute of the estimator. - Future calls use the existing
_metadata_requestattribute.
| ``_MetadataRequester`` class, and ``BaseEstimator`` inherits from this mixin. | ||
| This mixin also implements the ``get_metadata_routing``, which meta-estimators | ||
| need to override, but it works for simple consumers as is. | ||
| This mixin also implements a ``_get_metadata_request`` method. |
There was a problem hiding this comment.
But you've answered my question :)
For a router-consumer object,obj._get_metadata_request() returns the self request. It's indeed used within the MetadataRouter add_self_request.
| of the output of that method. | ||
| of its :class:`~sklearn.utils.metadata_routing.MetadataRouter`. | ||
| - If the object provides a `_get_metadata_request` method, return a copy | ||
| of is :class:`~sklearn.utils.metadata_routing.MetadataRequest`. |
There was a problem hiding this comment.
| of is :class:`~sklearn.utils.metadata_routing.MetadataRequest`. | |
| of its :class:`~sklearn.utils.metadata_routing.MetadataRequest`. |
Ah thanks for the clarification! Maybe a workaround to test if an object is not a consumer is: (but I'm still unsure when an object is considered or not a consumer) |
|
Note to myself on what to do next: add developer API for |
|
I opened #34314 to unblock this PR. |
| X, y, **routed_params.estimator.transform | ||
| ) | ||
| return X | ||
|
|
|
|
||
| def transform(self, X, y=None, **transform_params): | ||
| routed_params = process_routing(self, "transform", **transform_params) | ||
| self.estimator_ = clone(self.estimator).transform( |
There was a problem hiding this comment.
For my understanding, could you tell my why it's necessary to clone the estimator?
I thought that estimator_ always was a fitted estimator, and transform needs a fitted estimator. No?
What does this implement/fix? Explain your changes.
This PR de-couples the double-handling of
MetadataRouterandMetadataRequestobjects in metadata routing ( a bit), by not using theget_metadata_routingmethod inMetadataRequestanymore, but instead to directly use_get_metadata_request.This change has affect in several parts of our metadata routing implementation and the tests and there simplifies the code and makes it more intuitive to read.
The goal of this PR is to increase maintainability.
While at it, I also:
__metadata_request__*class attribute into__metadata_request__{method}and made clear to mention its a class attribute in our internal documentation to make it easier to distinguish it from the_metadata_requestinstance attribute present in consumers at first sight