[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,66 +2,192 @@
|
||||
id: wiki-2026-0508-spectral-clustering
|
||||
title: Spectral Clustering
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [MATH-CLUST-SPEC-001]
|
||||
aliases: [Graph Spectral Clustering, Laplacian Clustering, Normalized Cuts]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [math, machine-learning, clustering, spectral-clustering, Graph-Theory, Linear-Algebra, eigenvalues]
|
||||
confidence_score: 0.93
|
||||
verification_status: applied
|
||||
tags: [clustering, graph, unsupervised, laplacian, eigendecomposition]
|
||||
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/scipy/networkx
|
||||
---
|
||||
|
||||
# Spectral Clustering (스펙트럴 클러스터링)
|
||||
# Spectral Clustering
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "데이터를 연결의 선으로 엮어 그래프를 만들고, 행렬의 고유값(Spectrum) 속에 숨겨진 최적의 절단면(Min-cut)을 찾아 복잡하게 얽힌 무리들을 명쾌하게 갈라치기하라" — 데이터 간의 유사도 그래프를 구축하고 라플라시안 행렬의 고유값 분해를 통해 저차원 공간으로 투영하여 군집화하는 기법.
|
||||
## 매 한 줄
|
||||
> **"매 graph Laplacian 의 eigenvector 의 lower-dim embed → k-means"**. Spectral clustering 매 affinity-graph 매 cluster 의 detect, 매 non-convex / manifold 의 흐름 의 break (concentric circle, moons). 매 von Luxburg 2007 tutorial 의 canonical reference; 매 modern 매 Nyström approx + GPU eigen 의 large-scale.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** "Graph Laplacian and Dimensionality Reduction for Clustering" — 데이터 포인트 간의 유사도를 측정해 인접 행렬(Adjacency Matrix)을 만들고, 이를 차수 행렬(Degree Matrix)과 결합한 라플라시안(Laplacian) 행렬의 하위 고유 벡터들을 추출하여 군집 간의 연결은 최소화하고 내부 결속은 최대화하는 패턴.
|
||||
- **핵심 장점:**
|
||||
- **Non-convex Shapes:** K-Means가 실패하는 도넛 모양이나 소용돌이 모양의 데이터 군집도 완벽하게 분류 가능.
|
||||
- **Connectivity Focus:** 단순 거리가 아닌 '연결 관계'를 중심으로 군집 형성.
|
||||
- **주요 단계:**
|
||||
1. 데이터 간 유사도 행렬 계산.
|
||||
2. 라플라시안 행렬(L = D - A) 산출.
|
||||
3. 하위 k개의 고유 벡터 추출 및 저차원 투영.
|
||||
4. 투영된 공간에서 K-Means 등을 적용해 최종 군집 결정.
|
||||
- **의의:** 이미지 분할(Image Segmentation), 사회망의 커뮤니티 탐지 등 구조적 관계가 중요한 복잡한 데이터 분석의 강력한 도구.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 연산 복잡도가 높다는($O(n^3)$) 이유로 대규모 데이터에 기피되었으나, 최근에는 희소 행렬 최적화와 근사 고유값 분해 기술을 통해 수십만 건 이상의 데이터에도 적용 가능한 수준으로 고도화됨.
|
||||
- **정책 변화:** Antigravity 프로젝트는 대규모 지식 문서의 시맨틱 토픽 클러스터링 시, 단순 주제 분류를 넘어 문서 간의 인용 및 참조 관계를 심층 분석하기 위해 스펙트럴 클러스터링을 엔진으로 활용함.
|
||||
### 매 3-step recipe
|
||||
1. **Affinity matrix** $W$: $w_{ij} = \exp(-\|x_i - x_j\|^2 / 2\sigma^2)$ 또는 k-NN graph.
|
||||
2. **Laplacian**:
|
||||
- Unnormalized: $L = D - W$
|
||||
- Symmetric normalized (Ng-Jordan-Weiss): $L_{sym} = I - D^{-1/2} W D^{-1/2}$
|
||||
- Random-walk: $L_{rw} = I - D^{-1} W$
|
||||
3. **Eigendecompose** → take k smallest eigenvectors → row-normalize → k-means on rows.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- Cluster-[[Analysis|Analysis]]-Techniques, Graph-Theory-Foundations, [[Singular-Value-Decomposition|Singular-Value-Decomposition]], [[Social-Network-Analysis|Social-Network-Analysis]]
|
||||
- **Raw Source:** 10_Wiki/Topics/AI/Spectral-Clustering.md
|
||||
### 매 why eigenvectors?
|
||||
- 매 graph cut (RatioCut / NCut) 매 NP-hard.
|
||||
- 매 spectral relaxation 매 continuous: 매 2nd-smallest eigenvector (Fiedler) 의 sign 매 binary cut 의 approximate.
|
||||
- 매 k cluster 매 k smallest eigenvectors 의 use.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 variant
|
||||
- **Ng-Jordan-Weiss (2002)**: $L_{sym}$ + row-normalize.
|
||||
- **Shi-Malik (2000)**: Normalized Cuts, $L_{rw}$, image segmentation.
|
||||
- **Self-tuning** (Zelnik-Manor 2004): per-point sigma.
|
||||
- **Power Iteration Clustering** (Lin-Cohen 2010): 매 cheap approx.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### 매 응용
|
||||
1. Image segmentation (NCut on pixel graph).
|
||||
2. Community detection (small social nets).
|
||||
3. Manifold-aware clustering (Swiss-roll, moons).
|
||||
4. Speaker diarization (utterance affinity).
|
||||
5. Document clustering (TF-IDF cosine graph).
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
### scikit-learn
|
||||
```python
|
||||
from sklearn.cluster import SpectralClustering
|
||||
from sklearn.datasets import make_moons
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
X, _ = make_moons(n_samples=400, noise=0.05)
|
||||
sc = SpectralClustering(
|
||||
n_clusters=2,
|
||||
affinity="nearest_neighbors", # k-NN graph
|
||||
n_neighbors=10,
|
||||
assign_labels="kmeans",
|
||||
random_state=42,
|
||||
)
|
||||
labels = sc.fit_predict(X)
|
||||
```
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
### From scratch (numpy + scipy)
|
||||
```python
|
||||
import numpy as np
|
||||
from scipy.sparse import csgraph
|
||||
from scipy.sparse.linalg import eigsh
|
||||
from sklearn.cluster import KMeans
|
||||
from sklearn.neighbors import kneighbors_graph
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
def spectral_cluster(X, k, n_neighbors=10):
|
||||
# 1. k-NN affinity
|
||||
W = kneighbors_graph(X, n_neighbors=n_neighbors, mode='connectivity')
|
||||
W = 0.5 * (W + W.T) # symmetrize
|
||||
# 2. Symmetric normalized Laplacian
|
||||
L = csgraph.laplacian(W, normed=True)
|
||||
# 3. k smallest eigenvectors
|
||||
vals, vecs = eigsh(L, k=k, which='SM')
|
||||
# 4. Row-normalize
|
||||
norm = np.linalg.norm(vecs, axis=1, keepdims=True)
|
||||
vecs = vecs / np.clip(norm, 1e-10, None)
|
||||
# 5. k-means
|
||||
return KMeans(n_clusters=k, n_init=10).fit_predict(vecs)
|
||||
```
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
### RBF affinity
|
||||
```python
|
||||
from sklearn.metrics.pairwise import rbf_kernel
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
def rbf_affinity(X, sigma=1.0):
|
||||
gamma = 1.0 / (2.0 * sigma**2)
|
||||
return rbf_kernel(X, gamma=gamma)
|
||||
```
|
||||
|
||||
### Sigma auto-tuning (k-th NN distance)
|
||||
```python
|
||||
from sklearn.neighbors import NearestNeighbors
|
||||
|
||||
def auto_sigma(X, k=7):
|
||||
nn = NearestNeighbors(n_neighbors=k+1).fit(X)
|
||||
d, _ = nn.kneighbors(X)
|
||||
return np.median(d[:, k])
|
||||
```
|
||||
|
||||
### Eigengap heuristic (choose k)
|
||||
```python
|
||||
def eigengap_k(L, max_k=15):
|
||||
vals, _ = eigsh(L, k=max_k, which='SM')
|
||||
vals = np.sort(vals)
|
||||
gaps = np.diff(vals)
|
||||
return int(np.argmax(gaps)) + 1
|
||||
```
|
||||
|
||||
### Large-scale Nyström approximation
|
||||
```python
|
||||
from sklearn.kernel_approximation import Nystroem
|
||||
from sklearn.cluster import KMeans
|
||||
|
||||
# For N >> 10k
|
||||
nys = Nystroem(kernel='rbf', gamma=0.1, n_components=300, random_state=0)
|
||||
X_low = nys.fit_transform(X)
|
||||
labels = KMeans(n_clusters=k, n_init=10).fit_predict(X_low)
|
||||
```
|
||||
|
||||
### Image segmentation (NCut)
|
||||
```python
|
||||
from skimage import data, segmentation, color
|
||||
from skimage.future import graph
|
||||
|
||||
img = data.coffee()
|
||||
labels1 = segmentation.slic(img, compactness=30, n_segments=400)
|
||||
g = graph.rag_mean_color(img, labels1, mode='similarity')
|
||||
labels2 = graph.cut_normalized(labels1, g)
|
||||
out = color.label2rgb(labels2, img, kind='avg')
|
||||
```
|
||||
|
||||
### Diarization affinity (cosine)
|
||||
```python
|
||||
def speaker_affinity(embeddings):
|
||||
# (N, D) speaker embeddings, L2-normalized
|
||||
sim = embeddings @ embeddings.T
|
||||
sim = (sim + 1) / 2 # [0,1]
|
||||
return sim
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Convex blob clusters | k-means (faster) |
|
||||
| Non-convex / manifold | Spectral (k-NN affinity) |
|
||||
| N < 5k | Full eigendecomp |
|
||||
| 5k < N < 50k | k-NN sparse + eigsh |
|
||||
| N > 50k | Nyström / mini-batch |
|
||||
| Image seg | NCut + SLIC superpixels |
|
||||
| Speaker diar | Cosine affinity + spectral |
|
||||
|
||||
**기본값**: sklearn `SpectralClustering(affinity='nearest_neighbors', n_neighbors=10)`.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Clustering]] · [[Unsupervised-Learning]]
|
||||
- 변형: [[K-Means]] · [[DBSCAN]] · [[HDBSCAN]]
|
||||
- 응용: [[Image-Segmentation]] · [[Diarization]] · [[Community-Detection]]
|
||||
- Adjacent: [[Graph-Laplacian]] · [[Manifold-Learning]] · [[Eigenvalue-Decomposition]] · [[Normalized-Cuts]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 affinity choice rationale, 매 eigengap interpretation, 매 sklearn pipeline scaffolding.
|
||||
**언제 X**: 매 numerical eigendecomp (use scipy/PyTorch), 매 cluster validation 매 ground-truth needed.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Dense N×N for N>10k**: 매 OOM. 매 k-NN sparse 의 use.
|
||||
- **Sigma 의 untuned**: 매 RBF kernel 매 useless. 매 median distance heuristic.
|
||||
- **k 매 hand-pick**: 매 eigengap heuristic 의 first try.
|
||||
- **No symmetrization**: 매 k-NN graph 의 directed → 매 complex eigenvalues.
|
||||
- **Wrong Laplacian for unbalanced**: 매 unnormalized 매 cluster size 의 sensitive. 매 $L_{sym}$ default.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (von Luxburg "A Tutorial on Spectral Clustering" 2007; Ng-Jordan-Weiss NIPS 2002; sklearn docs 1.5).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — full content (Laplacian variants + sklearn/scipy + Nyström patterns) |
|
||||
|
||||
Reference in New Issue
Block a user