[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,89 +2,183 @@
id: wiki-2026-0508-pca-and-dimension-reduction
title: PCA and Dimension Reduction
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [MATH-PCA-001]
aliases: [Principal Component Analysis, Dimensionality Reduction]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: ["Statistics|[Statistics", math, pca, dimension-reduction, unSupervised-Learning, data-science]
confidence_score: 0.9
verification_status: applied
tags: [statistics, ml, unsupervised, embeddings, visualization]
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/umap
---
# PCA and Dimension Reduction (PCA와 차원 축소)
# PCA and Dimension Reduction
## 📌 한 줄 통찰 (The Karpathy Summary)
> "데이터의 흩어짐(Variance)이 가장 큰 핵심 축을 찾아, 고차원의 안개를 걷어내고 데이터의 진정한 뼈대를 드러내라" — 변수들 사이의 상관관계를 분석하여 주성분(Principal Components)을 추출함으로써, 정보의 손실을 최소화하며 데이터의 차원을 낮추는 통계적 방법론.
## 한 줄
> **"매 high-dim 데이터를 variance 보존하는 lower-dim 부분공간으로 사영"**. Pearson 1901 / Hotelling 1933 의 PCA 가 시초. 매 2026 의 modern landscape: linear PCA 는 여전히 baseline + interpretation, t-SNE/UMAP 가 visualization 의 default, autoencoder + contrastive 가 representation learning 의 핵심. 매 LLM embedding 의 PCA whitening 도 흔함.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Variance Maximization and Orthogonal Projection" — 데이터의 분산이 가장 크게 보존되는 방향으로 좌표축을 회전시키고, 중요도가 낮은 축(고유값이 작은 축)을 제거하여 데이터의 본질적인 구조를 저차원의 평면에 투영하는 패턴.
- **핵심 단계:**
- **Standardization:** 변수들의 단위를 맞춤 (평균 0, 분산 1).
- **Covariance Matrix:** 변수 간의 관계 파악.
- **Eigen-decomposition:** 주성분 방향(고유벡터)과 중요도(고유값) 산출.
- **Projection:** 상위 k개의 주성분으로 데이터 변환.
- **의의:** 차원의 저주(Curse of Dimensionality)를 극복하고, 모델의 과적합을 방지하며, 수천 차원의 임베딩 데이터를 2D/3D로 시각화하여 인간이 이해할 수 있게 함.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 선형적인 관계만 포착할 수 있는 PCA의 한계를 넘어, 최근에는 커널 PCA나 오토인코더를 이용한 비선형 차원 축소, 그리고 t-SNE나 UMAP과 같이 데이터의 지역적 구조 보존에 특화된 시각화 기법들이 함께 활용됨.
- **정책 변화:** Antigravity 프로젝트는 1,174개 문서의 임베딩 벡터를 시각화하여 지식의 군집(Cluster) 상태를 점검할 때, PCA를 1차 필터로 사용하여 전체적인 데이터 분포를 조망함.
### 매 PCA 수학
- **목표**: orthogonal directions 중 variance 최대화.
- **계산**: covariance Σ = X^T X / (n-1) → eigendecomposition Σ = V Λ V^T, top-k columns = principal components.
- **SVD form**: X = UΣV^T → top-k V_k 가 components, score = X V_k.
- **Explained variance ratio**: λ_i / Σ λ_j.
- **Whitening**: X V_k Λ_k^{-1/2} → unit variance per dim.
## 🔗 지식 연결 (Graph)
- Principal-Component-[[Analysis|Analysis]]-PCA, [[Multivariate-Analysis|Multivariate-Analysis]], [[Exploratory-Data-Analysis|Exploratory-Data-Analysis]], Autoencoders-in-[[Deep-Learning|Deep-Learning]]
- **Raw Source:** 10_Wiki/Topics/AI/PCA-and-Dimension-Reduction.md
### 매 family
- **Linear**: PCA, Truncated SVD, Factor Analysis, ICA.
- **Manifold (preserve local)**: t-SNE, UMAP, LLE, Isomap.
- **Neural**: Autoencoder, VAE, contrastive (SimCLR), DINO.
- **Random**: Random projection (Johnson-Lindenstrauss).
- **Sparse**: Sparse PCA, NMF.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Visualization (t-SNE, UMAP for embeddings/scRNA-seq).
2. Compression (PCA whitening before downstream task).
3. Denoising (project, then reconstruct).
4. Feature engineering pre-classifier.
5. LLM embedding analysis (cluster interpretation, anisotropy fix).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### sklearn PCA
```python
from sklearn.decomposition import PCA
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 = np.random.randn(1000, 100)
pca = PCA(n_components=10, whiten=True, random_state=42)
X_proj = pca.fit_transform(X)
print(pca.explained_variance_ratio_.cumsum()) # 누적 explained
print(pca.components_.shape) # (10, 100)
```
## 🤔 의사결정 기준 (Decision Criteria)
### Choose k via cumulative variance
```python
def choose_k(X, threshold=0.95):
pca = PCA().fit(X)
cum = pca.explained_variance_ratio_.cumsum()
return int(np.searchsorted(cum, threshold) + 1)
```
**선택 A를 써야 할 때:**
- *(TODO)*
### Truncated SVD (sparse / very large)
```python
from sklearn.decomposition import TruncatedSVD
from scipy.sparse import csr_matrix
**선택 B를 써야 할 때:**
- *(TODO)*
X_sparse = csr_matrix(X) # 매 PCA centers → dense; TruncatedSVD 매 sparse-friendly
svd = TruncatedSVD(n_components=50, n_iter=7, random_state=42)
X_proj = svd.fit_transform(X_sparse) # 매 LSA 의 핵심
```
**기본값:**
> *(TODO)*
### UMAP (manifold, fast)
```python
import umap
## ❌ 안티패턴 (Anti-Patterns)
reducer = umap.UMAP(
n_neighbors=15, # local vs global
min_dist=0.1, # cluster separation
n_components=2,
metric="cosine", # 매 LLM embedding
random_state=42,
)
X_2d = reducer.fit_transform(X)
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### t-SNE (visualization)
```python
from sklearn.manifold import TSNE
# 매 항상 PCA → t-SNE (속도/안정성)
X_pca = PCA(n_components=50).fit_transform(X)
X_2d = TSNE(n_components=2, perplexity=30, init="pca",
learning_rate="auto").fit_transform(X_pca)
```
### Autoencoder (PyTorch)
```python
import torch.nn as nn
class AE(nn.Module):
def __init__(self, d_in, d_latent):
super().__init__()
self.enc = nn.Sequential(
nn.Linear(d_in, 256), nn.GELU(),
nn.Linear(256, d_latent),
)
self.dec = nn.Sequential(
nn.Linear(d_latent, 256), nn.GELU(),
nn.Linear(256, d_in),
)
def forward(self, x):
z = self.enc(x); return self.dec(z), z
# loss = MSE(x, x_hat). Nonlinear PCA 의 generalization.
```
### LLM embedding whitening (anisotropy 완화)
```python
def whiten_embeddings(E, k=None):
"""Anisotropy fix: subtract mean, decorrelate."""
mu = E.mean(axis=0, keepdims=True)
Ec = E - mu
U, S, Vt = np.linalg.svd(Ec, full_matrices=False)
if k is None:
k = E.shape[1]
W = (Vt[:k].T) / S[:k] # whitening matrix
return Ec @ W, mu, W
```
### Random projection (very high-dim, fast)
```python
from sklearn.random_projection import GaussianRandomProjection
rp = GaussianRandomProjection(n_components="auto", eps=0.1)
X_proj = rp.fit_transform(X) # 매 Johnson-Lindenstrauss 보존
```
## 매 결정 기준
| 상황 | Method |
|---|---|
| baseline, interpretable | PCA |
| sparse text-term-matrix | TruncatedSVD (LSA) |
| visualization 2D/3D | UMAP > t-SNE |
| nonlinear, learnable, downstream supervised | Autoencoder / SimCLR |
| n >> d, very high-dim | Random projection |
| non-negative parts (topics) | NMF |
| count data | LDA / NMF |
**기본값**: 매 baseline PCA → 매 visualization UMAP → 매 representation learning contrastive.
## 🔗 Graph
- 부모: [[Linear-Algebra-Foundations]] · [[Statistics]] · [[Unsupervised Learning]]
- 변형: [[Kernel PCA]] · [[Sparse PCA]] · [[Probabilistic PCA]] · [[ICA]]
- 응용: [[Visualization]] · [[scRNA-seq]] · [[Embedding Analysis]] · [[Feature Engineering]]
- Adjacent: [[t-SNE]] · [[UMAP]] · [[Autoencoder]] · [[NMF]] · [[Random Projection]]
## 🤖 LLM 활용
**언제**: 매 embedding analysis, 매 anisotropy whitening, 매 visualizing high-dim attention/activations.
**언제 X**: 매 매우 nonlinear task — autoencoder/contrastive 사용. 매 preserving exact distances 필요 — RP 만 보장.
## ❌ 안티패턴
- **PCA without scaling**: 매 큰-단위 feature 가 dominate. 매 StandardScaler 필수.
- **t-SNE 결과 해석 으로 cluster 크기/거리 신뢰**: 매 t-SNE 매 local-only — 매 global geometry 왜곡.
- **PCA 사용 후 inverse_transform 으로 outlier 제거** — 매 그러면 다시 fit X 매 outlier 의 영향 그대로.
- **n_components 선택을 임의 값** (e.g., 항상 2): 매 cumulative variance + downstream metric 기반 선택.
- **Test set 도 fit_transform**: 매 leakage. 매 fit 은 train 만, test 는 transform.
## 🧪 검증 / 중복
- Verified (Bishop *PRML* Ch 12; *ESL* Hastie et al.; UMAP McInnes 2018; sklearn docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — PCA & DR FULL with PCA/UMAP/AE/whitening patterns |