SVD for Recommender Systems: Matrix Factorisation in NumPy

Build a recommender from scratch with the SVD: factorise a user-item ratings matrix, tune the rank, and beat mean baselines on real Jester data.

Cover Image for SVD for Recommender Systems: Matrix Factorisation in NumPy

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.

Open In Colab

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.

Two side-by-side heatmaps of an 80-user by 100-joke ratings block. The left panel is the original ratings, noisy and detailed. The right panel is a low-rank SVD reconstruction that starts smooth at rank 1, capturing broad row and column structure, and sharpens toward the original as the rank increases, with the held-out RMSE shown in the title falling then rising.

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 AA (here 2,000 users by 100 jokes) into three pieces:

A=UΣV⊤A = U \Sigma V^{\top}

Think of it as a translation between people and jokes through a small shared vocabulary of latent tastes. Each column of UU is one taste direction scored for every user (how much this person leans that way). Each row of V⊤V^{\top} scores every joke on that same direction (how strongly the joke expresses it). The diagonal of Σ\Sigma, the singular values σ1≥σ2≥⋯≥0\sigma_1 \ge \sigma_2 \ge \dots \ge 0, 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.

Heatmap of 80 Jester users by 100 jokes with a red-blue diverging colour scale from -10 to +10. Whole rows lean red or blue (generous versus harsh raters) and several columns are consistently red or blue (widely liked or disliked jokes), showing strong low-rank structure.

Truncate to recommend

The magic is in the truncation. We keep only the top kk columns of UU, the top kk singular values, and the top kk rows of V⊤V^{\top}:

Ak=U:,1:k Σ1:k V1:k,:⊤A_k = U_{:,1:k}\, \Sigma_{1:k}\, V^{\top}_{1:k,:}

Reconstruct with k=7k = 7 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 kk 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 kk from 1 to 60 and score each on the held-out set.

Line chart of held-out RMSE against rank k from 1 to 60. The truncated SVD curve starts near 4.33, drops to a minimum of 4.04 at k=7, then rises steadily, crossing back above the user+item bias baseline of 4.37 around k=48. Dotted horizontal lines mark the global-mean (5.18), item-mean (4.97) and user+item bias (4.37) baselines, all above the SVD minimum.

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.

Bar chart of the first 50 singular values with a black line for cumulative variance explained. The first singular value is much larger than the rest, then the values decay slowly into a long tail. A red dashed line marks the best predictive rank at 7, annotated to note that rank 7 keeps only 33% of the variance yet predicts best.

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-kk reconstruction is the best possible rank-kk 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 VV are the principal components and σi2\sigma_i^2 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

Scatter plot of the two-dimensional Iris projection with the three species in different colours. Open black circles for the SVD scores sit exactly on top of the filled PCA points, showing the two projections are identical to a maximum difference of 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

Scatter of five words in a two-dimensional latent space from the SVD of a word-document matrix. Doctor, nurse and hospital cluster tightly along one axis (the medical topic) while car and wheel sit on the orthogonal axis (the vehicle topic), with no labels provided to the algorithm.

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, r^ui=μ+bu+bi+pu⊤qi\hat r_{ui} = \mu + b_u + b_i + p_u^{\top} q_i, but fits the factors pup_u and qiq_i 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 BB of rank at most kk, the one closest to AA in Frobenius (and spectral) norm is exactly Ak=U:,1:k Σ1:k V1:k,:⊤A_k = U_{:,1:k}\,\Sigma_{1:k}\,V^{\top}_{1:k,:}, and the error is set by the singular values you dropped:

min⁡rank⁡(B)≤k∥A−B∥F2=∑i>kσi2\min_{\operatorname{rank}(B) \le k} \lVert A - B \rVert_F^2 = \sum_{i > k} \sigma_i^2

That is why keeping the largest singular values is optimal, not just reasonable. The connection to eigenvalues comes from A⊤A=VΣ2V⊤A^{\top}A = V\Sigma^2 V^{\top}: the right singular vectors are eigenvectors of A⊤AA^{\top}A 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 UU, Σ\Sigma, and VV transform space and how singular values scale each direction.
  • Overfitting Explorer: Feel the underfit-to-overfit trade-off that the rank kk controls in the RMSE curve above.

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions