[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,88 +2,263 @@
|
||||
id: wiki-2026-0508-decision-trees-and-random-forest
|
||||
title: Decision Trees and Random Forests
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [TREE-001]
|
||||
aliases: [decision tree, random forest, CART, Gini, entropy, bagging, ensemble, OOB]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [machine-learning, decision-tree, random-forest, ensemble, classification]
|
||||
confidence_score: 0.93
|
||||
verification_status: applied
|
||||
tags: [decision-tree, random-forest, bagging, ensemble, classical-ml, interpretable, scikit-learn]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-26
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: Python
|
||||
framework: scikit-learn
|
||||
---
|
||||
|
||||
# [[Decision Tree|Decision Tree]]s and Random Forests (의사결정 나무와 랜덤 포레스트)
|
||||
# Decision Trees & Random Forests
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "데이터를 예/아니오의 질문으로 쪼개고, 수많은 나무의 의견을 모아 정확한 결론을 내려라" — 직관적인 규칙 기반 분류기인 의사결정 나무와, 여러 나무의 예측을 결합하여 과적합을 방지하고 성능을 극대화한 앙상블 모델인 랜덤 포레스트.
|
||||
## 매 한 줄
|
||||
> **"매 if-else tree + 매 ensemble"**. 매 interpretable + 매 strong baseline. 매 CART (Classification And Regression Tree). 매 Random Forest = 매 N tree 의 bagging. 매 vs Boosting (XGBoost, LightGBM): bagging 의 reduce variance, boosting 의 reduce bias.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** 정보를 가장 잘 구분할 수 있는 질문(불순도 최소화)을 순차적으로 던져 영역을 분할하는 구조와, 여러 독립적인 모델의 결론을 투표(Voting)나 평균을 통해 통합하는 앙상블 패턴.
|
||||
- **핵심 요소:**
|
||||
- **Entropy / Gini Impurity:** 데이터의 혼잡도를 측정하여 분기 기준 결정.
|
||||
- **Bagging (Bootstrap Aggregating):** 데이터셋의 일부를 무작위로 추출하여 여러 나무 학습.
|
||||
- **Feature Randomness:** 각 분기마다 특징(Feature) 중 일부만 선택하여 나무들 간의 다양성 확보.
|
||||
- **장점:** 설명 가능성이 높고(나무 한 그루 기준), 데이터 전처리가 적게 필요하며, 정형 데이터 처리에 매우 강력함.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 단순한 규칙 기반 시스템에서, 수천 개의 나무가 협력하여 복잡한 비선형 관계를 학습하는 고성능 머신러닝 모델로 진화.
|
||||
- **정책 변화:** Antigravity 프로젝트는 정형화된 로그 데이터 분석 및 장애 유형 초기 분류 시, 연산 속도가 빠르고 안정적인 랜덤 포레스트 모델을 활용함.
|
||||
### Decision Tree
|
||||
- 매 root → 매 leaf 의 binary split.
|
||||
- 매 split criterion: Gini, Entropy, MSE.
|
||||
- 매 hyperparameter: max_depth, min_samples_split, min_samples_leaf.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Ensemble-Methods|Ensemble-Methods]], Machine-Learning, [[Supervised-Learning-Foundations|Supervised-Learning-Foundations]], Explainable-AI
|
||||
- **Raw Source:** 10_Wiki/Topics/AI/Decision-Trees and Random Forests.md
|
||||
### Split criterion
|
||||
- **Gini**: 매 P(misclassify).
|
||||
- **Entropy**: 매 information gain.
|
||||
- **MSE / variance reduction** (regression).
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### CART vs ID3 vs C4.5
|
||||
- **ID3** (Quinlan 1986): 매 categorical, entropy.
|
||||
- **C4.5** (Quinlan 1993): 매 ID3 + 매 continuous.
|
||||
- **CART** (Breiman 1984): 매 binary split, 매 Gini, 매 sklearn default.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### Random Forest (Breiman 2001)
|
||||
- 매 N tree (bagging + 매 feature subset).
|
||||
- 매 매 tree 의 random subsample (bootstrap).
|
||||
- 매 매 split 의 random feature subset.
|
||||
- 매 vote / average.
|
||||
- 매 OOB (Out-of-Bag) error 의 자체 validation.
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### Bagging vs Boosting
|
||||
| 측면 | Bagging (RF) | Boosting (XGBoost) |
|
||||
|---|---|---|
|
||||
| Tree training | Parallel | Sequential |
|
||||
| Goal | Variance ↓ | Bias ↓ |
|
||||
| Sensitive to noise | Less | More |
|
||||
| Default winner | Robust baseline | SOTA accuracy |
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
### 매 응용
|
||||
1. **Tabular**: 매 baseline.
|
||||
2. **Feature importance**: 매 model interpretability.
|
||||
3. **Variable selection**.
|
||||
4. **Imbalanced (with class weight)**.
|
||||
5. **Mixed type** (categorical + numeric).
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
### 매 strength
|
||||
- 매 no scaling 필요.
|
||||
- 매 mixed feature OK.
|
||||
- 매 outlier 의 robust.
|
||||
- 매 fast.
|
||||
- 매 interpretable (single tree).
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
### 매 weakness
|
||||
- 매 single tree 의 high variance.
|
||||
- 매 RF 의 deep tree 의 overfit.
|
||||
- 매 high-dim sparse (NLP) 의 weak.
|
||||
- 매 extrapolation 의 X (regression).
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
## 💻 패턴
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
### Decision Tree
|
||||
```python
|
||||
from sklearn.tree import DecisionTreeClassifier, plot_tree
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
clf = DecisionTreeClassifier(
|
||||
criterion='gini',
|
||||
max_depth=5,
|
||||
min_samples_split=20,
|
||||
min_samples_leaf=10,
|
||||
random_state=42,
|
||||
)
|
||||
clf.fit(X_train, y_train)
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
# 매 visualize
|
||||
plt.figure(figsize=(20, 10))
|
||||
plot_tree(clf, feature_names=feature_names, class_names=class_names, filled=True)
|
||||
plt.show()
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Random Forest
|
||||
```python
|
||||
from sklearn.ensemble import RandomForestClassifier
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
rf = RandomForestClassifier(
|
||||
n_estimators=500,
|
||||
max_depth=10,
|
||||
min_samples_split=10,
|
||||
max_features='sqrt', # 매 √n 의 feature per split
|
||||
bootstrap=True,
|
||||
oob_score=True,
|
||||
n_jobs=-1,
|
||||
random_state=42,
|
||||
class_weight='balanced', # 매 imbalanced 의 case
|
||||
)
|
||||
rf.fit(X_train, y_train)
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
print(f'OOB: {rf.oob_score_:.3f}')
|
||||
print(f'Test: {rf.score(X_test, y_test):.3f}')
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Feature importance
|
||||
```python
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
importances = pd.DataFrame({
|
||||
'feature': feature_names,
|
||||
'importance': rf.feature_importances_,
|
||||
}).sort_values('importance', ascending=False)
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
print(importances.head(10))
|
||||
```
|
||||
|
||||
### Permutation importance (more robust)
|
||||
```python
|
||||
from sklearn.inspection import permutation_importance
|
||||
|
||||
result = permutation_importance(rf, X_test, y_test, n_repeats=10, random_state=42, n_jobs=-1)
|
||||
|
||||
for i in result.importances_mean.argsort()[::-1][:10]:
|
||||
if result.importances_mean[i] - 2 * result.importances_std[i] > 0:
|
||||
print(f'{feature_names[i]:<20} {result.importances_mean[i]:.3f} ± {result.importances_std[i]:.3f}')
|
||||
```
|
||||
|
||||
### SHAP
|
||||
```python
|
||||
import shap
|
||||
|
||||
explainer = shap.TreeExplainer(rf)
|
||||
shap_values = explainer.shap_values(X_test)
|
||||
|
||||
# 매 global
|
||||
shap.summary_plot(shap_values, X_test, feature_names=feature_names)
|
||||
|
||||
# 매 local
|
||||
shap.force_plot(explainer.expected_value[0], shap_values[0][0], X_test.iloc[0])
|
||||
```
|
||||
|
||||
### Hyperparameter tune (Optuna)
|
||||
```python
|
||||
import optuna
|
||||
|
||||
def objective(trial):
|
||||
params = {
|
||||
'n_estimators': trial.suggest_int('n_estimators', 100, 1000),
|
||||
'max_depth': trial.suggest_int('max_depth', 3, 20),
|
||||
'min_samples_split': trial.suggest_int('mss', 2, 50),
|
||||
'min_samples_leaf': trial.suggest_int('msl', 1, 30),
|
||||
'max_features': trial.suggest_categorical('mf', ['sqrt', 'log2', None]),
|
||||
}
|
||||
rf = RandomForestClassifier(**params, n_jobs=-1, random_state=42)
|
||||
rf.fit(X_train, y_train)
|
||||
return rf.score(X_val, y_val)
|
||||
|
||||
study = optuna.create_study(direction='maximize')
|
||||
study.optimize(objective, n_trials=50)
|
||||
```
|
||||
|
||||
### Extra Trees (extreme RF)
|
||||
```python
|
||||
from sklearn.ensemble import ExtraTreesClassifier
|
||||
|
||||
et = ExtraTreesClassifier(
|
||||
n_estimators=500,
|
||||
bootstrap=False, # 매 default no bootstrap
|
||||
n_jobs=-1,
|
||||
)
|
||||
# 매 더 random + 매 매 fast.
|
||||
```
|
||||
|
||||
### Cost-sensitive (imbalanced)
|
||||
```python
|
||||
class_weight = {0: 1, 1: 10} # 매 minority 의 10× weight
|
||||
|
||||
rf = RandomForestClassifier(
|
||||
n_estimators=300,
|
||||
class_weight=class_weight, # 매 dict or 'balanced'
|
||||
n_jobs=-1,
|
||||
)
|
||||
```
|
||||
|
||||
### Decision rules extraction
|
||||
```python
|
||||
from sklearn.tree import _tree
|
||||
|
||||
def extract_rules(tree, feature_names):
|
||||
tree_ = tree.tree_
|
||||
feature_name = [
|
||||
feature_names[i] if i != _tree.TREE_UNDEFINED else 'undefined'
|
||||
for i in tree_.feature
|
||||
]
|
||||
|
||||
def recurse(node, path):
|
||||
if tree_.feature[node] != _tree.TREE_UNDEFINED:
|
||||
name = feature_name[node]
|
||||
threshold = tree_.threshold[node]
|
||||
yield from recurse(tree_.children_left[node], path + [f'{name} <= {threshold:.2f}'])
|
||||
yield from recurse(tree_.children_right[node], path + [f'{name} > {threshold:.2f}'])
|
||||
else:
|
||||
yield (path, tree_.value[node])
|
||||
|
||||
return list(recurse(0, []))
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Algorithm |
|
||||
|---|---|
|
||||
| Quick baseline | Random Forest |
|
||||
| Need interpretability | Single decision tree |
|
||||
| Best accuracy (tabular) | XGBoost / LightGBM |
|
||||
| Mixed types | RF |
|
||||
| Imbalanced | RF + class_weight |
|
||||
| Cross-functional explanation | RF + SHAP |
|
||||
| Real-time inference | Decision tree (cheap) |
|
||||
|
||||
**기본값**: Random Forest as baseline + XGBoost as upgrade.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Classical-ML]] · [[Ensemble-Methods]]
|
||||
- 변형: [[CART]] · [[Random-Forest]] · [[Extra-Trees]] · [[Boosting-Algorithms-XGBoost-LightGBM]]
|
||||
- 응용: [[Feature-Importance]] · [[SHAP]] · [[Tabular-ML]]
|
||||
- Adjacent: [[Bias-vs-Variance]] · [[Causal-Inference]] (Causal Forest) · [[Cross-Entropy Loss]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 tabular ML. 매 baseline. 매 interpretable model.
|
||||
**언제 X**: 매 image / NLP / sequence (use NN). 매 strict accuracy (use boosting).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Default hyperparameter**: 매 task-specific tune 필요.
|
||||
- **No regularization** (deep + small data): 매 overfit.
|
||||
- **Single tree 의 scale 의 expect**: 매 ensemble 필요.
|
||||
- **Feature importance 의 single source**: 매 SHAP / permutation 도 cross-check.
|
||||
- **High-dim sparse data**: 매 wrong tool.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Breiman Random Forest 2001, scikit-learn docs, ESL).
|
||||
- 신뢰도 A.
|
||||
- Related: [[Boosting-Algorithms-XGBoost-LightGBM]] · [[Bias-vs-Variance]] · [[Causal-Inference]] · [[Cross-Entropy Loss]].
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — CART + RF + 매 sklearn / Optuna / SHAP / rules code |
|
||||
|
||||
Reference in New Issue
Block a user