Как GridSearchCV научить VotingRegressor учить несколько комбинаций моделей? - PullRequest
0 голосов
/ 27 сентября 2019

Я пытаюсь GridSearch сочетать несколько лучших моделей для VotingRegressor из предыдущего GridSearch.Я получаю сообщение об ошибке: «TypeError: init () отсутствует 1 обязательный позиционный аргумент:« оценки ».

Я попытался создать Pipelin и попробовать все модели в нескольких конвейерах., но это не похоже на работу.Я также нашел решение, в котором вы добавляете все модели в gridsearch и gridsearch параметры этих моделей внутри голосования-регрессора.Я не хочу этого делать, потому что, возможно, мне бы хотелось использовать только определенные алгоритмы, а не все алгоритмы, которые я тестирую.

from sklearn.model_selection import GridSearchCV
from sklearn.neural_network import MLPRegressor
from sklearn.ensemble import VotingRegressor
from xgboost import XGBRegressor
from sklearn.ensemble import RandomForestRegressor
from itertools import chain, combinations

X_train = pd.DataFrame(data=[[0, 3, 4, 5, 6, 8], [0, 2, 1, 5, 6, 1], 
                             [3, 3, 3, 3, 6, 8], [0, 3, 4, 5, 6, 8], 
                             [0, 3, 4, 5, 6, 8], [0, 3, 4, 5, 6, 8]])
y_train = pd.Series([1, 2, 1, 2, 3, 3])

# Build all top scoring models to test them for GridSearch Voting Regressor
xgb_estimator_mae_1 = XGBRegressor(max_depth=6, n_estimators=250, n_jobs=-1, subsample=.7)
xgb_estimator_mae_2 = XGBRegressor(max_depth=5, n_estimators=25, n_jobs=-1, subsample=.9)


xgb_estimator_r2_1 = XGBRegressor(max_depth=5, n_estimators=200, n_jobs=-1, subsample=.9)
xgb_estimator_r2_2 = XGBRegressor(max_depth=5, n_estimators=50, n_jobs=-1, subsample=.9)

rf_estimator_mae_1 = RandomForestRegressor(max_depth=20, n_estimators=300, n_jobs=-1)
rf_estimator_mae_2 = RandomForestRegressor(max_depth=15, n_estimators=150, n_jobs=-1)

mlp_estimator_mae_1 = MLPRegressor(activation='relu', alpha=0.0002, hidden_layer_sizes=(200, 25, 25, 25, 50), learning_rate='adaptive')
mlp_estimator_mae_2 = MLPRegressor(activation='relu', alpha=0.0001, hidden_layer_sizes=(50, 10, 50, 50, 100), learning_rate='constant')

# Make list of all models
estimators = [('xgb_mae_1', xgb_estimator_mae_1),
              ('xgb_mae_2', xgb_estimator_mae_2),
              ('xgb_r2_1', xgb_estimator_r2_1),
              ('xgb_r2_2', xgb_estimator_r2_2),
              ('rf_mae_1', rf_estimator_mae_1),
              ('rf_mae_2', rf_estimator_mae_2),
              ('mlp_mae_1', mlp_estimator_mae_1),
              ('mlp_mae_2', mlp_estimator_mae_2),]


# Find all combinations of length 3
def powerset(iterable):
    s = list(iterable)  # allows duplicate elements
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

estimators_list = []

for i, combo in enumerate(powerset(estimators), 1):
    if len(combo)==3:
        estimators_list.append(combo)

# Set parameters for GridSearch
grid_params = {'estimators': [estimators_list],
               'weights': [(1, 1, 1), (1.5, 1, 1), (1, 1.5, 1), (1, 1, 1.5), (2, 1, 1), (1, 2, 1), (1, 1, 2), (2, 2, 1), (1, 2, 2), (2, 1, 2), (3, 2, 1), (1, 3, 2), (2, 1, 3), (3, 1, 2)],
              'n_jobs': [-1]}

clf_vr = GridSearchCV(VotingRegressor(), param_grid=grid_params, cv=3, scoring=['neg_mean_absolute_error', 'r2'])
cv_models_vr = clf_vr.fit(X_train, y_train)
df_grid_vr = pd.DataFrame(cv_models_vr.cv_results_)
df_grid_vr = df_grid.sort_values(by='rank_test_neg_mean_absolute_error')

Я хотел бы знать, как установить GridSearchCV для VotingRegressorв основном с комбинацией нескольких предыдущих моделей.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...