我想检查通过交叉验证的新方法的预测错误。我想知道是否可以将我的方法传递给sklearn的交叉验证功能,以及如何传递给我。
我想要类似的东西sklearn.cross_validation(cv=10).mymethod。
sklearn.cross_validation(cv=10).mymethod
我还需要知道如何定义mymethod它应该是一个函数以及哪个输入元素和哪个输出
mymethod
例如,我们可以考虑将其作为mymethod最小二乘估计器(当然不是sklearn中的估计器)的实现。
我找到了本教程链接,但对我来说还不是很清楚。
他们在文档中使用
>>> 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
但是问题在于,他们正在使用clf通过sklearn内置函数获得的估计量。我应该如何定义自己的估算器才能将其传递给cross_validation.cross_val_score函数?
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. >>>
答案还在于sklearn的文档中。
您需要定义两件事:
实现fit(X, y)函数的估计量,X它是带有输入的矩阵,y是输出的向量
fit(X, y)
X
y
可以与以下功能一起使用的计分器功能或可调用对象:scorer(estimator, X, y)并返回给定模型的分数
scorer(estimator, X, y)
参考您的示例:首先,scorer不应该是估计器的方法,它是不同的概念。只需创建一个可调用对象:
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'(文档的此部分提供完整列表)cross_val_score以使用预定义的计分器。
'mean_squared_error'
'accuracy'
cross_val_score
另一种可能性是使用make_scorer工厂功能。
make_scorer
至于第二件事,你可以通过传递参数给你的模型fit_params dict的参数cross_val_score功能(在文档中提到)。这些参数将传递给fit函数。
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')