하이퍼파라미터 튜닝

R로 배우는 트리 기반 Machine Learning

Sandro Raabe

Data Scientist

하이퍼파라미터

  • 트리의 형태와 복잡도에 영향
  • 학습 전 설정하여 모델 복잡도를 제어하는 파라미터

parsnip 결정트리의 하이퍼파라미터:

  • min_n: 노드 분할에 필요한 최소 샘플 수
  • tree_depth: 허용되는 최대 트리 깊이
  • cost_complexity: 트리 복잡도에 대한 패널티
R로 배우는 트리 기반 Machine Learning

왜 튜닝할까요?

parsnip의 기본값:

decision_tree(min_n = 20, tree_depth = 30, cost_complexity = 0.01)
  • 많은 경우에 무난하지만, 모든 데이터셋에 최적은 아님

 

튜닝의 목표는 하이퍼파라미터의 최적 조합을 찾는 것입니다.

R로 배우는 트리 기반 Machine Learning

tune 패키지로 tidymodels에서 튜닝

빈 튜닝 그리드

R로 배우는 트리 기반 Machine Learning

tidymodels로 튜닝

더미 사양

R로 배우는 트리 기반 Machine Learning

tidymodels로 튜닝

그리드 포인트마다 학습된 모델이 하나씩 있는 튜닝 그리드

R로 배우는 트리 기반 Machine Learning

tidymodels로 튜닝

성능이 가장 좋은 그리드 포인트 선택

R로 배우는 트리 기반 Machine Learning

1단계: 자리표시자 생성: tune()

spec_untuned <- decision_tree(

min_n = tune(), tree_depth = tune()
) %>% set_engine("rpart") %>% set_mode("classification")
Decision Tree Model Specification 
(classification)


Main Arguments: tree_depth = tune() min_n = tune()
  • tune()으로 튜닝 대상 파라미터 표시
  • 나머지 사양은 동일
R로 배우는 트리 기반 Machine Learning

2단계: 튜닝 그리드 생성: grid_regular()

tree_grid <- grid_regular(

parameters(spec_untuned),
levels = 3 )
# A tibble: 9 x 2
  min_n tree_depth
1     2          1
2    21          1
3    40          1
4     2          8
5    21          8
6    40          8
7     2         15
8    21         15
9    40         15
  • 보조 함수 parameters()
  • levels: 각 하이퍼파라미터의 그리드 포인트 수
R로 배우는 트리 기반 Machine Learning

3단계: 그리드 튜닝: tune_grid()

  • 각 그리드 포인트마다 모델 학습
  • 모든 모델을 OOS(CV)로 평가

 

사용법 및 인자:

  • 미튜닝 트리 사양
  • 모델 포뮬러
  • CV 폴드
  • 튜닝 그리드
  • metric_set()으로 감싼 메트릭 목록
tune_results <- tune_grid(

spec_untuned,
outcome ~ .,
resamples = my_folds,
grid = tree_grid,
metrics = metric_set(accuracy))
R로 배우는 트리 기반 Machine Learning

튜닝 결과 시각화

autoplot(tune_results)

튜닝 결과

R로 배우는 트리 기반 Machine Learning

4단계: 최적 파라미터 적용: finalize_model()

# 가장 성능이 좋은 파라미터 선택
final_params <- select_best(tune_results)

final_params
# A tibble: 1 x 3
    min_n    tree_depth    .config
    <int>         <int>      <chr>
1      2              8     Model4
# 사양에 반영
best_spec <- finalize_model(spec_untuned, 
                            final_params)

best_spec
Decision Tree Model Specification 
                 (classification)

Main Arguments:
  tree_depth = 8
  min_n = 2

Computational engine: rpart
R로 배우는 트리 기반 Machine Learning

튜닝해 봅시다!

R로 배우는 트리 기반 Machine Learning

Preparing Video For Download...