Matrix Factorization (ALS) for Recommendations
Key idea: approximate the sparse user × item rating matrix as U Vᵀ with k-dimensional factors, fit only on observed entries with L2 regularization. Alternating least squares: fixing V makes each user's factor a small ridge regression (closed form), then swap.
The objective is non-convex: from a small random start, ALS sometimes stalls in a bad local minimum (try it — some seeds give a held-out error 50× worse). Spectral initialization — the top-k SVD of the observed matrix rescaled by 1/(fraction observed) — starts near the right subspace and fixes this.
import numpy as np
def als(R, mask, k=3, lam=0.1, iters=30):
P, s, Qt = np.linalg.svd(R / mask.mean(), full_matrices=False) # spectral init
U, V = P[:, :k] * np.sqrt(s[:k]), Qt[:k].T * np.sqrt(s[:k])
reg = lam * np.eye(k)
for _ in range(iters):
for u in range(R.shape[0]): # ridge regression per user
Vu = V[mask[u]]
U[u] = np.linalg.solve(Vu.T @ Vu + reg, Vu.T @ R[u, mask[u]])
for i in range(R.shape[1]): # ... and per item
Ui = U[mask[:, i]]
V[i] = np.linalg.solve(Ui.T @ Ui + reg, Ui.T @ R[mask[:, i], i])
return U, V
rng = np.random.default_rng(1)
true = rng.normal(size=(40, 3)) @ rng.normal(size=(25, 3)).T # rank-3 "taste" matrix
mask = rng.random(true.shape) < 0.5 # observe half the ratings
U, V = als(np.where(mask, true, 0), mask)
pred = U @ V.T
rmse = lambda m: np.sqrt(((pred - true)[m] ** 2).mean())
assert rmse(mask) < 0.1 and rmse(~mask) < 0.3 # generalizes to unseen ratings
print("ok, train rmse", round(float(rmse(mask)), 3), "held-out rmse", round(float(rmse(~mask)), 3))
Implicit feedback (clicks/views) uses weighted ALS with confidence weights, or a two-tower model trained with sampled negatives.