[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,88 +2,292 @@
id: wiki-2026-0508-dimensionality-reduction
title: Dimensionality Reduction
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [DIM-REDUC-001]
aliases: [PCA, t-SNE, UMAP, autoencoder, curse of dimensionality, feature extraction]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [ai, machine-learning, Statistics, dimensionality-reduction, pca, tsne]
confidence_score: 0.93
verification_status: applied
tags: [dimensionality-reduction, pca, tsne, umap, autoencoder, visualization, manifold-learning]
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-learn / PyTorch
---
# Dimensionality Reduction (차원 축소)
# Dimensionality Reduction
## 📌 한 줄 통찰 (The Karpathy Summary)
> "데이터의 덩치는 줄이되, 그 안에 담긴 핵심 메시지는 보존하라" — 수많은 변수(Feature)를 가진 고차원 데이터를 본질적인 특징을 잃지 않으면서 낮은 차원으로 변환하여, 연산 효율을 높이고 데이터 시각화를 가능하게 하는 기법.
## 한 줄
> **"매 high-dim 의 essence 의 low-dim"**. 매 PCA (linear) → 매 t-SNE / UMAP (nonlinear, 시각화) → 매 Autoencoder / VAE (deep). 매 modern: 매 embedding (CLIP, sentence-transformers) 의 implicit dim reduction.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 중복되거나 노이즈에 가까운 차원을 제거하고 데이터의 분산(Variance)이나 구조적 유사성을 가장 잘 설명하는 새로운 축을 찾아 정보를 압축하는 패턴.
- **주요 기법:**
- **PCA (Principal Component [[Analysis|Analysis]]):** 데이터의 분산이 최대인 방향으로 선형 결합하여 차원 축소 (선형 방식).
- **t-SNE / UMAP:** 고차원에서 가까운 데이터는 저차원에서도 가깝게 유지 (비선형 방식, 시각화에 탁월).
- **Autoencoders:** 신경망의 병목 구조를 통해 데이터를 압축 및 복원하며 핵심 특징 추출.
- **장점:** 차원의 저주(Curse of Dimensionality) 해결, 오버피팅 방지, 연산 속도 향상, 2D/3D 시각화를 통한 인사이트 도출.
## 매 핵심 method
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 단순히 데이터를 삭제(Feature Selection)하던 방식에서, 전체 데이터의 상관관계를 고려하여 새로운 정보를 창출(Feature Extraction)하는 방식으로 진화.
- **정책 변화:** Antigravity 프로젝트는 수천 개의 위키 문서 임베딩 벡터를 클러스터링하고 지식 지도로 시각화할 때 UMAP이나 t-SNE 기법을 사용하여 지식 간의 거리를 직관적으로 노출함.
### Linear
## 🔗 지식 연결 (Graph)
- [[Principal-Component-Analysis|Principal-Component-Analysis]]-PCA, Un[[Supervised-Learning-Foundations|Supervised-Learning-Foundations]], Autoencoder, [[Representation-Learning|Representation-Learning]]
- **Raw Source:** 10_Wiki/Topics/AI/Dimensionality-Reduction.md
#### PCA (Principal Component Analysis)
- 매 variance 의 maximum direction.
- 매 orthogonal axis.
- 매 SVD.
- 매 fast + interpretable.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
#### LDA (Linear Discriminant Analysis)
- 매 class separation 의 maximize.
- 매 supervised.
**언제 이 지식을 쓰는가:**
- *(TODO)*
#### Factor Analysis
- 매 latent factor 의 explain variance.
**언제 쓰면 안 되는가:**
- *(TODO)*
### Nonlinear (manifold)
## 🧪 검증 상태 (Validation)
#### t-SNE (Maaten 2008)
- 매 local neighborhood 의 preserve.
- 매 visualization 강.
- 매 global structure 의 weak.
- 매 stochastic.
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
#### UMAP (McInnes 2018)
- 매 t-SNE 의 successor.
- 매 faster + 매 global structure 도 better.
- 매 default for high-dim viz.
## 🧬 중복 검사 (Duplicate Check)
#### Isomap
- 매 geodesic distance 의 preserve.
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
#### LLE (Locally Linear Embedding).
## 🕓 변경 이력 (Changelog)
### Neural
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
#### Autoencoder
- 매 bottleneck 의 dim reduce.
## 💻 코드 패턴 (Code Patterns)
#### VAE (Variational AE)
- 매 probabilistic.
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
#### Self-Supervised Embedding
- 매 CLIP, BERT, sentence-transformers.
- 매 implicit dim reduction.
```text
# TODO
### 매 PaCMAP / TriMap (recent)
- 매 UMAP 의 variant.
- 매 better global structure.
### 매 응용
1. **Visualization** (2D / 3D): 매 t-SNE, UMAP.
2. **Speed** (preprocess): 매 PCA.
3. **Anomaly detection**: 매 autoencoder.
4. **Feature extraction**: 매 embedding.
5. **Compression**: 매 quantization + 매 embed.
6. **Clustering preprocessing**.
7. **RAG** (vector DB): 매 PCA / quantization.
### 매 curse of dimensionality
- 매 distance 의 meaningless.
- 매 sparsity in 매 high-dim.
- 매 sample requirement 의 exponential.
## 💻 패턴
### PCA (sklearn)
```python
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
X_scaled = StandardScaler().fit_transform(X)
pca = PCA(n_components=0.95) # 매 95% variance 의 keep
X_reduced = pca.fit_transform(X_scaled)
print(f'Original: {X.shape[1]}, reduced: {pca.n_components_}')
print(f'Explained variance: {pca.explained_variance_ratio_.cumsum()}')
```
## 🤔 의사결정 기준 (Decision Criteria)
### t-SNE
```python
from sklearn.manifold import TSNE
**선택 A를 써야 할 때:**
- *(TODO)*
tsne = TSNE(
n_components=2,
perplexity=30,
n_iter=1000,
random_state=42,
)
X_2d = tsne.fit_transform(X[:5000]) # 매 t-SNE 의 slow → 매 sample
```
**선택 B를 써야 할 때:**
- *(TODO)*
### UMAP (modern)
```python
import umap
**기본값:**
> *(TODO)*
reducer = umap.UMAP(
n_components=2,
n_neighbors=15,
min_dist=0.1,
metric='cosine', # 매 embedding 에 좋음
random_state=42,
)
X_2d = reducer.fit_transform(X)
```
## ❌ 안티패턴 (Anti-Patterns)
### Autoencoder (PyTorch)
```python
import torch.nn as nn
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
class AE(nn.Module):
def __init__(self, input_dim, latent_dim=32):
super().__init__()
self.encoder = nn.Sequential(
nn.Linear(input_dim, 128), nn.ReLU(),
nn.Linear(128, 64), nn.ReLU(),
nn.Linear(64, latent_dim),
)
self.decoder = nn.Sequential(
nn.Linear(latent_dim, 64), nn.ReLU(),
nn.Linear(64, 128), nn.ReLU(),
nn.Linear(128, input_dim),
)
def forward(self, x):
z = self.encoder(x)
return self.decoder(z), z
# 매 latent 의 use
model = AE(input_dim=784)
# ... train ...
_, latent = model(X_test)
```
### Visualization combo (UMAP + scatter)
```python
import matplotlib.pyplot as plt
X_2d = umap.UMAP().fit_transform(X)
plt.figure(figsize=(10, 8))
plt.scatter(X_2d[:, 0], X_2d[:, 1], c=labels, cmap='tab10', alpha=0.5, s=10)
plt.colorbar()
plt.title('UMAP projection')
plt.show()
```
### PCA for speed (vector DB preprocessing)
```python
from sklearn.decomposition import PCA
import faiss
# 매 매 768 의 OpenAI embedding → 매 256
embeddings = get_embeddings(documents)
pca = PCA(n_components=256)
reduced = pca.fit_transform(embeddings).astype('float32')
# 매 Faiss
index = faiss.IndexFlatIP(256)
index.add(reduced)
```
### Quantization (vector DB modern)
```python
import faiss
dim = 768
quantizer = faiss.IndexFlatIP(dim)
index = faiss.IndexIVFPQ(quantizer, dim, nlist=100, m=8, nbits=8)
# 매 8 byte 의 768-dim 의 represent — 매 매 100× compression.
index.train(embeddings_np)
index.add(embeddings_np)
```
### Word2Vec / CLIP-style (implicit reduction)
```python
from sentence_transformers import SentenceTransformer
model = SentenceTransformer('all-MiniLM-L6-v2') # 매 384-dim
embeddings = model.encode(sentences)
# 매 매 sentence (potentially infinite words) → 매 384-dim.
```
### Reconstruction error (anomaly)
```python
def detect_anomaly(model, X, threshold):
X_recon, _ = model(X)
error = ((X_recon - X) ** 2).mean(dim=1)
return error > threshold
```
### Choose dimension (elbow / cumvar)
```python
import numpy as np
import matplotlib.pyplot as plt
pca = PCA().fit(X_scaled)
cumvar = np.cumsum(pca.explained_variance_ratio_)
plt.plot(cumvar)
plt.xlabel('Component')
plt.ylabel('Cumulative variance')
plt.axhline(0.95, color='r', linestyle='--')
plt.show()
n_components = np.argmax(cumvar >= 0.95) + 1
```
### Manifold visualization comparison
```python
def viz_compare(X, labels):
fig, axes = plt.subplots(1, 3, figsize=(20, 6))
for ax, (name, reducer) in zip(axes, [
('PCA', PCA(n_components=2)),
('t-SNE', TSNE(n_components=2, random_state=42)),
('UMAP', umap.UMAP(n_components=2, random_state=42)),
]):
proj = reducer.fit_transform(X)
ax.scatter(proj[:, 0], proj[:, 1], c=labels, cmap='tab10', s=5)
ax.set_title(name)
```
## 매 결정 기준
| 상황 | Method |
|---|---|
| Speed (preprocess) | PCA |
| Visualization | UMAP |
| Cluster preserve | UMAP |
| Variance interpret | PCA |
| Class-aware | LDA |
| Text → embedding | Sentence-transformer |
| Image → embedding | CLIP |
| Vector DB compress | PCA / PQ quantization |
| Anomaly | Autoencoder |
| Generative | VAE |
**기본값**: PCA (preprocess) + UMAP (viz) + embedding (semantic).
## 🔗 Graph
- 부모: [[Unsupervised-Learning]] · [[Feature-Engineering]]
- 변형: [[PCA]] · [[t-SNE]] · [[UMAP]] · [[Autoencoder]] · [[VAE]] · [[Isomap]] · [[LLE]]
- 응용: [[CLIP]] · [[Sentence-Transformers]] · [[Faiss]] · [[Anomaly-Detection]]
- Adjacent: [[Auto-Encoding]] · [[Bag of Words (BoW)]] · [[Bias-vs-Variance]]
## 🤖 LLM 활용
**언제**: 매 visualization. 매 vector DB. 매 cluster preprocessing. 매 anomaly detection.
**언제 X**: 매 already low-dim. 매 lossless 필수.
## ❌ 안티패턴
- **PCA without standardize**: 매 wrong principal component.
- **t-SNE 의 cluster size 의 interpret**: 매 not preserved.
- **UMAP 의 distance 의 absolute interpret**: 매 local 만.
- **Too aggressive reduction**: 매 information loss.
- **Forget train-test split**: 매 leakage in PCA.
## 🧪 검증 / 중복
- Verified (Jolliffe PCA, van der Maaten t-SNE, McInnes UMAP).
- 신뢰도 A.
- Related: [[Auto-Encoding]] · [[Bag of Words (BoW)]] · [[CLIP]] · [[Sentence-Transformers]] · [[Bias-vs-Variance]].
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — methods + 매 PCA / t-SNE / UMAP / AE / Faiss / quantization code |