Hyper Parameter Tuning

Rooney Donghoon Lee
9 min readOct 23, 2020

--

Last week — Linear Regression 통해 간단한 머신러닝 모델을 만드는 법을 배웠다

This week’s topic : Tree Model

이번 주는 동일한 데이터 세트를 가지고, 트리 모델을 이용하여 분류/Classification 모델 만드는 것을 배우고, 모델의 성능을 최적화 하는 방법을 배웠다.
+ 처음으로 Kaggle에 도전하는 기회가 되었다. 매일 새로운 방법으로 모델을 최적화 하여 Kaggle Score가 높아지는것 보는것은 재미있었다.

Tree Model이라는 이름의 유래…

Decision Tree Classifier — 출처 : https://www.kdnuggets.com/

위 그림은 Decision Tree Classifier를 우리가 한눈에 보고, 설명하기 쉽게 그려진 그림이다. 우리가 만든 Model이 데이터 세트의 특성/feature를 가지고 우리가 원하는 결과/target을 예측해 나가는 모습이 마치 나뭇가지가 뻗어 가는 모습이라서 Tree Model이라는 이름이라고 한다.

이렇게 Tree Model을 하나만 만들어서 우리가 원하는 결과를 예측할 수도 있지만. 우리가 원하는 결과를 예측하는 성능을 높이기 위해서, Random Forest라는 모델을 사용할 수도 있다.

Decision Tree는 나무 한 그루로 모델을 만드는 거였다면…
RandomForest는 Forest/ '숲'이라는 이름에서 느낄 수 있듯이 숲을 이룰 만큼의 많은 Decision Tree 모델들을 만들고, 만들어진 Tree Model 들의 성능을 취합하여 만든 모델이다. (링크 첨부 필요)

Random Forest는 Decision Tree보다 좋은 성능을 보여주지만, 말 그대로, 알고리즘이 어떤, feature들을 선택해서 나무를 그리는지 관찰할 수가 없기 때문에, 성능은 좋지만, 왜 이런 결과를 도출하게 됐는지를 알고 싶을 때는 추천할 수 없는 방법이다.

그럼 여기서 드는 생각… 좋을 성능을 가진 Random Forest 모델을 만들고 싶다면 뭘 하면 될까?

RandomForestClassifier() 는 우리가 조정할 수 있는 여러가지 파라미터가 있다.

몇가지만 살펴보자면
n_estimator = ('숲'에 몇가지 tree모델을 만들것인가) 많으면 성능은 올라간다.
max_depth = 트리의 깊이/층수, (위에서 처음 보았던 모델은 6, 바로 위에있는 모델은 4)
min_sample_leaf = leaf node에 들어갈 최소 샘플의 수
max_features = 다음가지로 나뉠때 사용되될 최적의 feature의 갯수
이외의 여러가지 parameter가 있다

참고

parameter를 하나하나 조정해 보면, 모델의 성능이 증감하는것을 볼 수 있다.

우리가 직접 저 많은 변수를 수정하고, 나온 성능을 비교하고, 자료를 만들기엔 큰 노력과 시간이 들어갈 것이고, 우리가 들인 시간에 비례하는 성능을 뽑아내기란 매우 어려울 것이다.

그것을 자동으로 가능하게 해주는 아주 어썸한 기능을 scikit-learn에서 제공해준다.

바로 Randomized Search CV Grid Search CV이다.

Randomized Search CV는
지정한 범위 안에서 무작위(randomize)로 선택된 값을 Parameter에 대입하여 결과를 도출하는 방법이고

Grid Search CV는
지정한 범위에서 일정한 간격으로 선택된 값을 Parameter에 대입하는 방식이다.

Random Search CV와 Grid Search CV를 장단점을 잘 나타내 준 그림 https://www.researchgate.net/

두 방법이 완벽한것은 아닌게, Random Search CV는 지점을 무작위로 정해진 지점중에서 성능이 제일 높게 나온 것을 도출해 주는것이고,

Grid Search의 간격이 너무 넓어져 버리면, 최고성능을 내어주는 Parameter를 포함하지 않는 값을 도출 할 수가 있다.

그럼 어떻게 해결 하면 좋을까?

Random Search CV와, Grid Search CV를 각 각 사용하기보다는, Ramdom Search CV 이후, Grid Search CV를 하면, 아주 좋은 시너지를 기대 할 수 있다.

Random Search CV를 사용하여, 최고성능을 내게 해주는 값을 찾은이후. Grid Search CV를 사용하여 Random Search CV에서 최고 성능을 보여준 Parameter를 기준으로 잡고, Grid Search CV를 촘촘히 설정하여 찾으면, 최고성능을 끌어낼 수 있는 Parameter를 도출 할 수 있다.

실제 이번 캐글에서 사용한 코드로 예시를 들어 보겠다.

Random Search CV

pipe_ord = make_pipeline(
OrdinalEncoder(),
SimpleImputer(),
RandomForestClassifier(max_depth = 10, n_jobs=-1, random_state=63)
)
# Parameters 범위설정
dists = {
'simpleimputer__strategy': ['mean', 'median'],
'randomforestclassifier__n_estimators': randint(10, 1000),
'randomforestclassifier__max_depth': [5, 10, 15, 20, None],
'randomforestclassifier__max_features': uniform(0, 1),
'randomforestclassifier__class_weight': [ None, {0:1,1:2}, 'balanced_subsample'],
}
# Opimize Classificator?clf = RandomizedSearchCV(
pipe_ord,
param_distributions=dists, # 위에서 dist, 범위설정이 여기에 있다
n_iter=50, #50번 반복
cv=5, #5 fold model
scoring='f1', #f1스코어가 제일 좋은것으로.
verbose=1,
n_jobs=-1 #모든 코어 사용
)
# 모델 트레이닝 데이터로 학습 시키기
clf.fit(X_train, y_train)
-------------------------
# cv, n_iter를 어떻게 설정하느냐와, 본인 컴퓨터 CPU성능에 따라서, 모델트레이닝하는데 오랜 시간이 걸린다.
clf.best_params_ #이 코드를 치면, 최적화된 값을 출력해 준다.{'randomforestclassifier__class_weight': {0: 1, 1: 2},
'randomforestclassifier__max_depth': 10,
'randomforestclassifier__max_features': 0.4215012666998439,
'randomforestclassifier__n_estimators': 431,
'simpleimputer__strategy': 'mean'}

Random Search CV에서 얻은 결과 값으로, Grid Search CV 실행

# Random Search CV에서 찾은 최적의 hyper parameter 값을 넣어 모델을 만들었다
pipe_grid = make_pipeline(
OrdinalEncoder(),
SimpleImputer(),
RandomForestClassifier(class_weight={0: 1, 1: 2},
max_depth=10,
max_features=0.4215012666998439,
n_estimators=431, n_jobs=-1,
random_state=63)
)
# Parameter Set
dists_grid = {
# int로 넣으면 error(bug)
'simpleimputer__strategy': ['mean', 'median'],
'randomforestclassifier__max_depth': [8, 9, 10, 11, 12],
}
# Opimize Classificator?
clf_grid = GridSearchCV(
pipe_grid,
param_grid=dists_grid,
cv=5,
scoring='f1',
verbose=1,
n_jobs=-1
)
clf_grid.fit(X_train, y_train)
------------------
clf_grid.best_params_{'randomforestclassifier__max_depth': 9, 'simpleimputer__strategy': 'mean'}

Randomized Search CV + Grid Seach CV 를 통해 찾은 최적의 모델

pipe_grid = make_pipeline(
OrdinalEncoder(),
SimpleImputer('mean'),
RandomForestClassifier(class_weight={0: 1, 1: 2},
max_depth=9,
max_features=0.4215012666998439,
n_estimators=431, n_jobs=-1,
random_state=63)
)

Sign up to discover human stories that deepen your understanding of the world.

--

--

No responses yet

Write a response