scikit-learn - 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
还有其他方法吗?
解决方案
这里的问题仅仅是因为 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,它不实现转换方法()
推荐阅读
- android - 在 UncaughtExceptionHandler 中将 Stacktrace 记录到 FirebaseDatabase,调用默认 uncaughtException 方法时出现问题
- cucumber-java - 黄瓜功能,Java,Eclipse
- string - 将字符串列表添加到 Lucene 文档
- c++ - 通过 CMake 添加子项目
- javascript - 单元测试:存根/重新连接服务器请求中的函数
- c# - ErrorHandling Middleware catch 永远不会被捕获
- python - 查找所有坐标簇,其中簇中的每个坐标彼此之间的距离小于某个最大距离
- xamarin - 注册路线列表
- machine-learning - 除了 Mask R-CNN 之外,还有其他深度学习方法可以从卫星图像中检测和分割建筑物吗
- javascript - 如何选择复制事件的文本内容以及在进行复制事件之前如何使用它?