如何在sklearn中编写自定义估算器并对其进行交叉验证?

时间:2013-12-02 14:17:53

标签: python scikit-learn

我想通过交叉验证来检查新方法的预测误差。 我想知道我是否可以将我的方法传递给sklearn的交叉验证函数以及如何。

我想要sklearn.cross_validation(cv=10).mymethod

我还需要知道如何定义mymethod它应该是一个函数以及哪个输入元素和哪个输出

例如,我们可以将mymethod视为最小二乘估计的实现(当然不是sklearn中的那些)。

我找到了这个教程link,但对我来说并不是很清楚。

他们使用的documentation

>>> import numpy as np
>>> from sklearn import cross_validation
>>> from sklearn import datasets
>>> from sklearn import svm

>>> iris = datasets.load_iris()
>>> iris.data.shape, iris.target.shape
((150, 4), (150,))

 >>> clf = svm.SVC(kernel='linear', C=1) 
 >>> scores = cross_validation.cross_val_score(
 ...    clf, iris.data, iris.target, cv=5)
 ...
 >>> scores      

但问题是他们使用的是由sklearn中构建的函数获得的估算器clf。我应该如何定义自己的估算器,以便将其传递给cross_validation.cross_val_score函数?

例如,假设一个简单的估计器使用线性模型$ y = x \ beta $,其中beta估计为X [1,:] + alpha,其中alpha是参数。我该如何填写代码?

class my_estimator():
      def fit(X,y):
          beta=X[1,:]+alpha #where can I pass alpha to the function?
          return beta
      def scorer(estimator, X, y) #what should the scorer function compute?
          return ?????

使用以下代码我收到错误:

class my_estimator():
    def fit(X, y, **kwargs):
        #alpha = kwargs['alpha']
        beta=X[1,:]#+alpha 
        return beta

>>> cv=cross_validation.cross_val_score(my_estimator,x,y,scoring="mean_squared_error")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\scikit_learn-0.14.1-py2.7-win32.egg\sklearn\cross_validation.py", line 1152, in cross_val_score
    for train, test in cv)
  File "C:\Python27\lib\site-packages\scikit_learn-0.14.1-py2.7-win32.egg\sklearn\externals\joblib\parallel.py", line 516, in __call__
    for function, args, kwargs in iterable:
  File "C:\Python27\lib\site-packages\scikit_learn-0.14.1-py2.7-win32.egg\sklearn\cross_validation.py", line 1152, in <genexpr>
    for train, test in cv)
  File "C:\Python27\lib\site-packages\scikit_learn-0.14.1-py2.7-win32.egg\sklearn\base.py", line 43, in clone
    % (repr(estimator), type(estimator)))
TypeError: Cannot clone object '<class __main__.my_estimator at 0x05ACACA8>' (type <type 'classobj'>): it does not seem to be a scikit-learn estimator a it does not implement a 'get_params' methods.
>>> 

1 个答案:

答案 0 :(得分:24)

答案还在于sklearn的documentation

您需要定义两件事:

  • 实现fit(X, y)函数的估算工具,X是带输入的矩阵,y是输出向量

  • 可以与scorer(estimator, X, y)一起使用的记分器函数或可调用对象,并返回给定模型的分数

参考你的例子:首先,scorer不应该是估算器的方法,它是一个不同的概念。只需创建一个可调用的:

def scorer(estimator, X, y)
    return ?????  # compute whatever you want, it's up to you to define
                  # what does it mean that the given estimator is "good" or "bad"

甚至是一个更简单的解决方案:您可以将字符串'mean_squared_error''accuracy'this part of the documentation中提供的完整列表)传递给cross_val_score函数,以使用预定义的记分员。

另一种可能性是使用make_scorer工厂功能。

至于第二件事,您可以通过cross_val_score函数的fit_params dict参数将参数传递给模型(如文档中所述)。这些参数将传递给fit函数。

class my_estimator():
    def fit(X, y, **kwargs):
        alpha = kwargs['alpha']
        beta=X[1,:]+alpha 
        return beta

在阅读了所有错误消息后,这些消息非常清楚地知道缺少什么,这是一个简单的例子:

import numpy as np
from sklearn.cross_validation import cross_val_score

class RegularizedRegressor:
    def __init__(self, l = 0.01):
        self.l = l

    def combine(self, inputs):
        return sum([i*w for (i,w) in zip([1] + inputs, self.weights)])

    def predict(self, X):
        return [self.combine(x) for x in X]

    def classify(self, inputs):
        return sign(self.predict(inputs))

    def fit(self, X, y, **kwargs):
        self.l = kwargs['l']
        X = np.matrix(X)
        y = np.matrix(y)
        W = (X.transpose() * X).getI() * X.transpose() * y

        self.weights = [w[0] for w in W.tolist()]

    def get_params(self, deep = False):
        return {'l':self.l}

X = np.matrix([[0, 0], [1, 0], [0, 1], [1, 1]])
y = np.matrix([0, 1, 1, 0]).transpose()

print cross_val_score(RegularizedRegressor(),
                      X,
                      y, 
                      fit_params={'l':0.1},
                      scoring = 'mean_squared_error')