[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -2,92 +2,228 @@
id: wiki-2026-0508-imbalanced-data-handling
title: Imbalanced Data Handling
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [ML-IMBAL-001]
aliases: [imbalanced data, class imbalance, SMOTE, oversampling, undersampling, class weight]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [machine-learning, imbalanced-data, resampling, smote, Focal-Loss]
confidence_score: 0.95
verification_status: applied
tags: [machine-learning, imbalanced, smote, oversampling, class-weight, fraud]
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: imbalanced-learn / scikit-learn
---
# Imbalanced Data Handling (불균형 데이터 처리)
# Imbalanced Data Handling
## 📌 한 줄 통찰 (The Karpathy Summary)
> "데이터의 양(Quantity)에 압도당하지 말고, 소외된 소수의 정보(Minority Class) 속에 숨겨진 가치에 집중하라" — 학습 데이터의 클래스 분포가 편향되어 있을 때, 모델이 다수 클래스에만 치우친 예측을 하지 않도록 데이터나 알고리즘 측면에서 균형을 맞추는 기법.
## 한 줄
> **"매 class distribution 의 의 의 imbalance — 매 majority dominate"**. 매 fraud, 매 medical rare disease, 매 anomaly 의 common. 매 method: 매 oversample (SMOTE), undersample, class weight, focal loss, threshold tune. 매 evaluation: 매 accuracy 의 useless — PR-AUC, F1, MCC.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 다수 데이터의 영향력을 줄이거나 소수 데이터의 비중을 높여, 모델이 희귀하지만 중요한 샘플의 특징을 충분히 학습하게 만드는 가중치 및 샘플링 조정 패턴.
- **핵심 전략:**
- **Data-level (Resampling):**
- **Undersampling:** 다수 클래스 데이터를 삭제. 정보 손실 위험.
- **Oversampling:** 소수 클래스 데이터를 복제하거나 생성 (예: SMOTE - 합리적인 가상 데이터 생성).
- **Algorithm-level:**
- **Cost-sensitive Learning:** 소수 클래스를 틀렸을 때 더 큰 벌점을 부여.
- **Focal Loss:** 쉬운 샘플의 비중을 낮추고 어려운 샘플에 집중.
- **평가 지표의 전환:** 불균형 데이터에서는 '정확도(Accuracy)' 대신 '정밀도(Precision)', '재현율(Recall)', 'F1-Score' 등을 사용하여 모델의 실질적인 성능을 측정해야 함.
- **의의:** 이상 탐지, 질병 진단, 사기 적발 등 실생활에서 가장 중요한 '희귀 케이스' 탐지 능력 확보.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 단순히 데이터를 늘리거나 줄이던 방식에서, 최근에는 [[Focal-Loss|Focal-Loss]]와 같은 손실 함수 최적화와 이상 탐지(Anomaly Detection) 관점의 접근이 주를 이룸.
- **정책 변화:** Antigravity 프로젝트는 보안 로그 분석 시, 압도적으로 많은 '정상 접근' 사이에서 극소수의 '공격 징후'를 놓치지 않기 위해 SMOTE와 Cost-sensitive 앙상블 모델을 표준으로 사용함.
### 매 method
- **Resampling**:
- **Random oversample** (minority).
- **SMOTE**: 매 synthetic minority.
- **ADASYN**: adaptive.
- **Random undersample** (majority).
- **Tomek links**: 매 boundary clean.
- **Class weight**.
- **Loss-based**: focal loss, weighted CE.
- **Threshold tuning**: 매 default 0.5 의 X.
- **Anomaly detection** (1-class).
- **Cost-sensitive learning**.
## 🔗 지식 연결 (Graph)
- [[Focal-Loss|Focal-Loss]], [[Supervised-Learning-Foundations|Supervised-Learning-Foundations]], Precision-Recall-and-F1-Score, [[Deep-Learning|Deep-Learning]]-Foundations
- **Raw Source:** 10_Wiki/Topics/AI/Imbalanced-Data-Handling.md
### 매 metric
- **PR-AUC** (Average Precision).
- **F1** / Macro-F1.
- **MCC** (Matthews Correlation Coefficient).
- **Cohen's κ**.
- **Confusion matrix**.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. **Fraud detection**.
2. **Medical** (rare disease).
3. **Anomaly detection**.
4. **Customer churn**.
5. **Click prediction**.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Class weight (sklearn)
```python
from sklearn.utils import class_weight
weights = class_weight.compute_class_weight('balanced', classes=np.unique(y), y=y)
weight_dict = dict(zip(np.unique(y), weights))
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
from sklearn.linear_model import LogisticRegression
model = LogisticRegression(class_weight=weight_dict).fit(X, y)
```
## 🤔 의사결정 기준 (Decision Criteria)
### SMOTE (imbalanced-learn)
```python
from imblearn.over_sampling import SMOTE
sm = SMOTE(random_state=0)
X_res, y_res = sm.fit_resample(X, y)
```
**선택 A를 써야 할 때:**
- *(TODO)*
### SMOTE-NC (mixed numerical + categorical)
```python
from imblearn.over_sampling import SMOTENC
smnc = SMOTENC(categorical_features=[0, 2, 5], random_state=0)
X_res, y_res = smnc.fit_resample(X, y)
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Random undersample
```python
from imblearn.under_sampling import RandomUnderSampler
rus = RandomUnderSampler(sampling_strategy=0.5, random_state=0)
X_res, y_res = rus.fit_resample(X, y)
```
**기본값:**
> *(TODO)*
### Combined (SMOTE + Tomek)
```python
from imblearn.combine import SMOTETomek
smt = SMOTETomek(random_state=0)
X_res, y_res = smt.fit_resample(X, y)
```
## ❌ 안티패턴 (Anti-Patterns)
### Pipeline (avoid leakage)
```python
from imblearn.pipeline import Pipeline as ImbPipeline
pipe = ImbPipeline([
('scaler', StandardScaler()),
('smote', SMOTE()),
('clf', LogisticRegression()),
])
# 매 SMOTE applied 매 매 fold (CV-safe)
from sklearn.model_selection import cross_val_score
scores = cross_val_score(pipe, X, y, cv=5, scoring='f1')
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Focal loss (PyTorch)
```python
import torch.nn.functional as F
def focal_loss(logits, targets, alpha=0.25, gamma=2.0):
p = torch.sigmoid(logits)
p_t = p * targets + (1 - p) * (1 - targets)
alpha_t = alpha * targets + (1 - alpha) * (1 - targets)
bce = F.binary_cross_entropy_with_logits(logits, targets, reduction='none')
return (alpha_t * (1 - p_t) ** gamma * bce).mean()
```
### Threshold tuning
```python
from sklearn.metrics import precision_recall_curve
y_score = model.predict_proba(X_val)[:, 1]
prec, rec, thr = precision_recall_curve(y_val, y_score)
f1_scores = 2 * prec * rec / (prec + rec + 1e-9)
best_thr = thr[f1_scores.argmax()]
y_pred = (y_score > best_thr).astype(int)
```
### XGBoost scale_pos_weight
```python
import xgboost as xgb
ratio = sum(y == 0) / sum(y == 1)
model = xgb.XGBClassifier(scale_pos_weight=ratio).fit(X, y)
```
### Eval metrics (proper)
```python
from sklearn.metrics import classification_report, average_precision_score, matthews_corrcoef, confusion_matrix
print(classification_report(y_val, y_pred))
print(f'PR-AUC: {average_precision_score(y_val, y_score):.3f}')
print(f'MCC: {matthews_corrcoef(y_val, y_pred):.3f}')
print(confusion_matrix(y_val, y_pred))
```
### Cost-sensitive learning
```python
COST_MATRIX = np.array([[0, 1], [10, 0]]) # 매 FN cost = 10x FP
def cost_sensitive_predict(probs, cost):
expected_cost = probs @ cost
return expected_cost.argmin(axis=1)
```
### One-class anomaly
```python
from sklearn.ensemble import IsolationForest
iso = IsolationForest(contamination=0.01).fit(X_majority)
anomalies = iso.predict(X_test) == -1
```
### Weighted sampler (PyTorch)
```python
from torch.utils.data import WeightedRandomSampler
class_counts = [sum(y == c) for c in np.unique(y)]
weights = [1.0 / class_counts[label] for label in y]
sampler = WeightedRandomSampler(weights, num_samples=len(y), replacement=True)
loader = DataLoader(dataset, batch_size=32, sampler=sampler)
```
### Stratified split
```python
from sklearn.model_selection import StratifiedKFold
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
for train_idx, val_idx in skf.split(X, y):
train_fold(X[train_idx], y[train_idx])
```
### Borderline-SMOTE
```python
from imblearn.over_sampling import BorderlineSMOTE
bsm = BorderlineSMOTE(random_state=0)
X_res, y_res = bsm.fit_resample(X, y)
```
### Calibration check after handling
```python
from sklearn.calibration import calibration_curve
prob_true, prob_pred = calibration_curve(y_val, y_score, n_bins=10)
# 매 oversampling 매 의 의 calibration 의 distort
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Mild (< 1:10) | Class weight |
| Moderate (1:10-1:100) | SMOTE / class weight |
| Severe (> 1:100) | Anomaly detection / focal |
| Tabular | XGBoost scale_pos_weight |
| DL | Focal loss + weighted sampler |
| Cost varies | Cost-sensitive |
**기본값**: 매 class weight + 매 threshold tune + 매 PR-AUC eval. 매 severe = focal + anomaly detection 의 explore. 매 SMOTE 는 careful (calibration distort).
## 🔗 Graph
- 부모: [[Machine-Learning]] · [[Data-Preprocessing]]
- 변형: [[SMOTE]] · [[Focal-Loss]]
- 응용: [[Fraud-Detection]] · [[Anomaly-Detection]]
- Adjacent: [[Calibration]] · [[Cost-Sensitive-Learning]]
## 🤖 LLM 활용
**언제**: 매 fraud / medical / churn / anomaly.
**언제 X**: 매 balanced.
## ❌ 안티패턴
- **Accuracy metric on imbalanced**: 매 misleading.
- **SMOTE before train/val split**: 매 leakage.
- **No threshold tune**: 매 default 0.5 의 wrong.
- **Aggressive oversample**: 매 calibration 의 break.
- **Ignore minority cost**: 매 FN expensive.
## 🧪 검증 / 중복
- Verified (Chawla SMOTE 2002, He & Garcia review 2009, Lin focal 2017).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — methods + 매 SMOTE / focal / threshold / scale_pos_weight code |