let us not love with words or tongue but actions and truth.

IT/파이썬

GridSearchCV 그리드서치 1탄

sarah0518 2020. 12. 21. 17:11

xfrita s 이미지 참조

 

모델별로 best성능을 만들어 줄수있는 hyper parameter값을 찾아야 될 경우가 있을텐데요.

그때 유용하게 사용되는 Grid Search CV에 대해서 알아보도록 할게요.

 

우선 각 모델별로 가장 기본적인 모델을 선언해줄게요.

 

 

1
2
3
4
5
6
7
8
9
10
11
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import GradientBoostingClassifier
import xgboost
from xgboost import XGBClassifier
 
def clf3():
    rfc = RandomForestClassifier()
    gb = GradientBoostingClassifier() 
    xg = XGBClassifier()
  
    return rfc, gb, xg
cs

 

 

 

그 다음은, 각 모델별 하이퍼파라미터 값을 설정해줍니다. (보통 log단위로 증가한다고 생각하시면되요)

저는 다음에도 동일한 값을 불러오게 하고 싶어서 radom_state값을 임의값이 99로 정해놨습니다.

 

1
2
3
4
rf_parameters ={'max_depth' : [3,4,5,6,7,8] , 'n_estimators': [3,4, 5,10], 'random_state':[99]}
gb_parameters ={'max_depth' : [4,5,7] , 'n_estimators': [3,4, 5,10,30], 'learning_rate':[0.01, 0.1], 'random_state':[99]}
xg_parameters ={'max_depth' : [3,4,5,6] , 'n_estimators': [12,24,32], 'learning_rate':[0.01, 0.1], 'gamma': [0.5, 1, 2], 'random_state':[99]}
 
cs

 

 

우리가 사전에 define했던 함수를 통해 모델을 불러오고,

RFC모델에 대한 best hyper parameter값의 결과를 확인할 수 있습니다.

 

1
2
3
4
5
6
7
8
9
from sklearn import model_selection
rfc, gb, xg = clf3()
#RFC모델에 대한 grid search, scoring기준은 recall값으로, cross-validation은 10회 반복한다는 뜻임
grid_search_rf = model_selection.GridSearchCV ( estimator = rfc, param_grid = rf_parameters, scoring = 'recall', cv = 10 )
 
grid_search_rf.fit( x2, y )
#best hyper parameter값을 받음
best_rfc = grid_search_rf.best_estimator_
best_rfc
cs

 

[output]

RandomForestClassifier(max_depth=7, n_estimators=10, random_state=99)

> RFC모델에서의 max_depth=7로(분류트리의 깊이), n_estimators=10(트리의 개수)로 설정시에 가장 좋은 recall값이 나온다고 생각하시면 됩니다.

참고로, n_estimator의 default값은 100인데, 제가 쓴 모형은 data sample수도 작고, 과적합을 방지시키기위해 트리개수를 작게 했습니다.

 

 

 

그 다음은 XG Boost에 대한 Grid Search에 대한 내용입니다.

1
2
3
4
grid_search_xg = model_selection.GridSearchCV ( estimator = xg, param_grid = xg_parameters, scoring = 'recall', cv = 10 )
grid_search_xg.fit( x2, y )
best_xg = grid_search_xg.best_estimator_
best_xg
cs

 

[output]

XGBClassifier( gamma=3, learning_rate=0.01, max_depth=10, n_estimators=10, random_state=99 )

 

 

 

마지막으로 GB에 대한 내용입니다.

1
2
3
4
grid_search_gb = model_selection.GridSearchCV ( estimator = gb, param_grid = gb_parameters, scoring = 'recall', cv = 10 )
grid_search_gb.fit( x2, y )
best_gb = grid_search_gb.best_estimator_
best_gb
cs

 

[output]

GradientBoostingClassifier(max_depth=5, n_estimators=30, random_state=99)

 

 

 

 

혹시 For문을 통해 GridSearchCV과정을 확인하는 방법을 알고싶다면!!

 

아래 링크를 클릭해주세요!

 

 

sarah0518.tistory.com/75

 

GridSearchCV 2탄 (for문 활용)

지난번과 동일한 GridSearchCV이지만 약간은 다른 방식으로 진행해보려고 합니다. sarah0518.tistory.com/50?category=984180 GridSearchCV 그리드서치 1탄 모델별로 best성능을 만들어 줄수있는 hyper parameter..

sarah0518.tistory.com