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- factorization 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 table by a product of two thin matrices,
so every row gets a vector of latent factors, and so does every column . 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 , every row is a combination of just rows.
| User (factors) | Heist | Ballroom | Mixed Doubles | Getaway |
|---|---|---|---|---|
| Ana | 4 | 1 | 2 | 3 |
| Ben | 1 | 4 | 2 | 0 |
| Cy | 2.5 | 2.5 | 2 | 1.5 |
| Dee | 4.5 | 3 | 3 | 3 |
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: . Their factor vectors are the same combinations, and , 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.
A service has 500,000 users and 20,000 items and fits factors per user and per item. What percentage of the table's entries is the number of factor parameters?
Show the answer
0.26 %
parameters against entries: 0.26%. That compression is the whole point. It is also why the model can generalize: it cannot memorize 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 with , and keep the top terms, . It factors as and .
Applied to a centered data matrix with rows, this is principal component analysis: the right singular vectors are the principal directions, and is the variance along direction . 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 will do; if they decay slowly, any truncation throws away real signal.
A centered data matrix has singular values 10, 6, 2 and 1. What fraction of does the best rank-2 approximation keep?
- About 84%
- About 71%
- 50%
- About 96%
Show the answer
D. About 96%
, and the rank-2 truncation keeps , or . The squared error left over, , 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 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 of observed entries only:
The biases alone are already a strong baseline. If the mean rating is , a hard-to-please user has and a well-loved film has , the baseline predicts stars before any factors. The factors then explain what biases cannot: why this user loves this kind of film.
The ridge penalty 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 the ratio of the noise variance to the prior variance.
Alternating least squares and SGD
The objective is not convex in jointly: and fit equally well, while their midpoint fits badly. But fix and the problem splits into one ridge regression per user, each in only unknowns. Drop the biases for clarity (they can be absorbed by appending a constant 1 to each factor vector):
Fix the item factors. For user with rated items , stack those items' factor vectors as the rows of and their ratings in . Only is free:
Set the gradient to zero. For the matrix is positive definite, so the solution is unique even for a user with fewer ratings than factors:
By symmetry, with the users' factors fixed, each item solves the same kind of problem over its raters :
Each half-step solves its block exactly, so the objective never increases, and since its values converge. The iterates approach stationary points, which need not be global minima. One sweep costs , and all users (then all items) can be solved in parallel.
One latent factor () and no biases. The item factors are and ; a user rated item 1 with 3 stars and item 2 with 5 stars; . What is the user's ALS update ?
Show the answer
2.17
With the update is . Without the penalty it would be : the ridge term shrinks it toward zero. The prediction for an item with is stars.
Stochastic gradient descent, popular during the Netflix Prize, sweeps over the observed ratings instead. For each , with prediction error and learning rate , take a small step on that rating's loss (the factor 2 is absorbed into , and the penalty is applied at every visit, a common variant):
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 if user interacted with item and 0 otherwise, weighted by a confidence that grows with the number of interactions . They minimize plus a ridge penalty. That sum has 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.
| Method | Factors | Fitting | Typical use |
|---|---|---|---|
| Truncated SVD, PCA | orthogonal, signed | exact (Eckart–Young) | compression, denoising, latent semantic analysis |
| Regularized factorization | unconstrained, ridge-penalized | ALS or SGD on observed entries; nonconvex | ratings, implicit feedback |
| NMF | nonnegative | multiplicative or alternating updates; nonconvex | parts of images, topics in text, spectra |
| Topic models | probability vectors | maximum likelihood or Bayesian inference on word counts | themes in document collections |
Key takeaways
- Tables of users × items, documents × words or images × pixels are often nearly low rank. A rank- factorization gives every row and column latent factors, using numbers instead of , and the factors are determined only up to an invertible change of basis.
- With every entry observed, the truncated SVD is the best rank- approximation, with squared Frobenius error (Eckart–Young). On centered data it is PCA; on term–document counts, latent semantic analysis.
- With missing entries, fit to the observed ratings only, with a ridge penalty; never impute zeros.
- ALS alternates closed-form ridge solutions 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.
Why does each half-step of alternating least squares have a closed-form solution?
- Because the full objective is convex in
- Because with one factor matrix fixed, the objective is a separate ridge regression for each user (or each item)
- Because the SVD of the observed entries gives the factors directly
- 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 makes each user's loss , a quadratic in alone, solved by . The joint problem stays nonconvex, so ALS guarantees only a stationary point.
A user has rated 3 movies, and the model has factors. What keeps the prediction for this user sensible?
- The biases and alone
- The truncated SVD of the ratings matrix
- The ridge penalty: without it, 50 free numbers could fit 3 ratings exactly in infinitely many ways
- 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 , is invertible even though 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.
Two teams factor the same ratings matrix, report different item-factor matrices, and get identical predictions. How?
- Factors are determined only up to an invertible change of basis:
- One team must have made an error
- One team's item factors are the transpose of the other's
- Identical predictions are impossible with different factors
Show the answer
A. Factors are determined only up to an invertible change of basis:
Any invertible (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.
In the implicit-feedback model of Hu, Koren & Volinsky, what happens to a user–item pair with no interactions?
- It is ignored, as in explicit-rating models
- It is treated as a strong dislike
- It is imputed with the item's average rating
- It is a weak negative: preference 0 with the lowest confidence,
Show the answer
D. It is a weak negative: preference 0 with the lowest confidence,
Every pair enters the loss, but confidence 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".
Why not fill the missing ratings with zeros and take a truncated SVD?
- Because the SVD cannot be computed for matrices containing zeros
- Because it treats "not rated" as "rated zero", dragging predictions down, and missing ratings are not missing at random
- It would give the same answer as the regularized fit, only more slowly
- 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
- Collaborative Filtering · Latent factors, implicit feedback and the Netflix Prize.
- Matrix Completion Theory · Nuclear norms, incoherence and how many entries you need.
- NMF, ICA & Sparse Coding · Parts-based, independent and sparse representations.
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).