04. Decision Tree 완전정복
Gini, Entropy, 가지치기(Pruning), Feature Importance
학습 목표
이 튜토리얼을 완료하면 다음을 할 수 있습니다:
- Gini Impurity와 Entropy의 수학적 원리와 차이점 이해
- Information Gain을 통한 분기 기준 선택 과정을 단계별로 계산
- Graphviz를 활용하여 트리 구조를 시각화하고 해석
- Pruning (가지치기) 기법을 통한 Overfitting 방지
- Feature Importance 분석 및 해석
- 하이퍼파라미터 튜닝을 통한 최적 트리 구조 탐색
핵심 개념
1. Decision Tree란?
Decision Tree(결정 트리)는 if-else 규칙의 연속으로 데이터를 분류하는 알고리즘입니다. 데이터를 **질문(조건)**으로 분할하여 예측하는 트리 구조 모델입니다.
[Root Node]
/ \
[Internal] [Internal]
/ \ / \
[Leaf] [Leaf] [Leaf] [Leaf]Decision Tree는 White-box 모델로, 의사결정 과정을 시각화하고 해석할 수 있어 모델의 예측 근거를 설명하기 쉽습니다.
2. 불순도 (Impurity) 지표
Decision Tree는 불순도를 최소화하는 방향으로 데이터를 분할합니다.
Gini Impurity (지니 불순도)
Gini = 1 - Σ(pᵢ)²pᵢ: 클래스 i의 비율- 범위: [0, 1 - 1/C]
- 0: 완전 순수 (한 클래스만)
- 0.5: 최대 불순 (2클래스 동일 비율)
예시 (이진 분류):
- 노드에 A:50개, B:50개 → Gini = 1 - (0.5² + 0.5²) = 0.5
- 노드에 A:90개, B:10개 → Gini = 1 - (0.9² + 0.1²) = 0.18
- 노드에 A:100개, B:0개 → Gini = 1 - (1.0² + 0.0²) = 0.0
Entropy (엔트로피)
Entropy = -Σ pᵢ log₂(pᵢ)- 정보 이론에서 유래한 불확실성 측정
- 범위: [0, log₂C]
- 완전 순수: Entropy = 0
- 완전 불순: Entropy = log₂C
예시 (이진 분류):
- A:50개, B:50개 → Entropy = 1.0
- A:90개, B:10개 → Entropy ≈ 0.469
- A:100개, B:0개 → Entropy = 0
Gini vs Entropy 선택: 실제 성능 차이는 미미하지만, Gini가 연산이 빠릅니다 (로그 계산 불필요). Entropy는 불순도에 더 민감하게 반응합니다.
Information Gain (정보 이득)
분할 전후의 불순도 감소량을 측정합니다.
IG = Impurity(parent) - Σ(weighted) Impurity(children)Decision Tree는 Information Gain이 최대가 되는 분할을 선택합니다.
3. 분할 과정
- 모든 피처와 분할점에서 불순도 감소량 계산
- 가장 큰 감소를 주는 분할 선택
- 재귀적으로 반복
- 종료 조건 도달 시 Leaf 노드 생성
4. Pruning (가지치기)
Overfitting을 방지하기 위해 트리의 성장을 제한합니다.
Pre-Pruning (사전 가지치기)
| 파라미터 | 설명 |
|---|---|
max_depth | 트리 최대 깊이 |
min_samples_split | 노드 분할을 위한 최소 샘플 수 |
min_samples_leaf | Leaf 노드의 최소 샘플 수 |
max_leaf_nodes | 최대 Leaf 노드 수 |
Post-Pruning (사후 가지치기)
# Cost Complexity Pruning (ccp_alpha)
path = tree.cost_complexity_pruning_path(X_train, y_train)
alphas = path.ccp_alphas
# CV로 최적 alpha 찾기
for alpha in alphas:
clf = DecisionTreeClassifier(ccp_alpha=alpha)
scores = cross_val_score(clf, X_train, y_train, cv=5)Post-pruning 팁: 완전히 자란 트리에서 ccp_alpha 경로를 계산한 후, Cross-Validation으로 최적의 alpha 값을 찾는 것이 효과적입니다.
5. Feature Importance
# Gini 기반 중요도
importances = model.feature_importances_
# 시각화
pd.Series(importances, index=feature_names).sort_values().plot(kind='barh')Feature Importance는 해당 피처가 분류에 기여한 정도를 나타내며, Feature Selection에 활용할 수 있습니다.
코드 요약
from sklearn.tree import DecisionTreeClassifier, plot_tree, export_text
from sklearn.model_selection import cross_val_score, GridSearchCV
# 기본 모델
tree = DecisionTreeClassifier(random_state=42)
tree.fit(X_train, y_train)
# 과적합 방지 (Pre-pruning)
tree_pruned = DecisionTreeClassifier(
max_depth=5,
min_samples_split=10,
min_samples_leaf=5,
random_state=42
)
# 트리 구조 시각화
import matplotlib.pyplot as plt
plt.figure(figsize=(20, 10))
plot_tree(tree_pruned, feature_names=feature_names,
class_names=class_names, filled=True, rounded=True)
plt.show()
# 텍스트로 트리 규칙 출력
print(export_text(tree_pruned, feature_names=list(feature_names)))GridSearchCV를 이용한 하이퍼파라미터 튜닝
from sklearn.model_selection import GridSearchCV
param_grid = {
'criterion': ['gini', 'entropy'],
'max_depth': [None, 3, 5, 7, 10],
'min_samples_split': [2, 5, 10],
'min_samples_leaf': [1, 2, 4],
'max_features': ['sqrt', 'log2', None]
}
grid = GridSearchCV(
DecisionTreeClassifier(random_state=42),
param_grid,
cv=5,
scoring='accuracy',
n_jobs=-1
)
grid.fit(X_train, y_train)
print(f"Best params: {grid.best_params_}")
print(f"Best CV Score: {grid.best_score_:.4f}")장단점
| 장점 | 단점 |
|---|---|
| 해석이 쉬움 (White-box 모델) | 과적합 경향 |
| 스케일링 불필요 | 불안정 (데이터 변화에 민감, High Variance) |
| 비선형 관계 학습 | 성능 한계 |
| 범주형 + 수치형 동시 처리 가능 | 축에 수직인 경계만 생성 |
과적합 주의: 깊은 트리는 Train 데이터를 외우기 쉽습니다. Train Accuracy가 1.0에 가까워지면 Overfitting 신호입니다. 반드시 Pruning을 적용하세요!
회귀 vs 분류
| 문제 | 분할 기준 | Leaf 예측값 |
|---|---|---|
| 분류 | Gini / Entropy | 다수 클래스 |
| 회귀 | MSE / MAE | 평균값 |
from sklearn.tree import DecisionTreeRegressor
reg_tree = DecisionTreeRegressor(max_depth=5)
reg_tree.fit(X_train, y_train)핵심 정리 체크리스트
| 항목 | 설명 |
|---|---|
| 불순도 지표 | Gini (빠름) vs Entropy (민감) - 성능 차이 미미 |
| Information Gain | 분할 후 불순도 감소량이 최대가 되는 Feature/값 선택 |
| Overfitting 방지 | max_depth, min_samples_split, min_samples_leaf 조절 |
| Post-pruning | ccp_alpha로 비용-복잡도 가지치기 |
| Feature Importance | 분류에 기여한 정도, Feature Selection에 활용 |
면접 질문 맛보기
- Gini와 Entropy의 차이점은?
- Decision Tree의 과적합을 어떻게 방지하나요?
- Feature Importance는 어떻게 계산되나요?
- Decision Tree가 축에 수직인 경계만 생성하는 이유는?
더 많은 면접 질문은 Premium Interviews (opens in a new tab)에서 확인하세요.
실습 노트북
노트북에서는 다음 추가 내용을 다룹니다:
- Gini Impurity와 Entropy 직접 구현 및 시각화
- Information Gain 단계별 수동 계산
- Iris와 Wine 두 데이터셋에 대한 실습
- Decision Boundary 시각화 (max_depth별 비교)
- Cost Complexity Pruning 상세 분석
- Learning Curve를 통한 모델 진단
- Feature Selection 효과 분석
이전: 03. Logistic Regression | 다음: 05. Ensemble Methods