开发符合元数据路由的估计器#

本文档展示了如何在 scikit-learn 中使用元数据路由机制来构建估计器,这些估计器可以将元数据路由到其他可以消费元数据的估计器、评分器和交叉验证分割器。

为了更好地理解以下文档,我们需要介绍两个概念:路由器消费者。一个路由器是一个将给定数据和元数据转发给其他对象的对象。在大多数情况下,路由器是一个元估计器,即一个以另一个估计器作为参数的估计器。像sklearn.model_selection.cross_validate这样以估计器作为参数并转发数据和元数据的函数,也是一个路由器。

另一方面,一个消费者是一个接受并使用给定元数据的对象。例如,在其fit方法中考虑sample_weight的估计器是sample_weight的消费者。

一个对象可以同时是路由器和消费者。例如,一个元估计器可能在某些计算中考虑sample_weight,但它也可能将其路由到底层估计器。

首先是一些导入和脚本其余部分的随机数据。

# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause
import warnings
from pprint import pprint

import numpy as np

from sklearn import set_config
from sklearn.base import (
    BaseEstimator,
    ClassifierMixin,
    MetaEstimatorMixin,
    RegressorMixin,
    TransformerMixin,
    clone,
)
from sklearn.linear_model import LinearRegression
from sklearn.utils import metadata_routing
from sklearn.utils.metadata_routing import (
    ,
    ,
    ,
)
from sklearn.utils.validation import check_is_fitted

n_samples, n_features = 100, 4
rng = np.random.RandomState(42)
X = rng.rand(n_samples, n_features)
y = rng.randint(0, 2, size=n_samples)
my_groups = rng.randint(0, 10, size=n_samples)
my_weights = rng.rand(n_samples)
my_other_weights = rng.rand(n_samples)

元数据路由仅在明确启用时可用

set_config(enable_metadata_routing=True)

此实用函数是一个虚拟函数,用于检查是否传递了元数据

def check_metadata(obj, **kwargs):
    for key, value in kwargs.items():
        if value is not None:
            print(
                f"Received {key} of length = {len(value)} in {obj.__class__.__name__}."
            )
        else:
            print(f"{key} is None in {obj.__class__.__name__}.")

一个用于美观地打印对象路由信息的实用函数

def print_routing(obj):
    pprint(obj.get_metadata_routing()._serialize())

消费估计器#

这里我们演示了估计器如何公开所需的 API 以支持元数据路由作为消费者。想象一个简单的分类器,在其fit方法中接受sample_weight作为元数据,并在其predict方法中接受groups

class ExampleClassifier(ClassifierMixin, BaseEstimator):
    def fit(self, X, y, sample_weight=None):
        check_metadata(self, sample_weight=sample_weight)
        # all classifiers need to expose a classes_ attribute once they're fit.
        self.classes_ = np.array([0, 1])
        return self

    def predict(self, X, groups=None):
        check_metadata(self, groups=groups)
        # return a constant value of 1, not a very smart classifier!
        return np.ones(len(X))

上述估计器现在拥有消费元数据所需的一切。这是通过BaseEstimator中完成的一些“魔法”来实现的。现在,上述类公开了三个方法:set_fit_requestset_predict_requestget_metadata_routing。还有一个针对sample_weightset_score_request,它之所以存在是因为ClassifierMixin实现了一个接受sample_weightscore方法。同样的情况也适用于继承自RegressorMixin的回归器。

默认情况下,不请求任何元数据,我们可以看到如下:

print_routing(ExampleClassifier())
{'fit': {'sample_weight': None},
 'predict': {'groups': None},
 'score': {'sample_weight': None}}

上述输出意味着ExampleClassifier不请求sample_weightgroups,如果路由器给出了这些元数据,它应该引发错误,因为用户没有明确设置它们是否必需。对于score方法中的sample_weight也是如此,它继承自ClassifierMixin。为了明确设置这些元数据的请求值,我们可以使用这些方法:

est = (
    ExampleClassifier()
    .set_fit_request(sample_weight=False)
    .set_predict_request(groups=True)
    .set_score_request(sample_weight=False)
)
print_routing(est)
{'fit': {'sample_weight': False},
 'predict': {'groups': True},
 'score': {'sample_weight': False}}

注意

请注意,只要上述估计器未在元估计器中使用,用户就无需为元数据设置任何请求,并且设置的值将被忽略,因为消费者不验证或路由给定的元数据。上述估计器的简单用法将按预期工作。

est = ExampleClassifier()
est.fit(X, y, sample_weight=my_weights)
est.predict(X[:3, :], groups=my_groups)

输出

Received sample_weight of length = 100 in ExampleClassifier.
Received groups of length = 100 in ExampleClassifier.

array([1., 1., 1.])

路由元估计器#

现在,我们展示如何设计一个元估计器作为路由器。作为一个简化示例,这是一个元估计器,它除了路由元数据外没有做太多其他事情。

要使元估计器成为路由器,您只需要:

  • 定义其get_metadata_routing方法,该方法返回一个负责配置元数据路由的MetadataRouter实例。

  • 在其方法(fitpredict等)内部使用process_routing,以将元数据从元估计器正确路由到其子估计器。

class MetaClassifier(MetaEstimatorMixin, ClassifierMixin, BaseEstimator):
    def __init__(self, estimator):
        self.estimator = estimator

    def get_metadata_routing(self):
        # This method defines the routing for this meta-estimator.
        # In order to do so, a `MetadataRouter` instance is created, and the
        # routing is added to it.
        router = (owner=self).add(
            estimator=self.estimator,
            method_mapping=()
            .add(caller="fit", callee="fit")
            .add(caller="predict", callee="predict")
            .add(caller="score", callee="score"),
        )
        return router

    def fit(self, X, y, **fit_params):
        # Get information on all the metadata that should be routed from here to
        # consuming methods.
        routed_params = (self, "fit", **fit_params)
        # A sub-estimator is fitted and its classes are attributed to the
        # meta-estimator. Since we call the sub-estimator's fit method, we pass the
        # the metadata stored in `routed_params.estimator.fit`.
        self.estimator_ = clone(self.estimator).fit(X, y, **routed_params.estimator.fit)
        self.classes_ = self.estimator_.classes_
        return self

    def predict(self, X, **predict_params):
        check_is_fitted(self)
        # As in `fit`, we get information on all the metadata that should be routed and
        # pass the metadata that is stored in `routed_params.estimator.predict` to the
        # sub-estimator's predict method.
        routed_params = (self, "predict", **predict_params)
        return self.estimator_.predict(X, **routed_params.estimator.predict)

让我们分解上述代码的不同部分。

在每个方法中,我们使用process_routing函数构造一个形式为{"object_name": {"method_name": {"metadata": value}}}Bunch,以传递给底层估计器的方法。其中的object_name(在routed_params.estimator.fit中是estimator)与在get_metadata_routing中添加的estimator相同。process_routing还会验证输入元数据:它确保所有给定的元数据都已被请求,以避免潜在的错误。

接下来,我们将说明不同的行为,特别是引发的错误类型。

meta_est = MetaClassifier(
    estimator=ExampleClassifier().set_fit_request(sample_weight=True)
)
meta_est.fit(X, y, sample_weight=my_weights)
Received sample_weight of length = 100 in ExampleClassifier.
MetaClassifier(estimator=ExampleClassifier())
在 Jupyter 环境中,请重新运行此单元格以显示 HTML 表示形式或信任 notebook。
在 GitHub 上,HTML 表示形式无法渲染,请尝试使用 nbviewer.org 加载此页面。


请注意,上述示例是通过ExampleClassifier调用我们的实用函数check_metadata()。它检查sample_weight是否正确传递给它。如果不是,如下例所示,它将打印sample_weightNone

meta_est.fit(X, y)
sample_weight is None in ExampleClassifier.
MetaClassifier(estimator=ExampleClassifier())
在 Jupyter 环境中,请重新运行此单元格以显示 HTML 表示形式或信任 notebook。
在 GitHub 上,HTML 表示形式无法渲染,请尝试使用 nbviewer.org 加载此页面。


如果我们传递一个未知的元数据,将引发错误。

try:
    meta_est.fit(X, y, test=my_weights)
except TypeError as e:
    print(e)
MetaClassifier.fit got unexpected argument(s) {'test'}, which are not routed to any object.

如果我们传递一个未明确请求的元数据:

try:
    meta_est.fit(X, y, sample_weight=my_weights).predict(X, groups=my_groups)
except ValueError as e:
    print(e)
Received sample_weight of length = 100 in ExampleClassifier.
[groups] are passed but are not explicitly set as requested or not requested for ExampleClassifier.predict, which is used within MetaClassifier.predict. Call `ExampleClassifier.set_predict_request({metadata}=True/False)` for each metadata you want to request/ignore. See the Metadata Routing User guide <https://scikit-learn.cn/stable/metadata_routing.html> for more information.

此外,如果我们明确将其设置为不请求,但它却被提供:

meta_est = MetaClassifier(
    estimator=ExampleClassifier()
    .set_fit_request(sample_weight=True)
    .set_predict_request(groups=False)
)
try:
    meta_est.fit(X, y, sample_weight=my_weights).predict(X[:3, :], groups=my_groups)
except TypeError as e:
    print(e)
Received sample_weight of length = 100 in ExampleClassifier.
MetaClassifier.predict got unexpected argument(s) {'groups'}, which are not routed to any object.

另一个要介绍的概念是别名元数据。当估计器以与默认变量名不同的变量名请求元数据时,就会出现这种情况。例如,在管道中有两个估计器的设置中,一个可能请求sample_weight1,另一个请求sample_weight2。请注意,这不会改变估计器所期望的内容,它只是告诉元估计器如何将提供的元数据映射到所需的内容。这是一个示例,我们将aliased_sample_weight传递给元估计器,但元估计器知道aliased_sample_weightsample_weight的别名,并将其作为sample_weight传递给底层估计器。

meta_est = MetaClassifier(
    estimator=ExampleClassifier().set_fit_request(sample_weight="aliased_sample_weight")
)
meta_est.fit(X, y, aliased_sample_weight=my_weights)
Received sample_weight of length = 100 in ExampleClassifier.
MetaClassifier(estimator=ExampleClassifier())
在 Jupyter 环境中,请重新运行此单元格以显示 HTML 表示形式或信任 notebook。
在 GitHub 上,HTML 表示形式无法渲染,请尝试使用 nbviewer.org 加载此页面。


在这里传递sample_weight将失败,因为它以别名形式请求,并且未以该名称请求sample_weight

try:
    meta_est.fit(X, y, sample_weight=my_weights)
except TypeError as e:
    print(e)
MetaClassifier.fit got unexpected argument(s) {'sample_weight'}, which are not routed to any object.

这使我们了解get_metadata_routing。scikit-learn 中的路由工作方式是,消费者请求他们所需的内容,路由器将其传递。此外,路由器会公开其自身所需的内容,以便可以在另一个路由器内部使用它,例如网格搜索对象内部的管道。get_metadata_routing的输出是MetadataRouter的字典表示,它包括所有嵌套对象请求的元数据的完整树以及它们相应的方法路由,即子估计器的哪个方法在元估计器的哪个方法中使用。

print_routing(meta_est)
{'estimator': {'mapping': [{'callee': 'fit', 'caller': 'fit'},
                           {'callee': 'predict', 'caller': 'predict'},
                           {'callee': 'score', 'caller': 'score'}],
               'router': {'fit': {'sample_weight': 'aliased_sample_weight'},
                          'predict': {'groups': None},
                          'score': {'sample_weight': None}}}}

如您所见,针对fit方法请求的唯一元数据是"sample_weight",其别名为"aliased_sample_weight"~utils.metadata_routing.MetadataRouter类使我们能够轻松创建路由对象,该对象将生成我们get_metadata_routing所需的输出。

为了理解别名在元估计器中的工作方式,想象一下我们的元估计器嵌套在另一个元估计器中:

meta_meta_est = MetaClassifier(estimator=meta_est).fit(
    X, y, aliased_sample_weight=my_weights
)
Received sample_weight of length = 100 in ExampleClassifier.

在上述示例中,meta_meta_estfit方法将按以下方式调用其子估计器的fit方法:

# user feeds `my_weights` as `aliased_sample_weight` into `meta_meta_est`:
meta_meta_est.fit(X, y, aliased_sample_weight=my_weights):
    ...

    # the first sub-estimator (`meta_est`) expects `aliased_sample_weight`
    self.estimator_.fit(X, y, aliased_sample_weight=aliased_sample_weight):
        ...

        # the second sub-estimator (`est`) expects `sample_weight`
        self.estimator_.fit(X, y, sample_weight=aliased_sample_weight):
            ...

消费和路由元估计器#

对于一个稍微更复杂的示例,考虑一个元估计器,它像以前一样将元数据路由到底层估计器,但它也在自己的方法中使用一些元数据。这个元估计器同时是消费者和路由器。实现这样一个估计器与我们之前的方法非常相似,但有一些调整。

class RouterConsumerClassifier(MetaEstimatorMixin, ClassifierMixin, BaseEstimator):
    def __init__(self, estimator):
        self.estimator = estimator

    def get_metadata_routing(self):
        router = (
            (owner=self)
            # defining metadata routing request values for usage in the meta-estimator
            .add_self_request(self)
            # defining metadata routing request values for usage in the sub-estimator
            .add(
                estimator=self.estimator,
                method_mapping=()
                .add(caller="fit", callee="fit")
                .add(caller="predict", callee="predict")
                .add(caller="score", callee="score"),
            )
        )
        return router

    # Since `sample_weight` is used and consumed here, it should be defined as
    # an explicit argument in the method's signature. All other metadata which
    # are only routed, will be passed as `**fit_params`:
    def fit(self, X, y, sample_weight, **fit_params):
        if self.estimator is None:
            raise ValueError("estimator cannot be None!")

        check_metadata(self, sample_weight=sample_weight)

        # We add `sample_weight` to the `fit_params` dictionary.
        if sample_weight is not None:
            fit_params["sample_weight"] = sample_weight
        routed_params = (self, "fit", **fit_params)
        self.estimator_ = clone(self.estimator).fit(X, y, **routed_params.estimator.fit)
        self.classes_ = self.estimator_.classes_
        return self

    def predict(self, X, **predict_params):
        check_is_fitted(self)
        routed_params = (self, "predict", **predict_params)
        return self.estimator_.predict(X, **routed_params.estimator.predict)

上述元估计器与我们之前的元估计器不同的关键部分在于,它在fit中明确接受sample_weight并将其包含在fit_params中。由于sample_weight是一个显式参数,我们可以确定此方法存在set_fit_request(sample_weight=...)。此元估计器既是sample_weight的消费者,也是其路由器。

get_metadata_routing中,我们使用add_self_requestself添加到路由中,以表明此估计器正在消费sample_weight,同时也是一个路由器;这也会在路由信息中添加一个$self_request键,如下所示。现在我们来看一些示例:

  • 未请求元数据

meta_est = RouterConsumerClassifier(estimator=ExampleClassifier())
print_routing(meta_est)
{'$self_request': {'fit': {'sample_weight': None},
                   'score': {'sample_weight': None}},
 'estimator': {'mapping': [{'callee': 'fit', 'caller': 'fit'},
                           {'callee': 'predict', 'caller': 'predict'},
                           {'callee': 'score', 'caller': 'score'}],
               'router': {'fit': {'sample_weight': None},
                          'predict': {'groups': None},
                          'score': {'sample_weight': None}}}}
  • 子估计器请求sample_weight

meta_est = RouterConsumerClassifier(
    estimator=ExampleClassifier().set_fit_request(sample_weight=True)
)
print_routing(meta_est)
{'$self_request': {'fit': {'sample_weight': None},
                   'score': {'sample_weight': None}},
 'estimator': {'mapping': [{'callee': 'fit', 'caller': 'fit'},
                           {'callee': 'predict', 'caller': 'predict'},
                           {'callee': 'score', 'caller': 'score'}],
               'router': {'fit': {'sample_weight': True},
                          'predict': {'groups': None},
                          'score': {'sample_weight': None}}}}
  • 元估计器请求sample_weight

meta_est = RouterConsumerClassifier(estimator=ExampleClassifier()).set_fit_request(
    sample_weight=True
)
print_routing(meta_est)
{'$self_request': {'fit': {'sample_weight': True},
                   'score': {'sample_weight': None}},
 'estimator': {'mapping': [{'callee': 'fit', 'caller': 'fit'},
                           {'callee': 'predict', 'caller': 'predict'},
                           {'callee': 'score', 'caller': 'score'}],
               'router': {'fit': {'sample_weight': None},
                          'predict': {'groups': None},
                          'score': {'sample_weight': None}}}}

请注意上述请求元数据表示中的差异。

  • 我们还可以为元数据设置别名,以便将不同的值传递给元估计器和子估计器的fit方法。

meta_est = RouterConsumerClassifier(
    estimator=ExampleClassifier().set_fit_request(sample_weight="clf_sample_weight"),
).set_fit_request(sample_weight="meta_clf_sample_weight")
print_routing(meta_est)
{'$self_request': {'fit': {'sample_weight': 'meta_clf_sample_weight'},
                   'score': {'sample_weight': None}},
 'estimator': {'mapping': [{'callee': 'fit', 'caller': 'fit'},
                           {'callee': 'predict', 'caller': 'predict'},
                           {'callee': 'score', 'caller': 'score'}],
               'router': {'fit': {'sample_weight': 'clf_sample_weight'},
                          'predict': {'groups': None},
                          'score': {'sample_weight': None}}}}

然而,元估计器的fit方法只需要子估计器的别名,并将其自身的样本权重视为sample_weight,因为它不验证和路由其自身所需的元数据。

meta_est.fit(X, y, sample_weight=my_weights, clf_sample_weight=my_other_weights)
Received sample_weight of length = 100 in RouterConsumerClassifier.
Received sample_weight of length = 100 in ExampleClassifier.
RouterConsumerClassifier(estimator=ExampleClassifier())
在 Jupyter 环境中,请重新运行此单元格以显示 HTML 表示形式或信任 notebook。
在 GitHub 上,HTML 表示形式无法渲染,请尝试使用 nbviewer.org 加载此页面。


  • 仅在子估计器上设置别名

当我们不希望元估计器使用元数据,但子估计器应该使用时,这非常有用。

meta_est = RouterConsumerClassifier(
    estimator=ExampleClassifier().set_fit_request(sample_weight="aliased_sample_weight")
)
print_routing(meta_est)
{'$self_request': {'fit': {'sample_weight': None},
                   'score': {'sample_weight': None}},
 'estimator': {'mapping': [{'callee': 'fit', 'caller': 'fit'},
                           {'callee': 'predict', 'caller': 'predict'},
                           {'callee': 'score', 'caller': 'score'}],
               'router': {'fit': {'sample_weight': 'aliased_sample_weight'},
                          'predict': {'groups': None},
                          'score': {'sample_weight': None}}}}

元估计器不能使用aliased_sample_weight,因为它期望将其作为sample_weight传递。即使在其上设置了set_fit_request(sample_weight=True),也同样适用。

简单管道#

一个稍微更复杂的用例是类似于Pipeline的元估计器。这是一个元估计器,它接受一个转换器和一个分类器。当调用其fit方法时,它会在转换器上运行fittransform,然后将分类器运行在转换后的数据上。在predict时,它会在分类器的predict方法对转换后的新数据进行预测之前,应用转换器的transform

class SimplePipeline(ClassifierMixin, BaseEstimator):
    def __init__(self, transformer, classifier):
        self.transformer = transformer
        self.classifier = classifier

    def get_metadata_routing(self):
        router = (
            (owner=self)
            # We add the routing for the transformer.
            .add(
                transformer=self.transformer,
                method_mapping=()
                # The metadata is routed such that it retraces how
                # `SimplePipeline` internally calls the transformer's `fit` and
                # `transform` methods in its own methods (`fit` and `predict`).
                .add(caller="fit", callee="fit")
                .add(caller="fit", callee="transform")
                .add(caller="predict", callee="transform"),
            )
            # We add the routing for the classifier.
            .add(
                classifier=self.classifier,
                method_mapping=()
                .add(caller="fit", callee="fit")
                .add(caller="predict", callee="predict"),
            )
        )
        return router

    def fit(self, X, y, **fit_params):
        routed_params = (self, "fit", **fit_params)

        self.transformer_ = clone(self.transformer).fit(
            X, y, **routed_params.transformer.fit
        )
        X_transformed = self.transformer_.transform(
            X, **routed_params.transformer.transform
        )

        self.classifier_ = clone(self.classifier).fit(
            X_transformed, y, **routed_params.classifier.fit
        )
        return self

    def predict(self, X, **predict_params):
        routed_params = (self, "predict", **predict_params)

        X_transformed = self.transformer_.transform(
            X, **routed_params.transformer.transform
        )
        return self.classifier_.predict(
            X_transformed, **routed_params.classifier.predict
        )

请注意MethodMapping的用法,它声明了子估计器(被调用者)的哪些方法在元估计器(调用者)的哪些方法中使用。如您所见,SimplePipelinefit中使用转换器的transformfit方法,并在predict中使用其transform方法,这正是您在管道类的路由结构中看到的实现。

上述示例与之前示例的另一个不同之处是使用了process_routing,它处理输入参数,执行所需的验证,并返回我们在先前示例中创建的routed_params。这减少了开发人员在每个元估计器方法中需要编写的样板代码。强烈建议开发人员使用此函数,除非有充分理由反对使用。

为了测试上述管道,让我们添加一个示例转换器。

class ExampleTransformer(TransformerMixin, BaseEstimator):
    def fit(self, X, y, sample_weight=None):
        check_metadata(self, sample_weight=sample_weight)
        return self

    def transform(self, X, groups=None):
        check_metadata(self, groups=groups)
        return X

    def fit_transform(self, X, y, sample_weight=None, groups=None):
        return self.fit(X, y, sample_weight).transform(X, groups)

请注意,在上述示例中,我们实现了fit_transform,它使用适当的元数据调用fittransform。仅当transform接受元数据时才需要这样做,因为TransformerMixin中的默认fit_transform实现不会将元数据传递给transform

现在我们可以测试我们的管道,看看元数据是否正确传递。此示例使用我们的SimplePipelineExampleTransformer和使用我们ExampleClassifierRouterConsumerClassifier

pipe = SimplePipeline(
    transformer=ExampleTransformer()
    # we set transformer's fit to receive sample_weight
    .set_fit_request(sample_weight=True)
    # we set transformer's transform to receive groups
    .set_transform_request(groups=True),
    classifier=RouterConsumerClassifier(
        estimator=ExampleClassifier()
        # we want this sub-estimator to receive sample_weight in fit
        .set_fit_request(sample_weight=True)
        # but not groups in predict
        .set_predict_request(groups=False),
    )
    # and we want the meta-estimator to receive sample_weight as well
    .set_fit_request(sample_weight=True),
)
pipe.fit(X, y, sample_weight=my_weights, groups=my_groups).predict(
    X[:3], groups=my_groups
)
Received sample_weight of length = 100 in ExampleTransformer.
Received groups of length = 100 in ExampleTransformer.
Received sample_weight of length = 100 in RouterConsumerClassifier.
Received sample_weight of length = 100 in ExampleClassifier.
Received groups of length = 100 in ExampleTransformer.
groups is None in ExampleClassifier.

array([1., 1., 1.])

弃用/默认值变更#

在本节中,我们将展示如何处理路由器也成为消费者的情况,特别是当它消费与其子估计器相同的元数据时,或者当消费者开始消费在旧版本中不消费的元数据时。在这种情况下,应该暂时发出警告,以告知用户行为已从先前版本中更改。

class MetaRegressor(MetaEstimatorMixin, RegressorMixin, BaseEstimator):
    def __init__(self, estimator):
        self.estimator = estimator

    def fit(self, X, y, **fit_params):
        routed_params = (self, "fit", **fit_params)
        self.estimator_ = clone(self.estimator).fit(X, y, **routed_params.estimator.fit)

    def get_metadata_routing(self):
        router = (owner=self).add(
            estimator=self.estimator,
            method_mapping=().add(caller="fit", callee="fit"),
        )
        return router

如上所述,如果my_weights不应该作为sample_weight传递给MetaRegressor,则这是一种有效用法。

reg = MetaRegressor(estimator=LinearRegression().set_fit_request(sample_weight=True))
reg.fit(X, y, sample_weight=my_weights)

现在假设我们进一步开发MetaRegressor,它现在也消费sample_weight

class WeightedMetaRegressor(MetaEstimatorMixin, RegressorMixin, BaseEstimator):
    # show warning to remind user to explicitly set the value with
    # `.set_{method}_request(sample_weight={boolean})`
    __metadata_request__fit = {"sample_weight": metadata_routing.WARN}

    def __init__(self, estimator):
        self.estimator = estimator

    def fit(self, X, y, sample_weight=None, **fit_params):
        routed_params = (
            self, "fit", sample_weight=sample_weight, **fit_params
        )
        check_metadata(self, sample_weight=sample_weight)
        self.estimator_ = clone(self.estimator).fit(X, y, **routed_params.estimator.fit)

    def get_metadata_routing(self):
        router = (
            (owner=self)
            .add_self_request(self)
            .add(
                estimator=self.estimator,
                method_mapping=().add(caller="fit", callee="fit"),
            )
        )
        return router

上述实现与MetaRegressor几乎相同,并且由于在__metadata_request__fit中定义的默认请求值,在拟合时会引发警告。

with warnings.catch_warnings(record=True) as record:
    WeightedMetaRegressor(
        estimator=LinearRegression().set_fit_request(sample_weight=False)
    ).fit(X, y, sample_weight=my_weights)
for w in record:
    print(w.message)
Received sample_weight of length = 100 in WeightedMetaRegressor.
Support for sample_weight has recently been added to WeightedMetaRegressor(estimator=LinearRegression()) class. To maintain backward compatibility, it is ignored now. Using `set_fit_request(sample_weight={True, False})` on this method of the class, you can set the request value to False to silence this warning, or to True to consume and use the metadata.

当估计器消费以前不消费的元数据时,可以使用以下模式来警告用户。

class ExampleRegressor(RegressorMixin, BaseEstimator):
    __metadata_request__fit = {"sample_weight": metadata_routing.WARN}

    def fit(self, X, y, sample_weight=None):
        check_metadata(self, sample_weight=sample_weight)
        return self

    def predict(self, X):
        return np.zeros(shape=(len(X)))


with warnings.catch_warnings(record=True) as record:
    MetaRegressor(estimator=ExampleRegressor()).fit(X, y, sample_weight=my_weights)
for w in record:
    print(w.message)
sample_weight is None in ExampleRegressor.
Support for sample_weight has recently been added to ExampleRegressor() class. To maintain backward compatibility, it is ignored now. Using `set_fit_request(sample_weight={True, False})` on this method of the class, you can set the request value to False to silence this warning, or to True to consume and use the metadata.

最后,我们禁用元数据路由的配置标志。

set_config(enable_metadata_routing=False)

第三方开发与scikit-learn依赖#

如上所示,信息通过MetadataRequestMetadataRouter在类之间传递。虽然强烈不建议这样做,但如果您严格希望拥有一个与scikit-learn兼容的估计器而不依赖于scikit-learn包,则可以获取与元数据路由相关的工具。如果满足以下所有条件,您根本不需要修改您的代码:

  • 您的估计器继承自BaseEstimator

  • 您的估计器方法(例如fit)所消费的参数在方法签名中明确定义,而不是作为*args*kwargs

  • 您的估计器不将任何元数据路由到底层对象,即它不是一个路由器

脚本总运行时间: (0 分钟 0.040 秒)

相关示例

使用预计算 Gram 矩阵和加权样本拟合 Elastic Net

使用预计算 Gram 矩阵和加权样本拟合 Elastic Net

scikit-learn 1.4 发布亮点

scikit-learn 1.4 发布亮点

SGD:加权样本

SGD:加权样本

SVM:加权样本

SVM:加权样本

由 Sphinx-Gallery 生成的图库