[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
+101 -38
View File
@@ -2,61 +2,124 @@
id: wiki-2026-0508-matrix-factorization
title: Matrix Factorization
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [MATH-MF-001]
aliases: [MF, Matrix Decomposition, Latent Factor Models, Collaborative Filtering MF]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [math, machine-learning, recommender-systems, matrix-factorization, svd, Collaborative-Filtering]
confidence_score: 0.93
verification_status: applied
tags: [ml, recommender, svd, nmf, als, collaborative-filtering, dimensionality-reduction]
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: scipy|surprise|implicit|sklearn }
---
# Matrix Factorization (행렬 분해)
# Matrix Factorization
## 📌 한 줄 통찰 (The Karpathy Summary)
> "거대하고 성긴(Sparse) 데이터 행렬을 두 개의 작고 밀도 있는 잠재 요인(Latent Factors)으로 쪼개어, 보이지 않는 취향과 특징을 복원하라" — 하나의 커다란 행렬을 두 개 이상의 작은 행렬의 곱으로 분해하여 데이터의 잠재적인 구조를 파악하고 누락된 값을 예측하는 기술.
> 한 줄: 큰 행렬 R ≈ U·Vᵀ로 분해해 잠재 요인(latent factor)을 학습 — 추천 시스템·차원 축소·이미지 압축의 핵심.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Latent Space Mapping" — 사용자-아이템 행렬과 같이 데이터가 비어 있는 거대 행렬을 사용자의 성향 행렬과 아이템의 속성 행렬로 분해하여, 둘 사이의 내적을 통해 선호도를 예측하는 패턴.
- **주요 기법:**
- **SVD (Singular Value Decomposition):** 행렬을 세 개의 특수한 행렬로 분해하여 데이터의 차원을 축소하고 노이즈 제거.
- **NMF (Non-negative Matrix Factorization):** 모든 요소가 양수인 행렬로 분해하여 부분-전체 관계를 더 명확히 파악 (이미지 분석, 텍스트 마이닝).
- **의의:** 아마존, 넷플릭스 등 현대 추천 시스템의 비약적 발전을 이끈 핵심 알고리즘이며, 고차원 데이터를 다루는 데이터 사이언스의 필수 도구.
## 핵심
- **목표**: R (m×n, 희소) → U (m×k) · Vᵀ (k×n), k ≪ min(m,n).
- **변형**: SVD (full/truncated), NMF (≥0 제약, 해석성), ALS (희소 explicit/implicit 피드백), FunkSVD (RMSE optimize), BPR (ranking loss).
- **손실**: explicit → MSE on observed; implicit → weighted MSE w/ confidence (Hu-Koren-Volinsky).
- **정규화**: L2 (`λ‖U‖² + λ‖V‖²`) — 과적합 방지. λ 튜닝 필수.
- **Cold-start**: side feature 결합 (FM, hybrid), content-based fallback.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 선형적인 관계만 포착할 수 있다는 한계가 있어, 최근에는 신경망 기반의 임베딩(Neural Matrix Factorization)과 결합하여 비선형적인 복잡한 관계까지 학습하는 방향으로 진화.
- **정책 변화:** Antigravity 프로젝트는 사용자의 지식 탐색 로그를 분석하여 개인화된 학습 경로를 추천할 때, 행렬 분해 기법을 활용하여 사용자가 아직 발견하지 못한 '연관 지식'을 도출함.
## 결정 기준
| 데이터 | 알고리즘 | 라이브러리 |
|---|---|---|
| 작은 dense matrix, 차원 축소 | Truncated SVD | `sklearn.decomposition.TruncatedSVD` |
| 토픽 모델 / 해석성 | NMF | `sklearn.decomposition.NMF` |
| Explicit ratings (1-5) | SVD/SVD++ | `surprise` |
| Implicit feedback (click/play) | ALS / BPR | `implicit` |
| 사이드 피처 포함 | Factorization Machines | `xlearn`, `pyFM` |
| 대규모 분산 | Spark ALS | `pyspark.ml.recommendation` |
| 딥러닝 추천 | NCF / Two-Tower | TF Recommenders, PyTorch |
## 🔗 지식 연결 (Graph)
- [[Collaborative-Filtering|Collaborative-Filtering]], [[Dimensionality-Reduction|Dimensionality-Reduction]], [[Item-Item-Collaborative-Filtering|Item-Item-Collaborative-Filtering]], Neural-Networks-Foundations
- **Raw Source:** 10_Wiki/Topics/AI/Matrix-Factorization.md
## 💻 패턴
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### Truncated SVD
```python
from sklearn.decomposition import TruncatedSVD
svd = TruncatedSVD(n_components=50, random_state=0)
U = svd.fit_transform(X) # (n_samples, 50)
V = svd.components_ # (50, n_features)
explained = svd.explained_variance_ratio_.sum()
```
**언제 이 지식을 쓰는가:**
- *(TODO)*
### NMF (해석 가능 토픽)
```python
from sklearn.decomposition import NMF
nmf = NMF(n_components=10, init="nndsvda", l1_ratio=0.5, max_iter=500)
W = nmf.fit_transform(X_tfidf) # 문서×토픽
H = nmf.components_ # 토픽×단어
```
**언제 쓰면 안 되는가:**
- *(TODO)*
### ALS implicit (BM25 weighting)
```python
import implicit, scipy.sparse as sp
from implicit.nearest_neighbours import bm25_weight
user_item = sp.csr_matrix((vals, (uids, iids)))
weighted = bm25_weight(user_item, K1=100, B=0.8).tocsr()
model = implicit.als.AlternatingLeastSquares(factors=64, regularization=0.05, iterations=20)
model.fit(weighted)
ids, scores = model.recommend(user_id=42, user_items=user_item[42], N=10)
```
## 🧪 검증 상태 (Validation)
### Surprise (explicit ratings)
```python
from surprise import SVD, Dataset, Reader, accuracy
from surprise.model_selection import train_test_split, GridSearchCV
data = Dataset.load_from_df(df[["user","item","rating"]], Reader(rating_scale=(1,5)))
gs = GridSearchCV(SVD, {"n_factors":[50,100], "lr_all":[0.005], "reg_all":[0.02,0.1]},
measures=["rmse"], cv=3)
gs.fit(data); print(gs.best_score["rmse"], gs.best_params["rmse"])
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### From-scratch SGD (FunkSVD)
```python
def funk_svd(R_obs, k=20, lr=0.005, reg=0.02, epochs=20):
m, n = R_obs.shape
U = np.random.normal(0, 0.1, (m, k)); V = np.random.normal(0, 0.1, (n, k))
for _ in range(epochs):
for i, j, r in R_obs: # list of (user, item, rating)
err = r - U[i] @ V[j]
U[i] += lr * (err * V[j] - reg * U[i])
V[j] += lr * (err * U[i] - reg * V[j])
return U, V
```
## 🧬 중복 검사 (Duplicate Check)
### Cold-start: Hybrid with content
```python
# 신규 아이템: content embedding으로 V_new 초기화
from sentence_transformers import SentenceTransformer
emb = SentenceTransformer("all-MiniLM-L6-v2").encode(item_descriptions)
V_new = projection_layer(emb) # learned mapping → factor space
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🔗 Graph
- 상위: [[Recommender-Systems]] · [[Linear-Algebra]] · [[Dimensionality-Reduction]]
- 관련: [[SVD]] · [[NMF]] · [[ALS]] · [[Collaborative-Filtering]] · [[Factorization-Machines]] · [[Two-Tower]]
- 비교: [[Neural-Collaborative-Filtering]] · [[Graph-Recommenders]]
## 🕓 변경 이력 (Changelog)
## 🤖 LLM 활용
- LLM 임베딩 → MF의 V를 부분 초기화 → cold-start 완화.
- 잠재 factor 해석: top-N 아이템을 LLM에 던져 "이 그룹 공통 테마는?" — 차원 라벨링 자동화.
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## ❌ 안티패턴
- **Implicit feedback에 MSE 그대로** — 0(미상호작용)을 negative로 학습 → confidence weighting 필요.
- **k 무작정 크게** — 과적합·메모리 폭발. validation으로 elbow 찾기.
- **정규화 0** — train RMSE만 떨어지고 test 폭발.
- **유저/아이템 ID 인코딩 누락** — sparse matrix 인덱스 mismatch 흔함.
- **Cold-start에 MF 단독** — 신규 유저/아이템은 hybrid/content 필수.
- **시간 무시** — 추천에선 최근성 큼. session-aware 모델 또는 time-decay weighting.
## 🧪 검증 / 중복
- 중복: [[SVD]], [[NMF]], [[ALS]] 별도 — 본 문서는 우산.
- 검증: held-out RMSE/MAE (explicit), NDCG@k·Recall@k·MAP (implicit). bootstrap CI 권장.
## 🕓 Changelog
- 2026-05-08 | Phase 1 — 자동 시드.
- 2026-05-10 | Manual cleanup — SVD/NMF/ALS/Surprise/FunkSVD 코드, cold-start, 안티패턴 정리.