【问题标题】:How to pass a keyword argument to the predict method in a sklearn pipeline如何将关键字参数传递给 sklearn 管道中的预测方法
【发布时间】:2014-08-26 15:29:12
【问题描述】:

我在Pipeline 中使用GaussianProcessGaussianProcesspredict 方法接受一个名为 batch_sizepredict 方法的关键字参数,我需要使用它来防止填满我的内存。

通过配置的管道调用predict时,有没有办法将此参数传递给GaussianProcess实例?

这是一个改编自 sklearn 文档的最小示例,用于演示我想要什么:

import numpy as np
from sklearn.gaussian_process import GaussianProcess
from matplotlib import pyplot as pl

np.random.seed(1)

def f(x):
    """The function to predict."""
    return x * np.sin(x)

X = np.atleast_2d([1., 3., 5., 6., 7., 8.]).T
y = f(X).ravel()

gp = GaussianProcess(corr='cubic', theta0=1e-2, thetaL=1e-4, thetaU=1e-1,
                     random_start=100)
gp.fit(X, y)

x = np.atleast_2d(np.linspace(0, 10, 1000)).T
y_pred = gp.predict(x, batch_size=10)

from sklearn import pipeline
steps = [('gp', gp)]
p = pipeline.Pipeline(steps)
# How to pass the batch_size here?
p.predict(x)

【问题讨论】:

  • 这是一个 API 缺陷:GP 应该在其构造函数中使用这个批量大小参数,而不是 predict

标签: python scikit-learn


【解决方案1】:

您可以通过允许将关键字参数 **predict_params 传递给 Pipeline 的 predict 方法来解决它。

from sklearn.pipeline import Pipeline

class Pipeline(Pipeline):
    def predict(self, X, **predict_params):
        """Applies transforms to the data, and the predict method of the
        final estimator. Valid only if the final estimator implements
        predict."""
        Xt = X
        for name, transform in self.steps[:-1]:
            Xt = transform.transform(Xt)
        return self.steps[-1][-1].predict(Xt, **predict_params)

【讨论】:

    【解决方案2】:

    一直在寻找这个——在其他地方找到了答案,但想在这里分享,因为这是我找到的第一个相关问题。

    sklearn的当前版本中,您可以将关键字args传递给管道,然后将其传递给预测器(即管道中的最后一个元素):

    from sklearn.base import BaseEstimator, ClassifierMixin
    from sklearn.pipeline import Pipeline
    
    class Predictor(BaseEstimator, ClassifierMixin):
        def fit(self, *_):
            return self
    
        def predict(self, X, additional_arg):
            return f'ok: {X}, {additional_arg}'
    
    pipe = Pipeline([
        ('passthrough', 'passthrough'),  # anything here would *not* see the keyword arg
        ('p', Predictor())
    ])
    
    print(Predictor().predict('one', 'two'))
    print(pipe.predict('three', additional_arg='four'))  # must be passed as keyword argument
    
    # DO NOT:
    print(pipe.predict('three')) # would raise an exception: missing parameter
    print(pipe.predict('three', 'four')) # would raise an exception: no positional args allowed
    

    【讨论】:

      【解决方案3】:

      虽然可以将拟合参数添加到管道的 fitfit_transform 方法,但对于 predict 是不可能的。请参阅this line 以及版本0.15 代码中的后续代码。

      你也许可以使用猴子补丁

      from functools import partial
      gp.predict = partial(gp.predict, batch_size=10)
      

      或者,如果这不起作用,那么

      pipeline.steps[-1][-1].predict = partial(pipeline.steps[-1][-1].predict, batch_size=10)
      

      【讨论】:

        猜你喜欢
        • 2021-09-25
        • 2017-03-12
        • 1970-01-01
        • 2021-08-23
        • 2021-08-09
        • 2018-03-18
        • 1970-01-01
        • 2017-11-26
        • 2016-07-03
        相关资源
        最近更新 更多