如何实现sklearn的Estimator接口以用于GridSearchCV管道?

我有一个自己的感知机分类器实现,并希望使用sklearn的GridSearchCV来调整其超参数。我尝试编写一个包装器来实现Estimator接口(阅读了https://scikit-learn.org/stable/developers/develop.html),但当我运行GridSearchCV(wrapper, params).fit(X,y)时,出现了以下错误:

FitFailedWarning: Estimator fit failed. The score on this train-test partition for these parameters will be set to nan. Details:AttributeError: 'NoneType' object has no attribute 'fit'  FitFailedWarning)Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\model_selection\_search.py", line 738, in fit    **self.best_params_))  File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\base.py", line 67, in clone    % (repr(estimator), type(estimator)))TypeError: Cannot clone object 'None' (type <class 'NoneType'>): it does not seem to be a scikit-learn estimator as it does not implement a 'get_params' methods.

这个错误与如何在sklearn中编写自定义估计器并对其使用交叉验证?完全相同,但我已经做了顶级评论中提出的所有建议。

我确信模型是正确的。以下是模型包装器的代码:

from models import Perceptron, Softmax, SVMfrom sklearn.model_selection import GridSearchCVclass Estimator():    def __init__(self, alpha=0.5, epochs=100):        self.alpha = alpha        self.epochs = epochs        self.model = Perceptron()    def fit(self, X, y, **kwargs):        self.alpha = kwargs['alpha']        self.epochs = kwargs['epochs']        self.model.alpha = kwargs['alpha']        self.model.epochs = kwargs['epochs']        self.model.train(X, y)    def predict(self, X):        return self.model.predict(X)    def score(self, data, targets):        return self.model.get_acc(self.predict(data), targets)    def set_params(self, alpha, epochs):        self.alpha = alpha        self.epochs = epochs        self.model.alpha = alpha        self.model.epochs = epochs    def get_params(self, deep=False):        return {'alpha':self.alpha, 'epochs':self.epochs}

回答:

文档的这一部分所解释的,您应该从BaseEstimator派生类class Estimator(BaseEstimator):,以避免重复代码并遵循fit predict结构。正如@Shihab在评论中所说,您的fit函数缺少return self代码行。

另外,在get_params()中,我不知道您是否有意为之,但文档中推荐的参数deep默认应设置为deep=True。请检查一下。

Related Posts

多维度Top-k评分

例如,在机器学习中的自然语言处理中,通常使用波束搜索来…

R – Caret train() “错误:停止” 与 “在newdata中未找到对象中使用的所有变量名”

我正在尝试为蘑菇数据构建一个简单的朴素贝叶斯分类器。我…

创建训练和测试数据集分割,数据嵌套在多个文件夹中

我正在准备数据以训练一个图像识别模型。目前我有一个文件…

我的神经网络预测出现错误:IndexError: list index out of range

我正在进行一个简单的垃圾邮件/非垃圾邮件文本分类。我的…

python 给出数组是一维的,但索引了两个维度错误

我已经为 miniBatchGradientDesce…

TensorFlow自定义训练步骤使用不同的损失函数

背景 根据TensorFlow文档,可以使用以下方式执…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注