Post

GridSearch 사용 방법 및 학습 과정 시각화

Hypyer Parameter Tunning 중 GridSearch의 사용 방법 및 학습 과정 시각화 방법을 알아보자.

✅ Scikit-learn을 활용한 GridSearch

1
2
3
4
5
6
from sklearn.model_selection import GridSearchCV

params = {'learning_rate' : np.linspace(0.01, 0.5, 20), 'n_estimators' : [50, 100, 150]}

model = GridSearchCV(XGBClassifier(), params, cv = 5)
model.fit(train_x, train_y)
GridSearchCV(cv=5,
             estimator=XGBClassifier(base_score=None, booster=None,
                                     callbacks=None, colsample_bylevel=None,
                                     colsample_bynode=None,
                                     colsample_bytree=None,
                                     early_stopping_rounds=None,
                                     enable_categorical=False, eval_metric=None,
                                     feature_types=None, gamma=None,
                                     gpu_id=None, grow_policy=None,
                                     importance_type=None,
                                     interaction_constraints=None,
                                     learning_rate=None,...
                                     n_estimators=100, n_jobs=None,
                                     num_parallel_tree=None, predictor=None,
                                     random_state=None, ...),
             param_grid={'learning_rate': array([0.01      , 0.03578947, 0.06157895, 0.08736842, 0.11315789,
       0.13894737, 0.16473684, 0.19052632, 0.21631579, 0.24210526,
       0.26789474, 0.29368421, 0.31947368, 0.34526316, 0.37105263,
       0.39684211, 0.42263158, 0.44842105, 0.47421053, 0.5       ]),
                         'n_estimators': [50, 100, 150]})
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.

✅ GridSearch 학습 과정 시각화

model.cv_results_에는 학습 과정에 대한 많은 정보가 들어있다.

1
2
3
4
5
6
7
result = pd.DataFrame(model.cv_results_)

plt.figure(figsize = (10, 6))
sns.lineplot(x = 'param_learning_rate', y = 'mean_test_score', data = result,
             marker = 'o', hue = 'param_n_estimators')
plt.grid()
plt.show()

output_3_0

✅ KNN에 사용 예시

1
2
3
4
5
6
7
8
9
10
11
12
params = {'n_neighbors' : range(3, 100, 2), 'metric' : ['manhattan', 'euclidean']}

model = GridSearchCV(KNeighborsClassifier(), params, cv=5)
model.fit(train_x_s, train_y)

result = pd.DataFrame(model.cv_results_)

plt.figure(figsize = (10, 6))
sns.lineplot(x = 'param_n_neighbors', y = 'mean_test_score', data = result,
             marker = 'o', hue = 'param_metric')
plt.grid()
plt.show()

output_5_0

✅ GridSearchCV 변수에 들어있는 정보들

기본적으로 GridSearch 후 model.predict를 하면 자동으로 가장 좋은 성능의 모델로 predict를 진행한다. 하지만 feature_importances_ 같은 경우는 자동으로 모델을 잡아주지 않아 에러가 난다. 이런 경우, model.best_estimator_가 가장 좋은 성능의 모델을 가지고 있음으로 model.best_estimator_.feature_importances_로 사용하면 된다. (KNN과 같이 feature_importances_를 가지고 있지 않는 모델의 경우엔 당연히 에러가 날것임)

또한, model.best_score_, model.best_params_ 으로 최고 성능을 보여줬을 때의 score 값과 parameter 값을 확인할 수 있다. 이때 score 값은 GridSearchCV에서 넣어준 scoring=에 해당하는 값이다. 값을 넣어주지 않으면 default로 분류문제는 accuracy, 회귀 문제는 r2 이다.

1
model.best_score_, model.best_params_
1
(0.73, {'metric': 'euclidean', 'n_neighbors': 15})
This post is licensed under CC BY 4.0 by the author.

가변수화, One-Hot Encoding(원핫인코딩) 방법

Class Imbalance