我希望实现一个简单的包装器/元估计器,它与scikit-learn兼容。很难找到对我所需内容的全面描述。
目标是拥有一个回归器,还要学习一个阈值以成为分类器。因此,我想到:
from sklearn.base import BaseEstimator, ClassifierMixin, clone
class Thresholder(BaseEstimator, ClassifierMixin):
def __init__(self, regressor):
self.regressor = regressor
# threshold_ does not get initialized in __init__ ??
def fit(self, X, y, optimal_threshold):
self.regressor = clone(self.regressor) # is this required my sklearn??
self.regressor.fit(X, y)
y_raw = self.regressor.predict()
self.threshold_ = optimal_threshold(y_raw)
def predict(self, X):
y_raw = self.regressor.predict(X)
y = np.digitize(y_raw, [self.threshold_])
return y
这个实现是否包含我需要的完整 API?
我的主要问题是在哪里放置 threshold
。我希望它只被学习一次,并且可以在后续的 .fit
调用中使用新数据而不需要重新调整。但是当前版本需要在每次 .fit
调用时重新调整 - 这不是我想要的。
另一方面,如果我将其作为固定参数 self.threshold
并传递给 __init__
,那么我就不能使用数据更改它了吗?
如何创建一个 threshold
参数,它可以在一次 .fit
调用中进行调整,并在后续的 .fit
调用中保持不变?
threshold_
初始化为None,并在fit
中检查它的值是否被设置,那么它不会起作用吗?有点类似于warm_start
参数。 - Shihab Shahriar Khanclone
和其他元估计器之类的函数在幕后执行某种魔法。这就是为什么我想知道使用sklearn的正确方式。 - Gereself.threshold = None
,然后加上一个 if 语句 -if self.threshold is not None: self.threshold = optimal_threshold(y_raw)
?虽然我认为更好的方法是在fit
方法中添加一个布尔值,指示是否更新阈值。 - Rotem Tal