You want to recommend something a person has not rated yet. Their past ratings help, but most user-item pairs are missing, so a recommendation needs to draw on patterns across other people's preferences too. Matrix factorisation looks for a smaller set of patterns behind that incomplete table. Retaining only seven SVD components predicts unseen ratings better than keeping the full decomposition.
We hide known Jester joke ratings. Rank-7 SVD lowers held-out RMSE from the bias baseline's 4.37 to 4.04. The data covers 24,983 users and 100 jokes. Building the collaborative filtering model and varying its rank shows which patterns transfer to missing ratings.
Let's Build It
Open this in Google Colab and run it top to bottom. It downloads the real Jester dataset, factorises the ratings, and scores predictions on held-out ratings.
The animation shows the whole trick. On the left is a block of real ratings; on the right, the matrix rebuilt from only its top few singular directions. A rank-1 rebuild already captures who is generous and which jokes land; adding more rank sharpens the picture, until it starts refitting noise and the held-out error climbs back up.

import urllib.request, io, zipfile
import numpy as np
import xlrd # pip install xlrd==1.2.0 (reads the legacy .xls)
# Load the Jester joke-ratings dataset: 24,983 users x 100 jokes, -10 to +10.
url = "https://goldberg.berkeley.edu/jester-data/jester-data-1.zip"
xls = zipfile.ZipFile(io.BytesIO(urllib.request.urlopen(url).read())).read("jester-data-1.xls")
sheet = xlrd.open_workbook(file_contents=xls).sheet_by_index(0)
raw = np.array([sheet.row_values(r) for r in range(sheet.nrows)], float)
R = raw[:, 1:] # drop the ratings-count column
R[R == 99.0] = np.nan # 99 marks an unrated joke
dense = R[~np.isnan(R).any(1)] # 7,200 users who rated all 100 jokes
rng = np.random.default_rng(0)
D = dense[rng.choice(len(dense), 2000, replace=False)] # 2,000-user demo block
# Hold out 10% of the known ratings so we can score predictions honestly.
test = rng.random(D.shape) < 0.10
train = np.where(test, np.nan, D)
idx = np.where(test)
truth = D[idx]
# Centre each user, fill their gaps with their own mean, then factorise.
user_mean = np.nanmean(train, axis=1, keepdims=True)
filled = np.where(np.isnan(train), user_mean, train) - user_mean
U, s, Vt = np.linalg.svd(filled, full_matrices=False)
def svd_predict(k):
recon = (U[:, :k] * s[:k]) @ Vt[:k] + user_mean
return recon[idx]
rmse = lambda p: np.sqrt(np.mean((p - truth) ** 2))
# Baseline: predict mu + user offset + joke offset (no interactions).
mu = np.nanmean(train)
b_u = np.nanmean(train, axis=1) - mu
b_i = np.nanmean(train, axis=0) - mu
bias_pred = mu + b_u[idx[0]] + b_i[idx[1]]
print(f"user+item bias RMSE : {rmse(bias_pred):.2f}") # 4.37
print(f"rank-7 SVD RMSE : {rmse(svd_predict(7)):.2f}") # 4.04
The SVD prediction beats a strong bias baseline that already knows each user's generosity and each joke's popularity. You just built a matrix-factorisation recommender in about twenty lines. Now let us take it apart.
What Just Happened?
Three matrices from one
np.linalg.svd factors any matrix (here 2,000 users by 100 jokes) into three pieces:
Think of it as a translation between people and jokes through a small shared vocabulary of latent tastes. Each column of is one taste direction scored for every user (how much this person leans that way). Each row of scores every joke on that same direction (how strongly the joke expresses it). The diagonal of , the singular values , says how important each taste is across the whole crowd.
A user's predicted rating for a joke is the dot product of their taste vector and the joke's taste vector, scaled by those importances. Latent taste 1 might be "enjoys crude one-liners", taste 2 "prefers wordplay", and so on. Nobody labelled these; the decomposition read them straight off the ratings.
Centre, then factorise
Two lines before the SVD do the real work. We subtract each user's mean rating, so a grumpy rater who scores everything low and a cheerful one who scores everything high sit on the same scale, and the factorisation models deviations from personal baseline rather than personality. We then fill the held-out gaps with that same user mean, which after centring becomes zero, a neutral placeholder that adds no signal. The raw ratings show exactly the row-and-column structure this exposes.

Truncate to recommend
The magic is in the truncation. We keep only the top columns of , the top singular values, and the top rows of :
Reconstruct with and every missing entry gets filled with a number that blends the seven strongest crowd tastes. That reconstructed number is the recommendation. Rank the unseen jokes by their predicted rating and you have a top-N list.
Going Deeper
The rank knob
The rank is the only hyperparameter, and it behaves like every other capacity knob in machine learning. Too small and the model is too coarse to fit anyone well. Too large and it starts reconstructing the noise in the training ratings, which does not generalise. Sweep from 1 to 60 and score each on the held-out set.

The curve is a clean U. Rank 7 wins with an RMSE of 4.04 and an MAE of 3.11, a 7.5% and 10.4% improvement over the bias baseline. Push past roughly rank 48 and the SVD is worse than a model that only knows averages. If you want to feel this trade-off interactively, the Overfitting Explorer shows the same underfit-to-overfit arc on a regression problem.
Signal in the head, noise in the tail
Why does a small rank win? Look at the singular values. The first one towers over the rest (the "how funny is this to everyone" direction), then they decay into a long, shallow tail.

Here is the counterintuitive part. Rank 7 keeps only about a third of the matrix's total variance, yet it predicts best. The leading directions carry the shared structure that transfers to unseen ratings; the long tail carries individual quirks and measurement noise that do not. Variance explained is not the same as predictive signal, and truncating the SVD is how you throw the noise away. That this rank- reconstruction is the best possible rank- approximation is a theorem, which we come to below.
The same decomposition, other doors
The SVD you just used for recommendations is the same computation behind two techniques that look unrelated.
PCA is SVD on centred data. Subtract the column means from a data matrix and take its SVD; the right singular vectors are the principal components and are proportional to the variance along each. On Iris the two projections land on top of each other to fifteen decimal places.
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
X = load_iris().data
Xc = X - X.mean(0) # centre the columns
U, s, Vt = np.linalg.svd(Xc, full_matrices=False)
scores_svd = (U * s)[:, :2] # SVD projection
scores_pca = PCA(n_components=2).fit_transform(Xc)
print(np.abs(np.abs(scores_svd) - np.abs(scores_pca)).max()) # ~4e-15

The PCA and SVD post derives this link in full and uses truncated SVD to compress images. The recommender here is that same low-rank approximation applied to a user-item matrix instead of pixels.
Latent semantic indexing is SVD on a term-document matrix. Replace users with words and jokes with documents, and the counts of which word appears in which document form a matrix. Its SVD finds latent topics. Take the classic five-word toy matrix and project the words into two latent dimensions.
A = np.array([[2,0,8,6,0,3,1], # doctor
[1,6,0,1,7,0,1], # car
[5,0,7,4,0,5,6], # nurse
[7,0,8,5,0,8,5], # hospital
[0,10,0,0,7,0,0]]) # wheel
U, s, Vt = np.linalg.svd(A.astype(float), full_matrices=False)
coords = U[:, :2] * s[:2] # each word placed in 2D topic space

doctor, nurse, and hospital collapse onto one axis; car and wheel onto the orthogonal one. The SVD discovered "medicine" and "vehicles" as latent topics from co-occurrence alone, the same way it discovered taste directions from ratings. This is why the machinery behind text classification and search shares a spine with recommenders.
When plain SVD is the wrong tool
Jester is unusually kind: it is dense, because we kept the users who rated all 100 jokes. Real ratings matrices are mostly empty. The MovieLens matrix used in the collaborative filtering post is 94% missing. Filling those gaps with means before an SVD injects a huge amount of made-up data, and the factorisation spends its capacity fitting the imputation rather than the ratings.
The fix that won the Netflix Prize keeps the SVD's factor-model shape, , but fits the factors and by gradient descent over only the observed entries, with regularisation. That is the model built in the collaborative filtering post, and it is the right tool once the matrix is sparse. Use the batch SVD here when the matrix is dense or you can afford to complete it; reach for gradient-based factorisation when it is not. For a related take on choosing factor models under uncertainty, see probabilistic PCA and factor analysis.
Where This Comes From
The truncation that makes all of this work rests on a theorem from 1936. Carl Eckart and Gale Young, working in psychometrics, proved that the truncated SVD is the best low-rank approximation of a matrix.
"The approximation of one matrix by another of lower rank." -- Eckart & Young (1936), Psychometrika
Formally, among all matrices of rank at most , the one closest to in Frobenius (and spectral) norm is exactly , and the error is set by the singular values you dropped:
That is why keeping the largest singular values is optimal, not just reasonable. The connection to eigenvalues comes from : the right singular vectors are eigenvectors of and the singular values are the square roots of its eigenvalues.
The two applications arrived decades later. Deerwester and colleagues introduced latent semantic indexing in 1990, using the SVD of a term-document matrix to retrieve documents by meaning rather than exact words. Sarwar, Karypis, Konstan, and Riedl brought it to recommenders in their 2000 case study "Application of Dimensionality Reduction in Recommender System", the paper the original code for this post was built from. Simon Funk's 2006 Netflix Prize write-up then reframed the factorisation as regularised gradient descent over observed ratings, which is the form recommenders use today.
Further Reading
- The theorem: Eckart & Young (1936), "The approximation of one matrix by another of lower rank", Psychometrika 1(3). The optimality of truncated SVD.
- Recommenders: Sarwar et al. (2000), "Application of Dimensionality Reduction in Recommender System". Koren, Bell & Volinsky (2009), "Matrix Factorization Techniques for Recommender Systems", IEEE Computer, is the definitive Netflix-era survey.
- Search: Deerwester et al. (1990), "Indexing by Latent Semantic Analysis".
- Next step: the collaborative filtering post fits the same factor model on sparse data with gradient descent.
Interactive Tools
- PCA Visualizer: Drag a point cloud and watch the principal components, scree plot and explained variance follow, then project onto one component to see what the reduction discards.
- Eigenvalue and SVD Visualizer: See how , , and transform space and how singular values scale each direction.
- Overfitting Explorer: Feel the underfit-to-overfit trade-off that the rank controls in the RMSE curve above.
Related Posts
- Collaborative Filtering from Scratch in Python: The sparse-matrix sibling: the same factor model fitted by gradient descent on MovieLens.
- PCA and SVD: The Linear Algebra You Actually Need: Proves PCA and SVD are the same computation and compresses images with truncation.
- Probabilistic PCA, EM-PCA, Bayesian PCA, Factor Analysis: Matrix factorisation with a probabilistic lens and principled rank selection.
- LDA vs PCA: Supervised Meets Unsupervised Dimensionality Reduction: Another eigenvalue problem, this time using labels to reduce dimensions.
- Text Classification from Scratch: TF-IDF and Naive Bayes: The term-document matrix that latent semantic indexing factorises.





