docs(10_Wiki): 위키 전체 재구성 — Topic_* 폴더를 4개 카테고리로 통합 + 대규모 중복 제거

Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를
Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류.

- 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로
  자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거,
  동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거.
- 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming,
  Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business,
  Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로,
  나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는
  title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백).
  원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지.
- 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서.
- 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는
  지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지.
- Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경.
- 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
This commit is contained in:
Antigravity Agent
2026-07-05 00:33:48 +09:00
parent 1cfd3bbb56
commit 9148c358d0
6455 changed files with 1 additions and 86875 deletions
@@ -0,0 +1,124 @@
---
id: wiki-2026-0508-matrix-factorization
title: Matrix Factorization
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [MF, Matrix Decomposition, Latent Factor Models, Collaborative Filtering MF]
duplicate_of: none
source_trust_level: A
confidence_score: 0.93
verification_status: applied
tags: [ml, recommender, svd, nmf, als, collaborative-filtering, dimensionality-reduction]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack: { language: python, framework: scipy|surprise|implicit|sklearn }
---
# Matrix Factorization
> 한 줄: 큰 행렬 R ≈ U·Vᵀ로 분해해 잠재 요인(latent factor)을 학습 — 추천 시스템·차원 축소·이미지 압축의 핵심.
## 핵심
- **목표**: 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.
## 결정 기준
| 데이터 | 알고리즘 | 라이브러리 |
|---|---|---|
| 작은 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 |
## 💻 패턴
### 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()
```
### 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_ # 토픽×단어
```
### 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)
```
### 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"])
```
### 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
```
### 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
```
## 🔗 Graph
- 상위: [[Recommender-Systems]] · [[Linear-Algebra-Foundations|Linear-Algebra]] · [[Dimensionality-Reduction]]
- 관련: [[SVD]] · [[ALS]] · [[Collaborative-Filtering]] · [[Two-Tower]]
## 🤖 LLM 활용
- LLM 임베딩 → MF의 V를 부분 초기화 → cold-start 완화.
- 잠재 factor 해석: top-N 아이템을 LLM에 던져 "이 그룹 공통 테마는?" — 차원 라벨링 자동화.
## ❌ 안티패턴
- **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, 안티패턴 정리.