Загрузка
Note that the methods and requirements introduced in this document are only
relevant if you want to pass metadata (e.g. sample_weight) to a method.
If you’re only passing X and y and no other parameter / metadata to
methods such as fit, transform, etc., then you don’t need to set
anything.
This guide demonstrates how metadata can be routed and passed between objects in scikit-learn. If you are developing a scikit-learn compatible estimator or meta-estimator, you can check our related developer guide: Developing Estimators Compliant with Metadata Routing.
Metadata is data that an estimator, scorer, or CV splitter takes into account if the
user explicitly passes it as a parameter. For instance, KMeans accepts
sample_weight in its fit() method and considers it to calculate its centroids.
classes are consumed by some classifiers and groups are used in some splitters, but
any data that is passed into an object’s methods apart from X and y can be considered as
metadata. Prior to scikit-learn version 1.3, there was no single API for passing
metadata like that if these objects were used in conjunction with other objects, e.g. a
scorer accepting sample_weight inside a GridSearchCV.
With the Metadata Routing API, we can transfer metadata to estimators, scorers, and CV
splitters using meta-estimators (such as Pipeline or
GridSearchCV) or functions such as
cross_validate which route data to other objects. In order to
pass metadata to a method like fit or score, the object consuming the metadata,
must request it. This is done via set_{method}_request() methods, where {method}
is substituted by the name of the method that requests the metadata. For instance,
estimators that use the metadata in their fit() method would use set_fit_request(),
and scorers would use set_score_request(). These methods allow us to specify which
metadata to request, for instance set_fit_request(sample_weight=True).
For grouped splitters such as GroupKFold, a
groups parameter is requested by default. This is best demonstrated by the
following examples.
Here we present a few examples to show some common use-cases. Our goal is to pass
sample_weight and groups through cross_validate, which
routes the metadata to LogisticRegressionCV and to a custom scorer
made with make_scorer, both of which can use the metadata in their
methods. In these examples we want to individually set whether to use the metadata
within the different consumers.
The examples in this section require the following imports and data:
>>> import numpy as np
>>> from sklearn.metrics import make_scorer, accuracy_score
>>> from sklearn.linear_model import LogisticRegressionCV, LogisticRegression
>>> from sklearn.model_selection import cross_validate, GridSearchCV, GroupKFold
>>> from sklearn.feature_selection
The splitter used internally in LogisticRegressionCV,
GroupKFold, requests groups by default. However, we need
to explicitly request sample_weight for it and for our custom scorer by specifying
sample_weight=True in LogisticRegressionCV’s set_fit_request()
method and in ’s method. Both
know how to use in their or
methods. We can then pass the metadata in
which will route it to any active consumers:
When passing metadata such as sample_weight into a router
(meta-estimators or routing function), all sample_weight consumers require weights to be either explicitly requested or explicitly not
requested (i.e. True or False). Thus, to perform an unweighted fit, we need to
configure LogisticRegressionCV to not request sample weights, so
that does not pass the weights along:
Routing metadata is only possible if the object’s method knows how to use the metadata,
which in most cases means they have it as an explicit parameter. Only then we can set
request values for metadata using set_fit_request(sample_weight=True), for instance.
This makes the object a consumer.
Unlike LogisticRegressionCV,
SelectKBest can’t consume weights and therefore no request
value for sample_weight on its instance is set and sample_weight is not routed
to it:
Despite make_scorer and
LogisticRegressionCV both expecting the key
sample_weight, we can use aliases to pass different weights to different
consumers. In this example, we pass scoring_weight to the scorer, and
fitting_weight to LogisticRegressionCV:
A consumer is an object (estimator, meta-estimator, scorer, splitter) which
accepts and uses some metadata in at least one of its methods (for instance
fit, predict, inverse_transform, transform, score, split).
Meta-estimators which only forward the metadata to other objects (child estimators,
scorers, or splitters) and don’t use the metadata themselves are not consumers.
(Meta-)Estimators which route metadata to other objects are routers.
A(n) (meta-)estimator can be a consumer and a router at the same time.
(Meta-)Estimators and splitters expose a set_{method}_request method for each method
which accepts at least one metadata. For instance, if an estimator supports
sample_weight in fit and score, it exposes
estimator.set_fit_request(sample_weight=value) and
estimator.set_score_request(sample_weight=value). Here value can be:
True: method requests a sample_weight. This means if the metadata is provided,
it will be used, otherwise no error is raised.
False: method does not request a sample_weight.
None: router will raise an error if sample_weight is passed. This is in almost
all cases the default value when an object is instantiated and ensures the user sets
the metadata requests explicitly when a metadata is passed. The only exception are
Group*Fold splitters.
"param_name": alias for sample_weight if we want to pass different weights to
different consumers. If aliasing is used the meta-estimator should not forward
to the consumer, but instead, because the consumer
will expect a param called . This means the mapping between the
metadata required by the object, e.g. and the variable name provided
by the user, e.g. is done at the router level, and not by the consuming
object itself.
Metadata are requested in the same way for scorers using set_score_request.
If a metadata, e.g. sample_weight, is passed by the user, the metadata request for
all objects which potentially can consume sample_weight should be set by the user,
otherwise an error is raised by the router object. For example, the following code
raises an error, since it hasn’t been explicitly specified whether sample_weight
should be passed to the estimator’s scorer or not:
>>> param_grid = {"C": [0.1, 1]}
>>> lr = LogisticRegression().set_fit_request(sample_weight=True)
>>> try:
... GridSearchCV(
... estimator=lr, param_grid=param_grid
The issue can be fixed by explicitly setting the request value:
>>> lr = LogisticRegression().set_fit_request(
... sample_weight=True
... ).set_score_request(sample_weight=False)
At the end of the Usage Examples section, we disable the configuration flag for metadata routing:
>>> sklearn.set_config(enable_metadata_routing=False)
All consumers (i.e. simple estimators which only consume metadata and don’t route them) support metadata routing, meaning they can be used inside meta-estimators which support metadata routing. However, development of support for metadata routing for meta-estimators is in progress, and here is a list of meta-estimators and tools which support and don’t yet support metadata routing.
Meta-estimators and functions supporting metadata routing:
Meta-estimators and tools not supporting metadata routing yet:
make_scorerset_score_request()sample_weightfit()score()>>> weighted_acc = make_scorer(accuracy_score).set_score_request(sample_weight=True)
>>> lr = LogisticRegressionCV(
... cv=GroupKFold(),
... scoring=weighted_acc,
... use_legacy_attributes=False,
... ).set_fit_request(sample_weight=True)
>>> cv_results = cross_validate(
... lr,
... X,
... y,
... params={"sample_weight": my_weights, "groups": my_groups},
... cv=GroupKFold(),
... scoring=weighted_acc,
... )
Note that in this example, cross_validate routes my_weights
to both the scorer and LogisticRegressionCV.
If we would pass sample_weight in the params of
cross_validate, but not set any object to request it,
UnsetMetadataPassedError would be raised, hinting to us that we need to explicitly set
where to route it. The same applies if params={"sample_weights": my_weights, ...}
were passed (note the typo, i.e. weights instead of weight), since
sample_weights was not requested by any of its underlying objects.
cross_validate>>> weighted_acc = make_scorer(accuracy_score).set_score_request(sample_weight=True)
>>> lr = LogisticRegressionCV(
... cv=GroupKFold(), scoring=weighted_acc, use_legacy_attributes=False
... ).set_fit_request(sample_weight=False)
>>> cv_results = cross_validate(
... lr,
... X,
... y,
... cv=GroupKFold(),
... params={"sample_weight": my_weights, "groups": my_groups},
... scoring=weighted_acc,
... )
If linear_model.LogisticRegressionCV.set_fit_request had not been called,
cross_validate would raise an error because sample_weight
is passed but LogisticRegressionCV would not be explicitly
configured to recognize the weights.
>>> weighted_acc = make_scorer(accuracy_score).set_score_request(sample_weight=True)
>>> lr = LogisticRegressionCV(
... cv=GroupKFold(), scoring=weighted_acc, use_legacy_attributes=False
... ).set_fit_request(sample_weight=True)
>>> sel = SelectKBest(k=2)
>>> pipe = make_pipeline(sel, lr)
>>> cv_results = cross_validate(
... pipe,
... X,
... y,
... cv=GroupKFold(),
... params={"sample_weight": my_weights, "groups": my_groups},
... scoring=weighted_acc,
... )
>>> weighted_acc = make_scorer(accuracy_score).set_score_request(
... sample_weight="scoring_weight"
... )
>>> lr = LogisticRegressionCV(
... cv=GroupKFold(), scoring=weighted_acc, use_legacy_attributes=False
... ).set_fit_request(sample_weight="fitting_weight")
>>> cv_results = cross_validate(
... lr,
... X,
... y,
... cv=GroupKFold(),
... params={
... "scoring_weight": my_weights,
... "fitting_weight": my_other_weights,
... "groups": my_groups,
... },
... scoring=weighted_acc,
... )
sample_weightsample_weightsample_weightmy_weights