I'm trying to make my own BaseEstimator class to use it as part of a pipeline but i can't make it work. Here's what I get: TypeError: score() takes 2 positional arguments but 3 were given
I’ve already tried to add self argument to the score function, but it doesn’t work: i have a ValueError instead.
When i make a separate model and then use that function separately, everything is just fine
class MyRegressor(BaseEstimator):
def __init__(self, regressor_type: str = 'SGDRegressor'):
"""
"""
self.regressor_type = regressor_type
def fit(self, X, y):
if self.regressor_type == 'SGDRegressor':
self.regressor_ = SGDRegressor()
elif self.regressor_type == 'RandomForestRegressor':
self.regressor_ = RandomForestRegressor()
elif self.regressor_type == 'LinearRegression':
self.regressor_ = LinearRegression()
elif self.regressor_type == 'CatBoostRegressor':
self.regressor_ = CatBoostRegressor()
elif self.regressor_type == 'XGBRegressor':
self.regressor_ = XGBRegressor()
else:
raise ValueError('Unknown regressor type.')
self.regressor_.fit(X, y)
return self
def predict(self, X):
y_pred = self.regressor_.predict(X)
return y_pred
def score(y, y_pred):
smape = sum(abs(y - y_pred) / (abs(y) + abs(y_pred)) / 2) * 100 / len(y)
return self.estimator.smape(y, y_pred)
pipe = Pipeline([('scaler', StandardScaler()), ('MyRegressor', MyRegressor())])
pipe.fit(X_train, y_train_final)
params = {
'MyRegressor__regressor_type': ['SGDRegressor', 'RandomForestRegressor', 'LinearRegression', 'CatBoostRegressor', 'XGBRegressor']
}
search = GridSearchCV(pipe , params, n_jobs=-1, cv=5)
search.fit(X_train, y_train_final)
print('Best model:
', search.best_params_)
Please help me to solve this issue. Thank you in advance!
question from:
https://stackoverflow.com/questions/65940709/how-to-fix-score-function-for-it-to-work-with-gridsearchcv-typeerror-score-t 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…