首页 > 解决方案 > sklearn 线性回归管道可以在输出变量上设置最大上限吗?

问题描述

我的 scikit 学习管道是线性回归,但我的问题域不应该允许输出高于某个值,所以我想限制输出。我知道我可以先运行我的模型,然后再做一个y = np.where(y > MAX_VALUE, MAX_VALUE, y),但我可能还有几个类似的自定义逻辑步骤,所以我想将它封装到管道中。sklearn 能做到吗?

我试图编写我自己的自定义估计器,如下所示,这给出了错误All intermediate steps should be transformers and implement fit and transform or be the string 'passthrough',因此管道似乎不允许在步骤之后放置LinearRegression步骤。有没有办法做到这一点?

import sklearn.base

class ClipOutputToMaxValue(sklearn.base.BaseEstimator, sklearn.base.RegressorMixin):
    '''custom step to put a ceiling on the output 'y' value```
    def fit(self, X, y):
        self.max_y = y.max()
        return self

    def predict(self, X, y):
        y = np.where(y > self.max_y, self.max_y, y)
        return y

model =  sklearn.pipeline.Pipeline(
        [('scaler', sklearn.preprocessing.StandardScaler()),
         ('model', sklearn.linear_model.LinearRegression()),
         ('clipper', ClipOutputToMaxValue()) #THIS IS WHAT I WANT BUT
         #SKLEARN DOESN'T ALLOW ME TO DO THIS
        ])

x = np.arange(10).reshape(10,-1)
y = x
model.fit(x, y)
model.predict(x)

但这失败并出现此错误: TypeError: All intermediate steps should be transformers and implement fit and transform or be the string 'passthrough' 'LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None, normalize=False)' (type <class 'sklearn.linear_model.base.LinearRegression'>) doesn't

还有其他方法吗?

标签: scikit-learnlinear-regression

解决方案


这里的问题仅仅是因为 Pipeline 必须只有带有 fit 和 transform 方法的中间步骤,除了最后一步,它必须是 Pipeline 调用 .fit 方法的最终模型。

从这里:

[https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html?highlight=pipeline#sklearn.pipeline.Pipeline][管道]

“依次应用一个transforms列表和一个final estimator。pipeline的中间步骤必须是‘transforms’,即必须实现fit和transform方法。final estimator只需要实现fit。pipeline中的transformer可以是使用内存参数缓存。”

因此,在您的情况下,您正在应用 LinearRegression,它不实现转换方法()


推荐阅读