Python 在sklearn中创建自定义回归器

Python 在sklearn中创建自定义回归器,python,scikit-learn,regression,Python,Scikit Learn,Regression,我想使用带有sklearnGridSearchCV的自定义回归器。它的精神类似于创建一个自定义分类器——如本博客所示: 下面是博客中代码的浓缩/编辑部分,展示了一些需要重写的方法 from sklearn.base import BaseEstimator, RegressorMixin class MyCustomClassifier(BaseEstimator, RegressorMixin): """An example of classifier""" def

我想使用带有
sklearn
GridSearchCV
的自定义回归器。它的精神类似于创建一个自定义分类器——如本博客所示:

下面是博客中代码的浓缩/编辑部分,展示了一些需要重写的方法

from sklearn.base import BaseEstimator, RegressorMixin

class MyCustomClassifier(BaseEstimator, RegressorMixin):  
    """An example of classifier"""

    def __init__(self, intValue=0, stringParam="defaultValue", otherParam=None):
        """
        Called when initializing the classifier
        """
        self.intValue = intValue
        self.stringParam = stringParam

    def fit(self, X, y=None):
        self.treshold_ = (sum(X)/len(X)) + self.intValue  # mean + intValue

        return self

    def _meaning(self, x):
        # returns True/False according to fitted classifier
        # notice underscore on the beginning
        return( True if x >= self.treshold_ else False )

    def predict(self, X, y=None):
         ..
回归器和分类器之间相同的东西很可能是
\uuuuu init\uuuuuu,fit,predict
方法:我可能可以将这些方法组合在一起。但是,与
\u意思是
的等价物呢?或其他可能不明显/不清楚的
回归器的微妙考虑因素

以下是我首先要介绍的骨架:

from sklearn.base import BaseEstimator, RegressorMixin
class MyCustomRegressor(BaseEstimator, RegressorMixin):
    def __init__(self, regressorMethod):
      self.regressorMethod = regressorMethod

    def fit(self, X, y=None):
      self.regressorMethod(X,y)
      return self

据我所知,GridSearchCv将使用
score
方法。

关于您的最后一个问题,当您调用估计器上的
.score
时,将使用
score
方法。例如,在basic中,
.score
方法返回“返回预测的确定系数R^2”对于GridSearchCV唯一重要的事情是
\uuuu init\uuuu
(对于参数),
获取参数()
设置参数()
(用于参数分配以进行调整,但这两个函数将继承自
BaseEstimator
)、
fit()
predict()
(出于明显的原因)和
score()
(只有在您未使用GridSearchCV的
评分
参数时才有必要)
仅供内部使用,如前面的
下划线()所示
。您可以使用它对数据进行一些内部处理,或使用任何其他名称或多个内部函数。它不应影响GridSearchCV的工作。GridSearchCV将克隆每个参数组合的估计器,因此,除非您在实现的函数中声明一些类级属性等,否则不需要额外的ord应该是这样的。除此之外,我不太清楚您想要什么。您能再澄清一点吗?如果您正在创建自定义回归器,您应该继承而不是
ClassifierMixin
,它将具有
分数()
方法已定义为R平方值。确定thx-我刚刚修复了
ClassifierMixin
->
RegressorMixin