[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,70 +2,190 @@
|
||||
id: wiki-2026-0508-similarity-metrics
|
||||
title: Similarity Metrics
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-SIME-001]
|
||||
aliases: [Distance Metrics, Similarity Functions]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.96
|
||||
tags: [auto-reinforced, mathematics, similarity-metrics, Statistics, vector-space]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [machine-learning, retrieval, embeddings, distance]
|
||||
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: Python
|
||||
framework: NumPy/FAISS
|
||||
---
|
||||
|
||||
# [[Similarity-Metrics|Similarity-Metrics]]
|
||||
# Similarity Metrics
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "데이터 사이의 거리 측정법: 서로 다른 두 정보가 얼마나 닮았는지를 수학적으로 정의하여, 추천 시스템과 검색 엔진이 '비슷한 것'을 찾아낼 수 있게 하는 지능의 척도."
|
||||
## 매 한 줄
|
||||
> **"매 두 vector 의 close 의 measure"**. Classical IR (Salton, 1970s) → modern embedding-based retrieval (RAG with Claude Opus 4.7, 2026) — 매 cosine 의 default, 매 task-specific tuning 의 critical.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
유사도 측정 지표(Similarity Metrics)는 벡터 공간에 표현된 데이터 객체 간의 거리나 상관관계를 정량화하는 수학적 방법론입니다.
|
||||
## 매 핵심
|
||||
|
||||
1. **핵심 지표 (Core Metrics)**:
|
||||
* **Cosine Similarity**: 두 벡터 사이의 각도를 측정. 텍스트 데이터처럼 크기(Magnitude)보다 방향성이 중요할 때 주로 사용.
|
||||
* **Euclidean Distance**: 공간상의 직선거리. 데이터의 절대적인 값이 중요할 때 사용.
|
||||
* **Manhattan Distance**: 격자 모양의 경로 거리 (L1 Norm).
|
||||
* **Jaccard Similarity**: 집합 간의 교집합 비중을 측정. 범주형 데이터 비교에 적합.
|
||||
2. **활용 분야**:
|
||||
* **RAG (검색 증강 생성)**: 질문과 가장 유사한 지식 조각을 벡터 DB에서 찾는 핵심 알고리즘.
|
||||
* **Recommender[[_system|system]]s**: 내가 본 영화와 가장 '유사한' 취향의 영화 추천.
|
||||
* **Anomaly Detection**: 다른 데이터들과의 거리가 너무 먼 '이상치' 식별.
|
||||
3. **선택 기준**:
|
||||
* 데이터의 차원수, 정규화 여부, 비즈니스 목적에 따라 적절한 지표 선택이 시스템 성능을 좌우함.
|
||||
### 매 주요 metrics
|
||||
- **Cosine**: `cos(a,b) = (a·b)/(||a|| ||b||)` ∈ [-1, 1]. Direction only, scale-invariant.
|
||||
- **Dot product**: `a·b`. Scale-sensitive — large norm dominates.
|
||||
- **Euclidean (L2)**: `||a-b||₂`. Geometric distance, sensitive to magnitude.
|
||||
- **Manhattan (L1)**: `Σ|aᵢ-bᵢ|`. Robust to outliers.
|
||||
- **Jaccard**: `|A∩B|/|A∪B|`. Set similarity.
|
||||
- **Hamming**: count of differing positions. Binary vectors.
|
||||
- **Edit (Levenshtein)**: min insertions/deletions/substitutions. Strings.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌**: 과거에는 단순한 거리 측정만으로 충분했으나, 고차원 데이터가 폭증하며 '차원의 저주' 문제가 발생. 이에 따라 단순히 가깝다고 비슷한 것이 아니라 의미적으로 유사한지를 파악하는 '임베딩 기반 유사도'로 정책이 이동함(RL Update).
|
||||
- **정책 변화(RL Update)**: 개인화 추천 정책 수립 시, 단순히 과거 유사도만 따지는 것이 아니라 유저의 '의도 변화'를 실시간 반영하는 가변적 유사도 가중치 정책이 표준화됨.
|
||||
### 매 핵심 관계
|
||||
- Normalized vectors (||v||=1): cosine = dot product = `1 - L2²/2`.
|
||||
- 매 modern embedding model (OpenAI text-embedding-3, voyage-3, BGE-M3) 의 normalized output → cosine ≡ dot.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- Vector Semantics, [[RAG (검색 증강 생성)|RAG (검색 증강 생성)]], [[Statistics & Data Analysis|Statistics & Data Analysis]], Information Extraction (IE), [[Principles-of-Data-Connect|Principles-of-Data-Connect]]
|
||||
- **Modern Tech/Tools**: Faiss (Facebook AI Similarity [[Search|Search]]), Scipy Spatial, Pinecone.
|
||||
---
|
||||
### 매 응용
|
||||
1. RAG retrieval (text embeddings + cosine).
|
||||
2. Image search (CLIP embeddings).
|
||||
3. Recommender systems (item-item).
|
||||
4. Deduplication (near-duplicate detection).
|
||||
5. Clustering (k-means uses Euclidean).
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
## 💻 패턴
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### Cosine similarity
|
||||
```python
|
||||
import numpy as np
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
def cosine(a, b):
|
||||
return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
# Batch
|
||||
def cosine_matrix(A, B):
|
||||
A_norm = A / np.linalg.norm(A, axis=1, keepdims=True)
|
||||
B_norm = B / np.linalg.norm(B, axis=1, keepdims=True)
|
||||
return A_norm @ B_norm.T
|
||||
```
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
### Sklearn pairwise
|
||||
```python
|
||||
from sklearn.metrics.pairwise import cosine_similarity, euclidean_distances
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
sim = cosine_similarity(X, Y) # (n_X, n_Y)
|
||||
dist = euclidean_distances(X, Y)
|
||||
```
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
### FAISS (large-scale)
|
||||
```python
|
||||
import faiss
|
||||
import numpy as np
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
embeddings = np.random.randn(1_000_000, 768).astype('float32')
|
||||
faiss.normalize_L2(embeddings) # for cosine via inner product
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
index = faiss.IndexFlatIP(768) # inner product = cosine on normalized
|
||||
index.add(embeddings)
|
||||
|
||||
query = np.random.randn(1, 768).astype('float32')
|
||||
faiss.normalize_L2(query)
|
||||
D, I = index.search(query, k=10) # top-10
|
||||
```
|
||||
|
||||
### RAG with embeddings (2026)
|
||||
```python
|
||||
from anthropic import Anthropic
|
||||
import voyageai
|
||||
|
||||
vo = voyageai.Client()
|
||||
client = Anthropic()
|
||||
|
||||
def embed(texts):
|
||||
r = vo.embed(texts, model="voyage-3", input_type="document")
|
||||
return np.array(r.embeddings)
|
||||
|
||||
docs_emb = embed(corpus)
|
||||
q_emb = vo.embed([query], model="voyage-3", input_type="query").embeddings[0]
|
||||
|
||||
scores = docs_emb @ np.array(q_emb) # cosine on normalized
|
||||
top_k = np.argsort(scores)[-5:][::-1]
|
||||
```
|
||||
|
||||
### Jaccard for sets
|
||||
```python
|
||||
def jaccard(a: set, b: set) -> float:
|
||||
if not a and not b:
|
||||
return 1.0
|
||||
return len(a & b) / len(a | b)
|
||||
|
||||
# MinHash for approximate Jaccard at scale
|
||||
from datasketch import MinHash
|
||||
m1, m2 = MinHash(), MinHash()
|
||||
for w in doc1.split(): m1.update(w.encode())
|
||||
for w in doc2.split(): m2.update(w.encode())
|
||||
print(m1.jaccard(m2))
|
||||
```
|
||||
|
||||
### Edit distance
|
||||
```python
|
||||
def levenshtein(a, b):
|
||||
if len(a) < len(b): a, b = b, a
|
||||
prev = list(range(len(b) + 1))
|
||||
for i, ca in enumerate(a, 1):
|
||||
curr = [i]
|
||||
for j, cb in enumerate(b, 1):
|
||||
curr.append(min(
|
||||
curr[-1] + 1,
|
||||
prev[j] + 1,
|
||||
prev[j-1] + (ca != cb)
|
||||
))
|
||||
prev = curr
|
||||
return prev[-1]
|
||||
```
|
||||
|
||||
### Hybrid search (BM25 + dense)
|
||||
```python
|
||||
# Reciprocal Rank Fusion
|
||||
def rrf(rankings, k=60):
|
||||
scores = {}
|
||||
for ranking in rankings:
|
||||
for rank, doc_id in enumerate(ranking):
|
||||
scores[doc_id] = scores.get(doc_id, 0) + 1 / (k + rank)
|
||||
return sorted(scores.items(), key=lambda x: -x[1])
|
||||
|
||||
bm25_top = bm25_search(query)
|
||||
dense_top = vector_search(query)
|
||||
fused = rrf([bm25_top, dense_top])
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Metric |
|
||||
|---|---|
|
||||
| Text embeddings (LLM, BERT) | Cosine |
|
||||
| Image embeddings (CLIP) | Cosine |
|
||||
| Tabular numeric features | Euclidean (after StandardScaler) |
|
||||
| Sparse binary features | Jaccard |
|
||||
| Strings / typo-tolerant | Levenshtein |
|
||||
| Hashes / fingerprints | Hamming |
|
||||
| L1-sparse (Lasso embeddings) | Manhattan |
|
||||
|
||||
**기본값**: normalized embeddings + cosine (= dot product on unit vectors).
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Information-Retrieval]] · [[Embeddings]]
|
||||
- 변형: [[Cosine-Similarity]] · [[Euclidean-Distance]] · [[Jaccard-Similarity]] · [[Edit-Distance]]
|
||||
- 응용: [[RAG]] · [[Vector-Database]] · [[Recommender-Systems]] · [[Clustering]]
|
||||
- Adjacent: [[FAISS]] · [[BM25]] · [[Locality-Sensitive-Hashing]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: RAG retrieval ranking. Semantic search. Deduplication. Clustering. Nearest-neighbor classification. Recommender similarity.
|
||||
**언제 X**: Hierarchical / structured similarity (use tree edit distance, graph kernels). Causal similarity (use DTW for time-series).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Cosine on un-normalized**: 매 normalization 의 forget 시 — `normalize_L2` 의 explicit call.
|
||||
- **Euclidean without scaling**: feature 의 다른 scale 의 → larger-scale feature 가 dominate.
|
||||
- **Jaccard on dense vectors**: 매 set similarity — dense float vec 에 X.
|
||||
- **Magnitude-blind cosine for ranking**: cosine 의 direction only — popularity / confidence 의 X capture.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Salton & McGill IR text, MTEB benchmark 2025, FAISS docs).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Similarity metrics with cosine/L2/Jaccard/edit, FAISS, RAG, hybrid |
|
||||
|
||||
Reference in New Issue
Block a user