---
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, 안티패턴 정리.
