Simple Algorithm
Machine Learning · Descent · 22 min

Matrix Factorization & Recommenders

Low-rank structure behind ratings, topics and images.

In 2006 Netflix released about 100 million movie ratings from 480,000 customers and offered $1 million to anyone who could predict held-out ratings 10% more accurately than its own system. Nearly 99% of the customer-by-movie table was empty. Filling it in looks hopeless, unless the table is nearly low rank: a few hidden factors of taste explain most ratings. This lesson builds that idea from the SVD to regularized factorization fitted by alternating least squares, and meets its relatives in documents and images.

What you’ll learn

  • Represent ratings, documents and images as matrices, and interpret a rank-rr factorization X≈PQ⊤X\approx PQ^\top as latent factors.
  • State the Eckart–Young theorem and compute best low-rank approximations with the truncated SVD.
  • Set up regularized matrix factorization with biases for a partially observed matrix, and derive the alternating least squares and stochastic gradient updates.
  • Explain cold start, implicit feedback and offline evaluation, and contrast SVD, NMF and topic models as factorizations.

Data as matrices, and what low rank means

Many data sets are tables: users × items (ratings, clicks), documents × words (counts), images × pixels, genes × samples. A matrix factorization approximates such an m×nm\times n table by a product of two thin matrices,

X≈PQ⊤,P∈Rm×r,Q∈Rn×r,x^ui=pu⊤qi,X\approx PQ^\top,\qquad P\in\R^{m\times r},\quad Q\in\R^{n\times r},\qquad\hat x_{ui}=\mathbf p_u^\top\mathbf q_i,

so every row uu gets a vector pu\mathbf p_u of rr latent factors, and so does every column ii. In a recommender system a movie's factors might measure how much action or romance it has, a user's factors how much they enjoy each, and the predicted rating adds up the matches. The factors are learned from the data, not named in advance. A low-rank table is redundant: with rank rr, every row is a combination of just rr rows.

User (factors)HeistBallroomMixed DoublesGetaway
Ana (2,0)(2,0)4123
Ben (0,2)(0,2)1420
Cy (1,1)(1,1)2.52.521.5
Dee (2,1)(2,1)4.5333
A rank-2 ratings table. Each user has factors (likes action, likes romance), and the movies have factors (2,12)(2,\tfrac12), (12,2)(\tfrac12,2), (1,1)(1,1) and (32,0)(\tfrac32,0); every rating is a dot product, such as Ana on Heist: 2⋅2+0⋅12=42\cdot2+0\cdot\tfrac12=4.
Think first Look at the rows for Cy and Dee. How are they related to Ana's and Ben's rows, and why?

Cy's row is the average of Ana's and Ben's, and Dee's row is Ana's plus half of Ben's: (4.5,3,3,3)=(4,1,2,3)+12(1,4,2,0)(4.5,3,3,3)=(4,1,2,3)+\tfrac12(1,4,2,0). Their factor vectors are the same combinations, (1,1)=12(2,0)+12(0,2)(1,1)=\tfrac12(2,0)+\tfrac12(0,2) and (2,1)=(2,0)+12(0,2)(2,1)=(2,0)+\tfrac12(0,2), and a rating is linear in the user's factors. In a rank-2 table, two rows determine all the others. That redundancy is what lets a factorization fill in entries it never saw.

Predict before you look

A service has 500,000 users and 20,000 items and fits r=50r=50 factors per user and per item. What percentage of the 500,000×20,000500{,}000\times20{,}000 table's entries is the number of factor parameters?

Show the answer

0.26 %

r(m+n)=50×520,000=2.6×107r(m+n)=50\times520{,}000=2.6\times10^7 parameters against mn=1010mn=10^{10} entries: 0.26%. That compression is the whole point. It is also why the model can generalize: it cannot memorize 101010^{10} arbitrary numbers, so it must find structure.

The best low-rank approximation: the SVD

When every entry is observed, the best factorization has a closed form. Write the singular value decomposition X=UΣV⊤=∑jσjujvj⊤X=U\Sigma V^\top=\sum_j\sigma_j\mathbf u_j\mathbf v_j^\top with σ1≥σ2≥⋯≥0\sigma_1\ge\sigma_2\ge\dots\ge0, and keep the top rr terms, Xr=∑j≤rσjujvj⊤X_r=\sum_{j\le r}\sigma_j\mathbf u_j\mathbf v_j^\top. It factors as P=UrΣr1/2P=U_r\Sigma_r^{1/2} and Q=VrΣr1/2Q=V_r\Sigma_r^{1/2}.

Applied to a centered data matrix with nn rows, this is principal component analysis: the right singular vectors are the principal directions, and σj2/n\sigma_j^2/n is the variance along direction jj. Applied to a term–document count matrix, it is latent semantic analysis (Deerwester, Dumais, Furnas, Landauer & Harshman, 1990): two documents that share no words can still land close together in the low-rank space if their words co-occur elsewhere, which partly solves the synonym problem of keyword search.

A useful habit is to look at the singular values. If they drop sharply after the first few, the table is nearly low rank and a small rr will do; if they decay slowly, any truncation throws away real signal.

Check your understanding

A centered data matrix has singular values 10, 6, 2 and 1. What fraction of ∥X∥F2\norm{X}_F^2 does the best rank-2 approximation keep?

  1. About 84%
  2. About 71%
  3. 50%
  4. About 96%
Show the answer

D. About 96%

∥X∥F2=∑jσj2=100+36+4+1=141\norm{X}_F^2=\sum_j\sigma_j^2=100+36+4+1=141, and the rank-2 truncation keeps 100+36=136100+36=136, or 136/141≈96.5%136/141\approx96.5\%. The squared error left over, 4+1=54+1=5, is the sum of the dropped squared singular values.

Missing entries and regularized factorization

Ratings tables are mostly empty: the Netflix Prize data filled about 1.2% of a 480,189×17,770480{,}189\times17{,}770 table. The SVD needs every entry, and filling the blanks with zeros, or with averages, tells the model that "not rated" means "hated", or merely "average", which is false: people rate what they chose to watch. Instead, fit the model to the set Ω\Omega of observed entries only:

min⁡b, P, Q ∑(u,i)∈Ω(rui−μ−bu−bi−pu⊤qi)2+λ(∑u(bu2+∥pu∥2)+∑i(bi2+∥qi∥2))\min_{b,\,P,\,Q}\ \sum_{(u,i)\in\Omega}\Big(r_{ui}-\mu-b_u-b_i-\mathbf p_u^\top\mathbf q_i\Big)^2+\lambda\Big(\sum_u\big(b_u^2+\norm{\mathbf p_u}^2\big)+\sum_i\big(b_i^2+\norm{\mathbf q_i}^2\big)\Big)
μ\mu is the global mean rating; the biases bub_u and bib_i capture a generous rater or a beloved movie; the dot product captures the interaction of tastes and traits. Koren, Bell & Volinsky (2009) describe this model and its refinements as they were developed during the Netflix Prize.

The biases alone are already a strong baseline. If the mean rating is μ=3.6\mu=3.6, a hard-to-please user has bu=−0.4b_u=-0.4 and a well-loved film has bi=+0.7b_i=+0.7, the baseline predicts 3.6−0.4+0.7=3.93.6-0.4+0.7=3.9 stars before any factors. The factors then explain what biases cannot: why this user loves this kind of film.

The ridge penalty λ\lambda is essential. A user with three ratings and 50 free factors would otherwise fit them perfectly in infinitely many ways and predict nonsense for everything else. Probabilistically, the objective is MAP estimation with Gaussian noise on the ratings and independent Gaussian priors on the biases and factors, with λ\lambda the ratio of the noise variance to the prior variance.

Alternating least squares and SGD

The objective is not convex in (P,Q)(P,Q) jointly: (P,Q)(P,Q) and (−P,−Q)(-P,-Q) fit equally well, while their midpoint (0,0)(0,0) fits badly. But fix QQ and the problem splits into one ridge regression per user, each in only rr unknowns. Drop the biases for clarity (they can be absorbed by appending a constant 1 to each factor vector):

DerivationThe ALS update
  1. min⁡pu ∑i∈Iu(rui−qi⊤pu)2+λ∥pu∥2=min⁡pu ∥ru−Qupu∥2+λ∥pu∥2\min_{\mathbf p_u}\ \sum_{i\in I_u}\big(r_{ui}-\mathbf q_i^\top\mathbf p_u\big)^2+\lambda\norm{\mathbf p_u}^2=\min_{\mathbf p_u}\ \norm{\mathbf r_u-Q_u\mathbf p_u}^2+\lambda\norm{\mathbf p_u}^2

    Fix the item factors. For user uu with rated items IuI_u, stack those items' factor vectors as the rows of Qu∈R∣Iu∣×rQ_u\in\R^{\abs{I_u}\times r} and their ratings in ru\mathbf r_u. Only pu\mathbf p_u is free:

  2. −2Qu⊤(ru−Qupu)+2λpu=0⟹pu=(Qu⊤Qu+λI)−1Qu⊤ru-2Q_u^\top(\mathbf r_u-Q_u\mathbf p_u)+2\lambda\mathbf p_u=\mathbf 0\quad\Longrightarrow\quad\mathbf p_u=\big(Q_u^\top Q_u+\lambda I\big)^{-1}Q_u^\top\mathbf r_u

    Set the gradient to zero. For λ>0\lambda>0 the matrix is positive definite, so the solution is unique even for a user with fewer ratings than factors:

  3. qi=(Pi⊤Pi+λI)−1Pi⊤ri\mathbf q_i=\big(P_i^\top P_i+\lambda I\big)^{-1}P_i^\top\mathbf r_i

    By symmetry, with the users' factors fixed, each item solves the same kind of problem over its raters UiU_i:

  4. J(Pt+1,Qt+1) ≤ J(Pt+1,Qt) ≤ J(Pt,Qt)J(P^{t+1},Q^{t+1})\ \le\ J(P^{t+1},Q^{t})\ \le\ J(P^{t},Q^{t})

    Each half-step solves its block exactly, so the objective JJ never increases, and since J≥0J\ge0 its values converge. The iterates approach stationary points, which need not be global minima. One sweep costs O(∣Ω∣ r2+(m+n) r3)O(\abs\Omega\,r^2+(m+n)\,r^3), and all users (then all items) can be solved in parallel.

Predict before you look

One latent factor (r=1r=1) and no biases. The item factors are q1=1q_1=1 and q2=2q_2=2; a user rated item 1 with 3 stars and item 2 with 5 stars; λ=1\lambda=1. What is the user's ALS update pup_u?

Show the answer

2.17

With r=1r=1 the update is pu=(q1r1+q2r2)/(q12+q22+λ)=(3+10)/(1+4+1)=13/6≈2.17p_u=(q_1r_1+q_2r_2)/(q_1^2+q_2^2+\lambda)=(3+10)/(1+4+1)=13/6\approx2.17. Without the penalty it would be 13/5=2.613/5=2.6: the ridge term shrinks it toward zero. The prediction for an item with q=1.5q=1.5 is 1.5×2.17≈3.251.5\times2.17\approx3.25 stars.

Stochastic gradient descent, popular during the Netflix Prize, sweeps over the observed ratings instead. For each (u,i)∈Ω(u,i)\in\Omega, with prediction error eui=rui−r^uie_{ui}=r_{ui}-\hat r_{ui} and learning rate η\eta, take a small step on that rating's loss (the factor 2 is absorbed into η\eta, and the penalty is applied at every visit, a common variant):

bu←bu+η (eui−λbu),bi←bi+η (eui−λbi),pu←pu+η (euiqi−λpu),qi←qi+η (euipu−λqi).\begin{aligned}b_u&\leftarrow b_u+\eta\,(e_{ui}-\lambda b_u),&\qquad b_i&\leftarrow b_i+\eta\,(e_{ui}-\lambda b_i),\\ \mathbf p_u&\leftarrow\mathbf p_u+\eta\,(e_{ui}\mathbf q_i-\lambda\mathbf p_u),&\qquad\mathbf q_i&\leftarrow\mathbf q_i+\eta\,(e_{ui}\mathbf p_u-\lambda\mathbf q_i).\end{aligned}
Each update costs O(r)O(r), so an epoch costs O(∣Ω∣ r)O(\abs\Omega\,r). SGD is simple and works with any differentiable loss; ALS needs no learning rate, parallelizes naturally, and stays efficient for implicit feedback, where every user–item pair counts.
python
import numpy as np

def als(R, mask, r=20, lam=0.1, sweeps=15, seed=0):
    """R: m x n ratings (ignored where mask is False); mask: m x n booleans."""
    rng = np.random.default_rng(seed)
    m, n = R.shape
    P = 0.1 * rng.standard_normal((m, r))
    Q = 0.1 * rng.standard_normal((n, r))
    I = lam * np.eye(r)
    for _ in range(sweeps):
        for u in range(m):                     # one ridge regression per user
            Qu = Q[mask[u]]                    # factors of the items u rated
            P[u] = np.linalg.solve(Qu.T @ Qu + I, Qu.T @ R[u, mask[u]])
        for i in range(n):                     # one ridge regression per item
            Pi = P[mask[:, i]]
            Q[i] = np.linalg.solve(Pi.T @ Pi + I, Pi.T @ R[mask[:, i], i])
    return P, Q                                # predict R[u, i] by P[u] @ Q[i]

Dense loops for clarity. Production systems store only the observed entries in sparse form and solve the users (then the items) in parallel.

Cold start, implicit feedback and other factorizations

Cold start. A new user or item has no ratings, so its factors stay at the prior, zero. Systems fall back on biases and popularity, ask a few onboarding questions, or predict the factors from side information such as a film's genre (hybrid models).

Implicit feedback. Most signals are clicks, plays and purchases rather than stars: positive-only, with no explicit dislikes. Hu, Koren & Volinsky (2008) use every user–item pair, with preference pui=1p_{ui}=1 if user uu interacted with item ii and 0 otherwise, weighted by a confidence cui=1+αruic_{ui}=1+\alpha r_{ui} that grows with the number of interactions ruir_{ui}. They minimize ∑u,icui(pui−xu⊤yi)2\sum_{u,i}c_{ui}(p_{ui}-\mathbf x_u^\top\mathbf y_i)^2 plus a ridge penalty. That sum has mnmn terms, yet ALS stays fast thanks to an algebraic shortcut derived in the Convergence lesson Collaborative Filtering.

Evaluation. Held-out RMSE measures rating prediction, but users see ranked lists, so ranking metrics, such as how many of a user's held-out items appear in the top 10, matter more, and an online A/B test is the final judge. The data are not missing at random, and a system retrained on the clicks its own recommendations produced can reinforce its own choices.

MethodFactorsFittingTypical use
Truncated SVD, PCAorthogonal, signedexact (Eckart–Young)compression, denoising, latent semantic analysis
Regularized factorizationunconstrained, ridge-penalizedALS or SGD on observed entries; nonconvexratings, implicit feedback
NMFnonnegativemultiplicative or alternating updates; nonconvexparts of images, topics in text, spectra
Topic modelsprobability vectorsmaximum likelihood or Bayesian inference on word countsthemes in document collections
Nonnegative matrix factorization forbids subtraction, so its factors often become additive parts: localized features such as noses and mouths for faces, and groups of co-occurring words for text (Lee & Seung, 1999). Latent Dirichlet allocation makes the document–word factorization probabilistic, with documents as mixtures of topics; the Convergence lesson Topic Models & Latent Dirichlet Allocation develops it.

Key takeaways

  • Tables of users × items, documents × words or images × pixels are often nearly low rank. A rank-rr factorization X≈PQ⊤X\approx PQ^\top gives every row and column rr latent factors, using r(m+n)r(m+n) numbers instead of mnmn, and the factors are determined only up to an invertible change of basis.
  • With every entry observed, the truncated SVD is the best rank-rr approximation, with squared Frobenius error ∑j>rσj2\sum_{j>r}\sigma_j^2 (Eckart–Young). On centered data it is PCA; on term–document counts, latent semantic analysis.
  • With missing entries, fit μ+bu+bi+pu⊤qi\mu+b_u+b_i+\mathbf p_u^\top\mathbf q_i to the observed ratings only, with a ridge penalty; never impute zeros.
  • ALS alternates closed-form ridge solutions pu=(Qu⊤Qu+λI)−1Qu⊤ru\mathbf p_u=(Q_u^\top Q_u+\lambda I)^{-1}Q_u^\top\mathbf r_u and never increases the objective, but guarantees only a stationary point; SGD visits ratings one at a time.
  • Cold start, implicit feedback, non-random missingness and ranking-based evaluation shape real recommenders. NMF and topic models are the factorizations of choice when factors should be additive parts or probabilities.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Why does each half-step of alternating least squares have a closed-form solution?

  1. Because the full objective is convex in (P,Q)(P,Q)
  2. Because with one factor matrix fixed, the objective is a separate ridge regression for each user (or each item)
  3. Because the SVD of the observed entries gives the factors directly
  4. Because the learning rate cancels out of the update
Show the answer

B. Because with one factor matrix fixed, the objective is a separate ridge regression for each user (or each item)

Fixing QQ makes each user's loss ∥ru−Qupu∥2+λ∥pu∥2\norm{\mathbf r_u-Q_u\mathbf p_u}^2+\lambda\norm{\mathbf p_u}^2, a quadratic in pu\mathbf p_u alone, solved by pu=(Qu⊤Qu+λI)−1Qu⊤ru\mathbf p_u=(Q_u^\top Q_u+\lambda I)^{-1}Q_u^\top\mathbf r_u. The joint problem stays nonconvex, so ALS guarantees only a stationary point.

Question 2

A user has rated 3 movies, and the model has r=50r=50 factors. What keeps the prediction for this user sensible?

  1. The biases bub_u and bib_i alone
  2. The truncated SVD of the ratings matrix
  3. The ridge penalty: without it, 50 free numbers could fit 3 ratings exactly in infinitely many ways
  4. Nothing; such users must be removed from the data
Show the answer

C. The ridge penalty: without it, 50 free numbers could fit 3 ratings exactly in infinitely many ways

With λ>0\lambda>0, (Qu⊤Qu+λI)(Q_u^\top Q_u+\lambda I) is invertible even though QuQ_u has only 3 rows, and the solution is the smallest-norm factor vector that fits reasonably, shrunk toward zero, so the prediction falls back toward the biases.

Question 3

Two teams factor the same ratings matrix, report different item-factor matrices, and get identical predictions. How?

  1. Factors are determined only up to an invertible change of basis: PQ⊤=(PR)(QR−⊤)⊤PQ^\top=(PR)(QR^{-\top})^\top
  2. One team must have made an error
  3. One team's item factors are the transpose of the other's
  4. Identical predictions are impossible with different factors
Show the answer

A. Factors are determined only up to an invertible change of basis: PQ⊤=(PR)(QR−⊤)⊤PQ^\top=(PR)(QR^{-\top})^\top

Any invertible RR (an orthogonal one if the penalty is to stay the same) produces new factors with the same products. That is why individual factors are not reliably interpretable, while predictions and the spanned subspaces are.

Question 4

In the implicit-feedback model of Hu, Koren & Volinsky, what happens to a user–item pair with no interactions?

  1. It is ignored, as in explicit-rating models
  2. It is treated as a strong dislike
  3. It is imputed with the item's average rating
  4. It is a weak negative: preference 0 with the lowest confidence, cui=1c_{ui}=1
Show the answer

D. It is a weak negative: preference 0 with the lowest confidence, cui=1c_{ui}=1

Every pair enters the loss, but confidence cui=1+αruic_{ui}=1+\alpha r_{ui} grows with the number of interactions, so absent pairs pull gently toward 0 while observed ones pull hard toward 1. A missing click may mean "never saw it" rather than "dislikes it".

Question 5

Why not fill the missing ratings with zeros and take a truncated SVD?

  1. Because the SVD cannot be computed for matrices containing zeros
  2. Because it treats "not rated" as "rated zero", dragging predictions down, and missing ratings are not missing at random
  3. It would give the same answer as the regularized fit, only more slowly
  4. Because zeros make the matrix full rank, so no approximation exists
Show the answer

B. Because it treats "not rated" as "rated zero", dragging predictions down, and missing ratings are not missing at random

With about 99% of entries missing, the zeros dominate the fit, and the approximation mostly learns where ratings are absent rather than what they would be. Fitting only the observed entries avoids this; how to correct for non-random missingness is a topic of the Convergence lesson Collaborative Filtering.

Go deeper

Further reading

  • Y. Koren, R. Bell & C. Volinsky, "Matrix factorization techniques for recommender systems," Computer 42(8), 30–37 (2009).
  • C. Eckart & G. Young, "The approximation of one matrix by another of lower rank," Psychometrika 1(3), 211–218 (1936).
  • Y. Hu, Y. Koren & C. Volinsky, "Collaborative filtering for implicit feedback datasets," Proceedings of the 8th IEEE International Conference on Data Mining, 263–272 (2008).
  • D. D. Lee & H. S. Seung, "Learning the parts of objects by non-negative matrix factorization," Nature 401, 788–791 (1999).