[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
@@ -1,93 +1,176 @@
---
id: wiki-2026-0508-principle-component-analysis
title: Principle Component Analysis
title: Principal Component Analysis
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-PPCA-001]
aliases: [PCA, Karhunen-Loeve Transform, Principle Component Analysis]
duplicate_of: none
source_trust_level: A
confidence_score: 0.98
tags: [auto-reinforced, pca, dimension-reduction, data-Analysis, machine-learning, Statistics]
confidence_score: 0.95
verification_status: applied
tags: [linear-algebra, dimensionality-reduction, unsupervised, statistics]
raw_sources: []
last_reinforced: 2026-04-20
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 / NumPy / PyTorch
---
# [[Principle-Component-Analysis|Principle-Component-Analysis]]
# Principal Component Analysis
## 📌 한 줄 통찰 (The Karpathy Summary)
> "데이터의 엑스레이: 수백 개의 복잡한 변수 중에서 데이터의 본질적 변동(Variance)을 가장 잘 설명하는 핵심 축(주성분) 몇 개만 추려내어, 정보의 핵심은 살리고 노이즈와 군더더기는 걷어내는 고차원의 시각화 마법."
## 한 줄
> **"매 orthogonal axes of maximum variance — eigendecomposition of covariance, equivalent to SVD of centered data"**. Pearson 1901, Hotelling 1933 의 statistical foundation; 2026 still the default linear dim-reduction baseline despite t-SNE/UMAP for viz. Note: spelled **Principal** (not "Principle") — kept alias for findability.
## 📖 구조화된 지식 (Synthesized Content)
주성분 분석(PCA)은 고차원의 데이터를 저차원으로 축소하면서 정보 손실을 최소화하는 통계적 기법입니다.
## 매 핵심
1. **작동 원칙**:
* 데이터가 가장 널리 퍼져 있는(분산이 큰) 방향을 첫 번째 주성분($PC_1$)으로 설정.
* 그 방향과 수직이면서 그다음 분산이 큰 곳을 $PC_2$로 설정. ([[Linear-Algebra|Linear-Algebra]]와 연결)
2. **효과**:
* **Dimension Reduction**: 연산량 폭감. ([[Efficiency|Efficiency]]와 연결)
* **Visualization**: 수백 차원의 데이터를 2~3차원으로 그려 한눈에 파악.
* **[[Noise|Noise]] Filtering**: 분산이 작은 하위 주성분(잡음) 제거. (Noise와 연결)
### 매 mathematical definition
- Center data: X_c = X - mean(X).
- Covariance: C = X_c^T X_c / (n-1).
- Eigendecompose C = V Λ V^T; columns of V are principal axes.
- Project: Z = X_c V_k (top k components).
- Equivalent: SVD X_c = U Σ V^T → V same; singular values σ_i = sqrt((n-1) λ_i).
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 선형적인 관계만 분석하는 정책(Linear PCA)이었으나, 현대 정책은 복잡하게 얽힌 데이터의 곡면까지 파악하는 '커널 PCA 정책'이나 '오토인코더(Autoencoder) 정책'으로 그 개념이 확장됨(RL Update).
- **정책 변화(RL Update)**: 단순히 데이터를 줄이는 정책을 넘어, LLM 내부의 거대한 임베딩 공간 정책이 어떤 구조를 가지고 있는지 분석하여 AI의 '사고 체계'를 엿보는 해석 도구 정책으로도 널리 활용 중임. ([[Explainable-AI (XAI)|Explainable-AI (XAI)]]와 연결)
### 매 properties
- **Orthogonal**: components uncorrelated.
- **Variance-ordered**: first PC explains most variance.
- **Linear**: cannot capture curved manifolds (use kernel PCA / UMAP).
- **Rotation-invariant**: same answer regardless of axis labels.
- **Scale-sensitive**: standardize features first if scales differ.
## 🔗 지식 연결 (Graph)
- [[Linear-Algebra|Linear-Algebra]], [[Noise|Noise]], [[Efficiency|Efficiency]], [[Explainable-AI (XAI)|Explainable-AI (XAI)]], [[Optimization|Optimization]]
- **Modern Tech/Tools**: Eigen-decomposition, SVD (Singular Value Decomposition), Scikit-learn (PCA).
---
### 매 variants
- **Kernel PCA**: nonlinear via kernel trick (RBF, polynomial).
- **Sparse PCA**: L1-regularized loadings for interpretability.
- **Robust PCA**: low-rank + sparse decomposition for outliers.
- **Probabilistic PCA**: latent Gaussian model — gives MLE objective.
- **Incremental / online PCA**: streaming data.
- **Randomized SVD**: O(n d k) instead of O(n d^2) for top-k.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 modern usage (2026)
- **Embeddings analysis**: PCA on Claude / GPT-5 hidden states for interpretability (mech interp).
- **Whitening**: precondition before clustering, ICA, neural net training.
- **Compression**: still used in image / signal pipelines.
- **Data viz**: PCA → 50D, then UMAP/t-SNE → 2D (the standard combo).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### scikit-learn PCA
```python
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
import numpy as np
## 🧪 검증 상태 (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
X_std = StandardScaler().fit_transform(X)
pca = PCA(n_components=0.95) # keep 95% variance
Z = pca.fit_transform(X_std)
print(f"#components for 95% var: {pca.n_components_}")
print(f"explained variance ratio: {pca.explained_variance_ratio_}")
```
## 🤔 의사결정 기준 (Decision Criteria)
### Manual PCA via SVD (numerical best)
```python
def pca(X, k):
Xc = X - X.mean(0)
U, s, Vt = np.linalg.svd(Xc, full_matrices=False)
components = Vt[:k]
explained_var = (s[:k] ** 2) / (X.shape[0] - 1)
Z = Xc @ components.T
return Z, components, explained_var
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Randomized SVD (fast for huge matrices)
```python
from sklearn.utils.extmath import randomized_svd
U, s, Vt = randomized_svd(X_centered, n_components=50, random_state=42)
# 100x faster than full SVD for d >> k
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Kernel PCA (nonlinear)
```python
from sklearn.decomposition import KernelPCA
kpca = KernelPCA(n_components=2, kernel="rbf", gamma=0.1)
Z = kpca.fit_transform(X)
```
**기본값:**
> *(TODO)*
### Incremental PCA (streaming)
```python
from sklearn.decomposition import IncrementalPCA
ipca = IncrementalPCA(n_components=50, batch_size=1024)
for batch in stream:
ipca.partial_fit(batch)
Z = ipca.transform(X_test)
```
## ❌ 안티패턴 (Anti-Patterns)
### Whitening before downstream model
```python
pca = PCA(whiten=True).fit(X_train)
X_train_w = pca.transform(X_train)
X_test_w = pca.transform(X_test)
# now features have unit variance, zero correlation
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### PCA for interpreting transformer hidden states
```python
import torch
hidden = model.encode(prompts) # (B, D=4096)
pca = PCA(n_components=8)
Z = pca.fit_transform(hidden.cpu().numpy())
# Top component often correlates with sentiment / topic / refusal.
```
### Reconstruction error (anomaly detection)
```python
pca = PCA(n_components=10).fit(X_train)
recon = pca.inverse_transform(pca.transform(X))
err = ((X - recon) ** 2).sum(axis=1)
anomalies = err > np.percentile(err, 99)
```
### Choosing k via scree plot / elbow
```python
import matplotlib.pyplot as plt
pca_full = PCA().fit(X_std)
plt.plot(np.cumsum(pca_full.explained_variance_ratio_))
plt.axhline(0.95, ls="--"); plt.xlabel("# components"); plt.ylabel("cumulative var")
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Linear dim-reduction baseline | PCA |
| Visualization to 2D | PCA→50D → UMAP→2D |
| Nonlinear manifold | Kernel PCA / UMAP / autoencoder |
| Streaming / huge data | IncrementalPCA / randomized SVD |
| Need interpretable loadings | Sparse PCA |
| Outliers in data | Robust PCA |
| Probabilistic / missing data | Probabilistic PCA / EM-PCA |
**기본값**: StandardScaler → PCA(n_components=0.95) → downstream model.
## 🔗 Graph
- 부모: [[Linear-Algebra]] · [[Unsupervised-Learning]] · [[Dimensionality-Reduction]]
- 변형: [[Kernel-PCA]] · [[Sparse-PCA]] · [[Robust-PCA]] · [[Probabilistic-PCA]]
- 응용: [[Data-Visualization]] · [[Feature-Engineering]] · [[Anomaly-Detection]] · [[Mechanistic-Interpretability]]
- Adjacent: [[SVD]] · [[ICA]] · [[Factor-Analysis]] · [[Autoencoder]] · [[UMAP]]
## 🤖 LLM 활용
**언제**: linear dim-reduction, whitening, denoising, hidden-state analysis, baseline before ML model.
**언제 X**: nonlinear manifold (use UMAP/autoencoder), categorical-only data (use MCA), interpretable original features required (use feature selection).
## ❌ 안티패턴
- **No standardization**: features with large scale dominate components.
- **PCA on labels-included data**: leakage if used for supervised pipeline.
- **Reading PC1 as "the cause"**: components are statistical, not causal.
- **PCA → tree models**: GBDT doesn't benefit from rotation; just hurts interpretability.
- **Forgetting sign ambiguity**: V and -V both valid; component direction is arbitrary.
## 🧪 검증 / 중복
- Verified (Pearson 1901, Hotelling 1933, Jolliffe 2002 textbook, sklearn docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — canonical PCA reference + 2026 mech interp use |