Best_params в GridSearch - PullRequest
       13

Best_params в GridSearch

1 голос
/ 02 июля 2019

Я использовал grid_search для того, чтобы найти наилучшую комбинацию параметров, и я составил график, чтобы увидеть, как оценка меняется при изменении параметров. Когда я запускаю gs_clf.best_params_, я получаю это как лучшую комбинацию параметров: {'learning_rate': 0.01, 'n_estimators': 200} Я не понимаю, почему тогда график оценки не показывает лучший результат для этой комбинации параметров?

Мой код указан ниже.

from sklearn.ensemble import GradientBoostingClassifier
from sklearn.model_selection import GridSearchCV, StratifiedKFold, cross_val_score
from sklearn.metrics import  accuracy_score, average_precision_score, recall_score, f1_score, precision_recall_curve, auc, confusion_matrix, classification_report
import matplotlib.pyplot as plt
import numpy as np


clf = GradientBoostingClassifier(min_samples_split=300, max_depth=4, random_state=0)

kfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=0) 

number_of_estimators= [20,200]
LR=[0.01,1]

grid = GridSearchCV(clf, param_grid = dict(n_estimators=number_of_estimators,learning_rate=LR), cv=kfold, return_train_score=True, scoring = 'accuracy', pre_dispatch='1*n_jobs',n_jobs=1)

gs_clf = grid.fit(X_train, Y_train.values.ravel()) # Fit the Grid Search on Train dataset

scores = [x for x in gs_clf.cv_results_['mean_train_score']]
scores = np.array(scores).reshape(len(number_of_estimators), len(LR))

for ind, i in enumerate(number_of_estimators):
    plt.plot(LR, scores[ind], label='Number_of_estimators: ' + str(i))
plt.legend()
plt.xlabel('Learning rate')
plt.ylabel('Mean score')
plt.title('Train score')
plt.show()

scores = [x for x in gs_clf.cv_results_['mean_test_score']]
scores = np.array(scores).reshape(len(number_of_estimators), len(LR))

for ind, i in enumerate(number_of_estimators):
    plt.plot(LR, scores[ind], label='Number_of_estimators: ' + str(i))
plt.legend()
plt.xlabel('Learning rate')
plt.ylabel('Mean score')
plt.title('Validation score')
plt.show()

gs_clf.best_params

Изображения участков, которые я получаю:

График подсчета поездов

График оценки валидации

1 Ответ

0 голосов
/ 02 июля 2019

Проблема на самом деле была в том, как я показал цифры на графиках. Это правильный код для участков:

#TRAIN DATA
scores=gs_clf.cv_results_['mean_train_score']
scores = np.array(scores).reshape(len(LR), len(number_of_estimators))

for ind, i in enumerate(LR):
    plt.plot(number_of_estimators, scores[ind], label='Learning rate: ' + str(i))
plt.legend()
plt.xlabel('Number_of_estimators')
plt.ylabel('Mean score')
plt.title('Train score')
plt.show()


#VALIDATION DATA
scores=gs_clf.cv_results_['mean_test_score']
scores = np.array(scores).reshape(len(LR), len(number_of_estimators))

for ind, i in enumerate(LR):
    plt.plot(number_of_estimators, scores[ind], label='Learning rate: ' + str(i))
plt.legend()
plt.xlabel('Number_of_estimators')
plt.ylabel('Mean score')
plt.title('Validation score')
plt.show()
...