[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,61 +2,178 @@
|
||||
id: wiki-2026-0508-linear-discriminant-analysis
|
||||
title: Linear Discriminant Analysis
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [ML-LDA-001]
|
||||
aliases: [LDA, Fisher Discriminant, Fisher LDA]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [machine-learning, lda, Dimensionality-Reduction, classification, Statistics]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [machine-learning, classification, dimensionality-reduction, supervised, sklearn]
|
||||
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: python
|
||||
framework: scikit-learn
|
||||
---
|
||||
|
||||
# Linear Discriminant [[Analysis|Analysis]] (LDA, 선형 판별 분석)
|
||||
# Linear Discriminant Analysis
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "집단 내부의 결속은 다지고, 집단 사이의 거리는 벌려 세상의 경계를 가장 선명하게 투영하라" — 클래스 간 분산(Between-class variance)과 클래스 내 분산(Within-class variance)의 비율을 최대화하여, 데이터를 가장 잘 분류할 수 있는 저차원 공간으로 투영하는 지도 학습 기반 차원 축소 기법.
|
||||
## 매 한 줄
|
||||
> **"매 LDA = 클래스 간 분산은 최대, 클래스 내 분산은 최소가 되는 축을 찾는 supervised dim reduction"**. Fisher (1936)가 제안한 방법으로 PCA가 variance-maximizing이라면 LDA는 separability-maximizing. 동시에 Gaussian + 공분산 동일 가정 하에서 optimal Bayes classifier가 된다.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** "Separability Maximization" — 정답 레이블(Label) 정보를 활용하여, 서로 다른 클래스가 겹치지 않고 가장 뚜렷하게 구분되는 최적의 투영 축을 찾아내는 분류 지향적 특징 추출 패턴.
|
||||
- **PCA와의 차이점:**
|
||||
- **PCA:** 데이터 전체의 분산이 큰 축을 찾음 (비지도 학습). 정보 손실 최소화 중심.
|
||||
- **LDA:** 클래스 간 구분이 잘 되는 축을 찾음 (지도 학습). 분류 성능 극대화 중심.
|
||||
- **의의:** 얼굴 인식, 마케팅 타겟 분류 등 특징 데이터가 많고 클래스가 명확한 환경에서 연산 효율과 분류 정확도를 동시에 잡는 강력한 도구.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 데이터가 정규 분포를 따르고 공분산 구조가 같아야 한다는 엄격한 가정이 있으나, 실제 복잡한 데이터에서는 비선형적 한계를 극복하기 위해 커널 LDA 등으로 확장되어 사용됨.
|
||||
- **정책 변화:** Antigravity 프로젝트는 에이전트의 행동 로그에서 특정 '사용자 의도'를 패턴별로 분류하여 시각화할 때, 의도 간 차이를 가장 잘 보여주는 LDA 투영 기법을 활용함.
|
||||
### 매 핵심 수식
|
||||
- $S_W = \sum_c \sum_{x \in c}(x - \mu_c)(x - \mu_c)^T$ — within-class scatter.
|
||||
- $S_B = \sum_c n_c (\mu_c - \mu)(\mu_c - \mu)^T$ — between-class scatter.
|
||||
- 목적: $\arg\max_W \frac{|W^T S_B W|}{|W^T S_W W|}$.
|
||||
- 해: $S_W^{-1} S_B$의 top eigenvector — 최대 (C-1)개 (C: class 수).
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Dimensionality-Reduction|Dimensionality-Reduction]], [[Supervised-Learning-Foundations|Supervised-Learning-Foundations]], [[Exploratory-Data-Analysis|Exploratory-Data-Analysis]], [[Pattern-Recognition|Pattern-Recognition]]-Foundations
|
||||
- **Raw Source:** 10_Wiki/Topics/AI/Linear-Discriminant-Analysis.md
|
||||
### 매 LDA vs PCA
|
||||
| 항목 | PCA | LDA |
|
||||
|---|---|---|
|
||||
| 지도/비지도 | 비지도 | 지도 |
|
||||
| 목적 | variance 최대 | class separability 최대 |
|
||||
| 출력 차원 한계 | min(n, d) | C-1 |
|
||||
| 가정 | 없음 (centered) | Gaussian, 공분산 동일 |
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 분류기로서의 LDA
|
||||
- 각 class가 같은 공분산 Σ를 가진 Gaussian이라 가정.
|
||||
- Decision boundary가 linear.
|
||||
- QDA (Quadratic): 공분산이 class별로 다름 → quadratic boundary.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### 매 한계
|
||||
- 클래스 분포가 비-Gaussian이면 약함.
|
||||
- Class 불균형 시 majority에 끌림.
|
||||
- 비선형 boundary 못함 → Kernel LDA / NDA.
|
||||
- C-1 차원 제약 → 2-class면 1차원만.
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### 매 응용
|
||||
1. Face recognition (Fisherfaces).
|
||||
2. 의료 진단 (small classes, Gaussian-ish).
|
||||
3. Document classification (TF-IDF 후).
|
||||
4. EEG/생체신호 분류.
|
||||
5. PCA 후 분류 직전 supervision으로 dim 줄이기.
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
## 💻 패턴
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
### sklearn — 기본 분류
|
||||
```python
|
||||
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
|
||||
from sklearn.model_selection import cross_val_score
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
lda = LinearDiscriminantAnalysis()
|
||||
print(cross_val_score(lda, X, y, cv=5).mean())
|
||||
lda.fit(X_tr, y_tr)
|
||||
print("priors:", lda.priors_, "means shape:", lda.means_.shape)
|
||||
```
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
### LDA를 dim reduction으로 사용
|
||||
```python
|
||||
lda = LinearDiscriminantAnalysis(n_components=2)
|
||||
X_2d = lda.fit_transform(X, y) # (n, 2) — class별로 시각화
|
||||
import matplotlib.pyplot as plt
|
||||
for c in np.unique(y):
|
||||
plt.scatter(X_2d[y==c, 0], X_2d[y==c, 1], label=str(c), alpha=.6)
|
||||
plt.legend(); plt.show()
|
||||
```
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
### LDA + Logistic 비교
|
||||
```python
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
from sklearn.pipeline import Pipeline
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
models = {
|
||||
"lda": LinearDiscriminantAnalysis(),
|
||||
"logreg": Pipeline([("sc", StandardScaler()), ("lr", LogisticRegression(max_iter=2000))]),
|
||||
}
|
||||
for name, m in models.items():
|
||||
print(name, cross_val_score(m, X, y, cv=5).mean())
|
||||
# Gaussian/공분산 동일에 가까우면 LDA가 logreg보다 안정적
|
||||
```
|
||||
|
||||
### Shrinkage LDA — 고차원/소표본
|
||||
```python
|
||||
# d >> n 일 때 S_W가 singular → shrinkage 사용
|
||||
lda = LinearDiscriminantAnalysis(solver="lsqr", shrinkage="auto") # Ledoit-Wolf
|
||||
lda.fit(X, y)
|
||||
```
|
||||
|
||||
### QDA — 공분산 다를 때
|
||||
```python
|
||||
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
|
||||
qda = QuadraticDiscriminantAnalysis(reg_param=0.01).fit(X_tr, y_tr)
|
||||
print(qda.score(X_te, y_te))
|
||||
```
|
||||
|
||||
### From scratch — eigenvalue 풀이
|
||||
```python
|
||||
import numpy as np
|
||||
def lda_fit(X, y, n_components=None):
|
||||
classes = np.unique(y); d = X.shape[1]
|
||||
mean_total = X.mean(0)
|
||||
Sw = np.zeros((d, d)); Sb = np.zeros((d, d))
|
||||
for c in classes:
|
||||
Xc = X[y == c]
|
||||
mc = Xc.mean(0)
|
||||
Sw += (Xc - mc).T @ (Xc - mc)
|
||||
Sb += len(Xc) * np.outer(mc - mean_total, mc - mean_total)
|
||||
eigvals, eigvecs = np.linalg.eig(np.linalg.pinv(Sw) @ Sb)
|
||||
idx = np.argsort(-eigvals.real)
|
||||
W = eigvecs[:, idx[:n_components or len(classes)-1]].real
|
||||
return W
|
||||
|
||||
W = lda_fit(X, y, n_components=2)
|
||||
X_proj = X @ W
|
||||
```
|
||||
|
||||
### Pipeline — PCA → LDA
|
||||
```python
|
||||
from sklearn.decomposition import PCA
|
||||
pipe = Pipeline([
|
||||
("pca", PCA(n_components=50)), # 1차로 dim 줄임 (S_W singular 회피)
|
||||
("lda", LinearDiscriminantAnalysis(n_components=9)), # 10-class 가정
|
||||
("clf", LogisticRegression()),
|
||||
]).fit(X_tr, y_tr)
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Class별 Gaussian + 공분산 동일 | LDA (분류 + dim reduction) |
|
||||
| Class별 공분산 다름 | QDA |
|
||||
| d >> n 또는 small sample | Shrinkage LDA |
|
||||
| 비-Gaussian / 비선형 | Kernel LDA, tree, NN |
|
||||
| 시각화 (class-aware) | LDA(n_components=2 또는 3) |
|
||||
|
||||
**기본값**: `StandardScaler` 후 sklearn `LinearDiscriminantAnalysis(solver="lsqr", shrinkage="auto")`.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Supervised-Learning]], [[Dimensionality-Reduction]]
|
||||
- 변형: [[Quadratic-Discriminant-Analysis]], [[Kernel-LDA]]
|
||||
- 응용: [[Fisherfaces]], [[Image-Classification]], [[Bioinformatics]]
|
||||
- Adjacent: [[PCA]], [[Logistic-Regression-Foundations]], [[Naive-Bayes]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: PCA vs LDA 결정 가이드, scatter matrix 직관 설명, shrinkage 파라미터 해석.
|
||||
**언제 X**: covariance 동일성 통계 검정 — Box's M test 등 statistician 영역.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Scaling 안 함**: 큰 scale feature가 scatter matrix 지배.
|
||||
- **C-1 차원 초과 요구**: 수학적으로 불가능.
|
||||
- **Class 매우 불균형**: priors 자동값으로 거대 majority 쏠림.
|
||||
- **고차원 소표본 raw LDA**: S_W singular → shrinkage 또는 PCA 선행.
|
||||
- **비-Gaussian 무시**: outlier 한 개로 전체 boundary 흔들림.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Fisher 1936, ESL Ch.4, sklearn 1.5+).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Shrinkage/QDA, from-scratch eigen, PCA→LDA pipeline |
|
||||
|
||||
Reference in New Issue
Block a user