簡體   English   中英

如何實現 sklearn 的 Estimator 接口以在 GridSearchCV 管道中使用?

[英]How to implement sklearn's Estimator interface for use in GridSearchCV pipeline?

所以我有自己的感知器分類器實現,並想使用 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, SVM
from sklearn.model_selection import GridSearchCV

class 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):派生該類,以避免樣板並遵循擬合預測結構。 正如@Shihab 在評論中所說,您的 fit 函數缺少return self代碼行。

另外,在 get_params() 中我不知道你是不是故意這樣做的,但是文檔中的參數 deep 也建議默認將其設置為deep=True 請檢查一下。

set_paramsfit方法應該返回self

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM