CART 하이퍼파라미터 튜닝

Python으로 배우는 트리 기반 Machine Learning

Elie Kawerk

Data Scientist

하이퍼파라미터

머신러닝 모델:

  • parameters: 데이터에서 학습

    • CART 예: 노드 분할점, 노드 분할 특성 등
  • hyperparameters: 학습 전 설정, 데이터에서 학습되지 않음

    • CART 예: max_depth, min_samples_leaf, 분할 기준 등
Python으로 배우는 트리 기반 Machine Learning

하이퍼파라미터 튜닝이란?

  • 문제: 학습 알고리즘의 최적 하이퍼파라미터 탐색

  • 해결: 최적 모델을 만드는 하이퍼파라미터 찾기

  • 최적 모델: 최적의 score 달성

  • Score: sklearn에서 기본은 정확도(분류), $R^2$(회귀)

  • 일반화 성능 추정에 교차검증 사용

Python으로 배우는 트리 기반 Machine Learning

왜 튜닝해야 하나요?

  • sklearn의 기본 하이퍼파라미터는 모든 문제에 최적이 아님

  • 성능 향상을 위해 하이퍼파라미터를 튜닝해야 함

Python으로 배우는 트리 기반 Machine Learning

하이퍼파라미터 튜닝 방법

  • 그리드 서치

  • 랜덤 서치

  • 베이즈 최적화

  • 유전 알고리즘

  • ...

Python으로 배우는 트리 기반 Machine Learning

그리드 서치 교차검증

  • 이산 하이퍼파라미터 그리드를 수동 설정

  • 성능 평가 지표 설정

  • 그리드를 전수 탐색

  • 각 하이퍼파라미터 조합에 대해 CV 점수 평가

  • 최고 CV 점수의 모델 하이퍼파라미터가 최적값

Python으로 배우는 트리 기반 Machine Learning

그리드 서치 교차검증: 예시

  • 하이퍼파라미터 그리드:
    • max_depth = {2,3,4},
    • min_samples_leaf = {0.05, 0.1}
  • 하이퍼파라미터 공간 = { (2,0.05) , (2,0.1) , (3,0.05), ... }
  • CV 점수 = { $score_{(2,0.05)}$ , ... }
  • 최적 하이퍼파라미터 = 최고 CV 점수에 해당하는 하이퍼파라미터 집합
Python으로 배우는 트리 기반 Machine Learning

sklearn에서 CART 하이퍼파라미터 확인

# Import DecisionTreeClassifier
from sklearn.tree import DecisionTreeClassifier

# Set seed to 1 for reproducibility
SEED = 1

# Instantiate a DecisionTreeClassifier 'dt'
dt = DecisionTreeClassifier(random_state=SEED)

Python으로 배우는 트리 기반 Machine Learning

sklearn에서 CART 하이퍼파라미터 확인

# Print out 'dt's hyperparameters
print(dt.get_params())
        {'class_weight': None,
         'criterion': 'gini',
         'max_depth': None,
         'max_features': None,
         'max_leaf_nodes': None,
         'min_impurity_decrease': 0.0,
         'min_impurity_split': None,
         'min_samples_leaf': 1,
         'min_samples_split': 2,
         'min_weight_fraction_leaf': 0.0,
         'presort': False,
         'random_state': 1,
         'splitter': 'best'}
Python으로 배우는 트리 기반 Machine Learning
# Import GridSearchCV
from sklearn.model_selection import GridSearchCV

# Define the grid of hyperparameters 'params_dt' params_dt = { 'max_depth': [3, 4,5, 6], 'min_samples_leaf': [0.04, 0.06, 0.08], 'max_features': [0.2, 0.4,0.6, 0.8] }
# Instantiate a 10-fold CV grid search object 'grid_dt' grid_dt = GridSearchCV(estimator=dt, param_grid=params_dt, scoring='accuracy', cv=10, n_jobs=-1)
# Fit 'grid_dt' to the training data grid_dt.fit(X_train, y_train)
Python으로 배우는 트리 기반 Machine Learning

최적 하이퍼파라미터 추출

# Extract best hyperparameters from 'grid_dt'
best_hyperparams = grid_dt.best_params_
print('Best hyerparameters:\n', best_hyperparams)
Best hyerparameters:
  {'max_depth': 3, 'max_features': 0.4, 'min_samples_leaf': 0.06}
# Extract best CV score from 'grid_dt'
best_CV_score = grid_dt.best_score_
print('Best CV accuracy'.format(best_CV_score))
Best CV accuracy: 0.938
Python으로 배우는 트리 기반 Machine Learning

최적 추정기 추출

# Extract best model from 'grid_dt'
best_model = grid_dt.best_estimator_

# Evaluate test set accuracy test_acc = best_model.score(X_test,y_test) # Print test set accuracy print("Test set accuracy of best model: {:.3f}".format(test_acc))
Test set accuracy of best model: 0.947
Python으로 배우는 트리 기반 Machine Learning

Passons à la pratique !

Python으로 배우는 트리 기반 Machine Learning

Preparing Video For Download...