[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,89 +1,230 @@
|
||||
---
|
||||
id: wiki-2026-0508-k-nearest-neighbors-k-nn
|
||||
title: K Nearest Neighbors K NN
|
||||
title: K-Nearest Neighbors (k-NN)
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [ML-KNN-001]
|
||||
aliases: [k-NN, kNN, nearest neighbor, lazy learning, FAISS, instance-based]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [machine-learning, knn, Instance-based-Learning, Similarity-Metrics, classification]
|
||||
confidence_score: 0.96
|
||||
verification_status: applied
|
||||
tags: [machine-learning, knn, classification, regression, faiss, retrieval]
|
||||
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 / FAISS / Annoy
|
||||
---
|
||||
|
||||
# K-Nearest Neighbors (K-NN, K-최근접 이웃)
|
||||
# K-Nearest Neighbors (k-NN)
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "데이터의 정체는 그 주변에 누가 있느냐에 따라 결정된다" — 새로운 데이터의 레이블을 예측할 때, 특징 공간 상에서 가장 가까운 K개의 훈련 데이터(이웃)를 찾아 그들의 다수결(분류)이나 평균(회귀)으로 값을 결정하는 직관적인 알고리즘.
|
||||
## 매 한 줄
|
||||
> **"매 query 의 의 의 K closest training point 의 의 의 의 vote/avg"**. 매 lazy learning (no training). 매 simple but effective baseline. 매 modern: 매 vector DB의 backbone (FAISS, Pinecone). 매 RAG retrieval 도 결국 k-NN.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** "Proximity-based [[Reasoning|Reasoning]]" — 별도의 학습 과정 없이 데이터 사이의 거리를 계산하여 즉각적으로 결론을 내리는 사례 기반 학습(Instance-based Learning) 패턴.
|
||||
- **핵심 요소:**
|
||||
- **Distance Metrics:** 유클리디안(Euclidean), 맨해튼(Manhattan), 코사인(Cosine) 거리 등 데이터의 특성에 맞는 척도 선택이 중요.
|
||||
- **K value:** 이웃의 수. K가 너무 작으면 노이즈에 민감([[Overfitting|Overfitting]]), 너무 크면 경계가 모호(Underfitting)해짐.
|
||||
- **Feature Scaling:** 모든 특징이 거리 계산에 공평하게 반영되도록 정규화([[Normalization|Normalization]]) 필수.
|
||||
- **의의:** 알고리즘이 매우 단순하여 구현이 쉽고, 데이터의 분포가 비선형적이거나 복잡할 때도 훌륭한 기준(Baseline) 성능을 제공함.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 차원의 저주(Curse of Dimensionality)로 인해 고차원 데이터에서 성능이 급감한다는 한계가 있으나, 최근에는 PCA 등을 통한 차원 축소나 고성능 근사 근접 이웃(ANN) 검색 기술과 결합하여 한계를 극복함.
|
||||
- **정책 변화:** Antigravity 프로젝트는 유사한 문맥을 가진 지식을 검색할 때, 의미 벡터 공간에서의 K-NN 탐색을 통해 가장 관련성이 높은 문서 후보군을 즉시 도출함.
|
||||
### 매 task
|
||||
- **Classification**: 매 majority vote.
|
||||
- **Regression**: 매 average.
|
||||
- **Density estimation**.
|
||||
- **Anomaly detection**.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Instance-based-Learning|Instance-based-Learning]], Distance-Metrics-in-AI, [[Dimensionality-Reduction|Dimensionality-Reduction]], [[Indexing-Strategies|Indexing-Strategies]]
|
||||
- **Raw Source:** 10_Wiki/Topics/AI/K-Nearest-Neighbors-K-NN.md
|
||||
### 매 distance
|
||||
- **Euclidean** (L2).
|
||||
- **Cosine** (text/embed).
|
||||
- **Manhattan** (L1).
|
||||
- **Hamming** (binary).
|
||||
- **Custom** (Mahalanobis).
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 efficiency
|
||||
- **Brute force**: O(N).
|
||||
- **KD-tree** (low-dim).
|
||||
- **Ball tree**.
|
||||
- **HNSW** (FAISS, modern).
|
||||
- **IVF** (inverted file).
|
||||
- **PQ** (product quantization).
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### 매 응용
|
||||
1. **Image retrieval**.
|
||||
2. **Recommendation**.
|
||||
3. **RAG retrieval**.
|
||||
4. **Anomaly detection**.
|
||||
5. **Baseline classifier**.
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
## 🧪 검증 상태 (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
|
||||
### Basic (sklearn)
|
||||
```python
|
||||
from sklearn.neighbors import KNeighborsClassifier
|
||||
knn = KNeighborsClassifier(n_neighbors=5, weights='distance', metric='euclidean')
|
||||
knn.fit(X_train, y_train)
|
||||
preds = knn.predict(X_test)
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Cosine (for embeddings)
|
||||
```python
|
||||
knn = KNeighborsClassifier(n_neighbors=5, metric='cosine')
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### KD-tree (for low-dim)
|
||||
```python
|
||||
from sklearn.neighbors import KDTree
|
||||
tree = KDTree(X)
|
||||
distances, indices = tree.query(X_query, k=5)
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### FAISS (large-scale)
|
||||
```python
|
||||
import faiss
|
||||
import numpy as np
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
d = 768
|
||||
index = faiss.IndexFlatIP(d) # 매 inner product
|
||||
faiss.normalize_L2(X)
|
||||
index.add(X)
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
faiss.normalize_L2(query)
|
||||
D, I = index.search(query, k=10)
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### FAISS HNSW (approximate, fast)
|
||||
```python
|
||||
index = faiss.IndexHNSWFlat(d, M=32)
|
||||
index.hnsw.efConstruction = 200
|
||||
index.add(X)
|
||||
index.hnsw.efSearch = 50
|
||||
D, I = index.search(query, k=10)
|
||||
```
|
||||
|
||||
### FAISS IVF + PQ (massive scale)
|
||||
```python
|
||||
nlist = 100
|
||||
quantizer = faiss.IndexFlatL2(d)
|
||||
index = faiss.IndexIVFPQ(quantizer, d, nlist, 8, 8) # 매 8 sub-quantizers, 8 bits each
|
||||
index.train(X)
|
||||
index.add(X)
|
||||
index.nprobe = 10 # 매 search trade-off
|
||||
D, I = index.search(query, k=10)
|
||||
```
|
||||
|
||||
### Annoy (alternative)
|
||||
```python
|
||||
from annoy import AnnoyIndex
|
||||
index = AnnoyIndex(d, 'angular') # 매 cosine
|
||||
for i, v in enumerate(vectors):
|
||||
index.add_item(i, v)
|
||||
index.build(n_trees=10)
|
||||
neighbors = index.get_nns_by_vector(query, 10)
|
||||
```
|
||||
|
||||
### Custom distance
|
||||
```python
|
||||
from sklearn.neighbors import KNeighborsClassifier
|
||||
|
||||
def custom_dist(a, b):
|
||||
return np.sum(np.abs(a - b)) # 매 Manhattan
|
||||
|
||||
knn = KNeighborsClassifier(n_neighbors=5, metric=custom_dist)
|
||||
```
|
||||
|
||||
### Weighted by distance
|
||||
```python
|
||||
knn = KNeighborsClassifier(n_neighbors=5, weights='distance')
|
||||
# 매 매 closer = 매 higher weight in vote
|
||||
```
|
||||
|
||||
### k-NN regression
|
||||
```python
|
||||
from sklearn.neighbors import KNeighborsRegressor
|
||||
knr = KNeighborsRegressor(n_neighbors=5).fit(X, y)
|
||||
```
|
||||
|
||||
### Anomaly detection (LOF)
|
||||
```python
|
||||
from sklearn.neighbors import LocalOutlierFactor
|
||||
lof = LocalOutlierFactor(n_neighbors=20)
|
||||
anomalies = lof.fit_predict(X) == -1
|
||||
```
|
||||
|
||||
### k-NN with normalization (always!)
|
||||
```python
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
from sklearn.pipeline import Pipeline
|
||||
pipe = Pipeline([('scaler', StandardScaler()), ('knn', KNeighborsClassifier(5))])
|
||||
pipe.fit(X, y)
|
||||
```
|
||||
|
||||
### Choose K (CV)
|
||||
```python
|
||||
from sklearn.model_selection import GridSearchCV
|
||||
grid = GridSearchCV(KNeighborsClassifier(), {'n_neighbors': [3, 5, 7, 11, 15]}, cv=5)
|
||||
grid.fit(X, y)
|
||||
print(grid.best_params_)
|
||||
```
|
||||
|
||||
### RAG retrieval (k-NN over embeddings)
|
||||
```python
|
||||
from sentence_transformers import SentenceTransformer
|
||||
m = SentenceTransformer('all-mpnet-base-v2')
|
||||
doc_embs = m.encode(documents)
|
||||
|
||||
import faiss
|
||||
index = faiss.IndexFlatIP(doc_embs.shape[1])
|
||||
faiss.normalize_L2(doc_embs)
|
||||
index.add(doc_embs)
|
||||
|
||||
def retrieve(query, k=5):
|
||||
q_emb = m.encode([query])
|
||||
faiss.normalize_L2(q_emb)
|
||||
_, I = index.search(q_emb, k)
|
||||
return [documents[i] for i in I[0]]
|
||||
```
|
||||
|
||||
### kNN-LM (LLM augmentation)
|
||||
```python
|
||||
def knn_lm_predict(context, llm, datastore, k=10):
|
||||
"""매 LLM logit + retrieve nearest neighbor logit (Khandelwal 2020)."""
|
||||
llm_logits = llm.next_token_logits(context)
|
||||
nn_logits = datastore.knn_logits(context_emb=context.encode(), k=k)
|
||||
return llm_logits + 0.25 * nn_logits # 매 simple interpolation
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Small data | sklearn brute / KD-tree |
|
||||
| High-dim | FAISS HNSW |
|
||||
| Massive scale | FAISS IVF+PQ |
|
||||
| Production search | Pinecone / Weaviate |
|
||||
| Anomaly | LOF |
|
||||
| RAG | FAISS / vector DB |
|
||||
|
||||
**기본값**: 매 normalize 의 always + 매 cosine for embed + 매 FAISS HNSW for prod + 매 CV-tuned K + 매 weighted-by-distance.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Machine-Learning]] · [[Information-Retrieval]]
|
||||
- 변형: [[Brute-Force-NN]] · [[Approximate-NN]] · [[HNSW]]
|
||||
- 응용: [[FAISS]] · [[Vector-Database]] · [[RAG]]
|
||||
- Adjacent: [[Distance-Metric]] · [[Embeddings]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 baseline. 매 retrieval. 매 RAG.
|
||||
**언제 X**: 매 high-dim raw (use embed first).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **No normalize**: 매 magnitude dominate.
|
||||
- **Brute force at scale**: 매 latency.
|
||||
- **Wrong K**: 매 underfit/overfit.
|
||||
- **No metric thought**: 매 cosine vs L2 의 wrong.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Cover & Hart 1967, FAISS docs, Khandelwal kNN-LM 2020).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — k-NN + 매 sklearn / FAISS / HNSW / IVF / RAG / kNN-LM code |
|
||||
|
||||
Reference in New Issue
Block a user