◆ AI All-in-One

Level 3 In-Depth AI · Classical Machine Learning

Recommender Systems

How Netflix, Spotify, Amazon and YouTube decide what to show you. Learn from what millions of people did to predict what you will like, using similarity, matrix factorisation and two-tower neural networks.

Level
●●●●● Easy
Reading
14 min
To learn it well
1 hour to read, an afternoon to practise
↗ Plan a path here

Read first

Matrices and Matrix MultiplicationSupervised Learning

This leads to

—
The full path from zero — 6 concepts before this one
  1. What Is AI?
  2. Vectors
  3. How Machines Learn
  4. Matrices and Matrix Multiplication
  5. Supervised, Unsupervised and Reinforcement Learning
  6. Supervised Learning
  7. Recommender Systems

Read them roughly in this order. See it on the concept map →

Why it matters

Netflix has thousands of titles, Spotify about 100 million tracks, YouTube billions of videos. Nobody can browse them all. A recommender system chooses the handful each person sees: the "Because you watched…" row, the Discover Weekly playlist, the next video that starts playing, the "customers also bought" strip.

Recommenders are probably the most commercially important application of machine learning. They decide what billions of people read, watch, listen to and buy. A large share of viewing on Netflix and YouTube is driven by recommendations, according to both companies, and the same machinery ranks social media feeds, job listings, dating profiles and ads.

The core problem looks like Supervised Learning: predict how much user uu will like item ii. But it has its own character:

  • The data is a huge, mostly empty user–item matrix: each user has interacted with a tiny fraction of the items.
  • The strongest signal isn't the items' descriptions but what other people did.
  • New users and new items arrive constantly with no history (the cold start problem).
  • At serving time you must pick the best 10 items out of millions in a few milliseconds.

The intuition

Before algorithms, people asked friends with similar taste. If you and a friend both loved the same five films, and she has just raved about a sixth you haven't seen, you'll probably like it too. You don't need to know why it's good. Your shared history is enough.

That is collaborative filtering: recommend using the behaviour of people similar to you. Its sibling, content-based filtering, uses the items' own properties instead: you liked three science-fiction films with spaceships, so here is another with spaceships.

Matrix factorisation, the idea that won the Netflix Prize, combines these intuitions. It assumes every user and every item can be described by a short list of hidden "taste" numbers, called latent factors, such as how much a film is sci-fi or romance, and how much each user enjoys sci-fi or romance. The predicted rating is how well the two lists line up.

Ratings R 4 users × 4 films, ? = unknown Alien Termin. Notting Love A. Ann 5 4 1 ? → 1.1 Bob 4 ? → 3.4 2 1 Cat 1 1 5 4 Dan ? → 1.8 2 4 5 ≈ User factors U taste for sci-fi, romance sci-fi romance 2.2 0.3 1.8 0.4 0.4 2.2 0.6 2.2 × Film factors Vᵀ how sci-fi / romantic each film is Alien Term. Nott. Love 2.2 1.8 0.4 0.2 0.2 0.3 2.2 2.2 Each predicted rating is a dot product: Bob's tastes · Terminator's traits (1.8 × 1.8) + (0.4 × 0.3) = 3.24 + 0.12 = 3.4 → Bob will probably like Terminator Training finds U and V so that the known ratings (blue) are matched; the unknown ones (orange) are then filled in. Real systems learn 32–256 factors with no names, for millions of users and items.
Fig. 1 Matrix factorisation of a small ratings table. The ratings matrix R is approximated by multiplying a user-factor matrix U (each user's taste for sci-fi and romance) by a film-factor matrix (each film's sci-fi and romance content). Each predicted rating is a dot product. The unknown cells are filled in: Bob is predicted to rate Terminator 3.4. Real systems learn the factors from data and they rarely have clean names.

Key idea Recommenders predict what a user will like from patterns in what many users did. The workhorse idea: represent every user and item as a vector of latent factors, learned from the data, and score a user–item pair by the dot product of their vectors.

How it works

The data: explicit and implicit feedback

  • Explicit feedback is a rating the user deliberately gave: 4 stars, thumbs up. It is clear but rare; most people never rate anything.
  • Implicit feedback is behaviour: clicks, purchases, plays, watch time, skips. It is plentiful but noisy, and it has only positives. A film you didn't watch might be one you'd hate, or one you've never noticed.

Most modern systems run mainly on implicit feedback. That changes the maths: instead of predicting a rating, you predict the probability of interaction, and you must treat the empty cells carefully (they aren't all "dislikes").

Neighbourhood collaborative filtering

The oldest approach compares rows or columns of the user–item matrix.

User-based: find users whose ratings correlate with yours and take a similarity-weighted average of their ratings of the target item. Item-based: find items rated similarly to the target item by the same people, and look at how you rated those. Item-based filtering, popularised by Amazon in 2003, is usually more stable because item similarities change slowly, and it can be precomputed.

Similarity is typically the cosine similarity of two vectors of ratings, often after subtracting each user's average rating (to correct for generous and stingy raters, which makes it Pearson correlation).

A worked example by hand

Four users have rated four films from 1 to 5:

Alien Terminator Notting Hill Love Actually
Ann 5 4 1 ?
Bob 4 ? 2 1
Cat 1 1 5 4
Dan ? 2 4 5

Will Bob like Terminator?

User-based collaborative filtering. First subtract each user's average from their ratings. Bob's average is (4+2+1)/3=2.33(4 + 2 + 1)/3 = 2.33, so his centred ratings are +1.67,−0.33,−1.33+1.67, -0.33, -1.33. Ann's average is 3.33; Cat's 2.75; Dan's 3.67.

Next, the similarity between Bob and each other user, as the cosine of their centred ratings on the films both rated:

Similarity to Bob Their centred rating of Terminator
Ann +0.73 4−3.33=+0.674 - 3.33 = +0.67
Cat −0.79 1−2.75=−1.751 - 2.75 = -1.75
Dan −1.00 2−3.67=−1.672 - 3.67 = -1.67

Ann has similar taste; Cat and Dan have opposite taste. Predict Bob's rating as his average plus a similarity-weighted average of their deviations:

r^=2.33+(0.73)(0.67)+(−0.79)(−1.75)+(−1.00)(−1.67)0.73+0.79+1.00=2.33+3.542.52=3.74\hat{r} = 2.33 + \frac{(0.73)(0.67) + (-0.79)(-1.75) + (-1.00)(-1.67)}{0.73 + 0.79 + 1.00} = 2.33 + \frac{3.54}{2.52} = 3.74

Ann liked it, and the people who disagree with Bob didn't, so Bob probably will: about 3.7 stars.

Matrix factorisation. In the figure, Bob's factors are (sci-fi 1.8, romance 0.4) and Terminator's are (1.8, 0.3). The prediction is the dot product: 1.8×1.8+0.4×0.3=3.24+0.12=3.41.8 \times 1.8 + 0.4 \times 0.3 = 3.24 + 0.12 = 3.4. Both methods agree that Bob will like it.

Matrix factorisation

Write the user–item matrix as R\mathbf{R}, with mm users and nn items, mostly unknown. Matrix factorisation approximates it as the product of two thin Matrices and Matrix Multiplication:

R≈P Q⊤\mathbf{R} \approx \mathbf{P}\,\mathbf{Q}^\top

P\mathbf{P} has one row pu\mathbf{p}_u of kk factors for each user; Q\mathbf{Q} has one row qi\mathbf{q}_i for each item. Typically kk is 20 to 200, far smaller than the number of users or items. The predicted rating is a dot product, usually plus a global average μ\mu and bias terms that capture "this user rates everything high" and "this film is generally loved":

r^ui=μ+bu+bi+pu⋅qi\hat{r}_{ui} = \mu + b_u + b_i + \mathbf{p}_u \cdot \mathbf{q}_i

The factors are learned by minimising squared error over the known ratings only, with an L2 penalty (Regularization: L1 and L2) to stop the factors overfitting the few ratings each user has:

min⁡∑(u,i) known(rui−r^ui)2+λ(∥pu∥2+∥qi∥2+bu2+bi2)\min \sum_{(u,i)\ \text{known}} \left(r_{ui} - \hat{r}_{ui}\right)^2 + \lambda \left( \lVert \mathbf{p}_u \rVert^2 + \lVert \mathbf{q}_i \rVert^2 + b_u^2 + b_i^2 \right)

Two standard ways to solve it:

  • Stochastic gradient descent: loop over known ratings, compute the error, nudge pu\mathbf{p}_u and qi\mathbf{q}_i towards reducing it. Simple and flexible (the code below).
  • Alternating least squares (ALS): fix Q\mathbf{Q} and solve exactly for every pu\mathbf{p}_u (a small Linear Regression per user), then fix P\mathbf{P} and solve for Q\mathbf{Q}, and alternate. Easy to parallelise, and the standard method for implicit feedback.

This is closely related to the singular value decomposition and to PCA and Dimensionality Reduction: both find the best low-rank approximation of a matrix. The difference is that a recommender's matrix is mostly missing, not zero, so it fits only the known entries.

The learned factors often turn out to be interpretable directions (action versus drama, mainstream versus art-house), though nobody told the model about genres. Users and items live in the same "taste space", so you can also find similar items as nearest neighbours of each other's vectors.

Content-based and hybrid models

Collaborative filtering can't recommend a brand-new item nobody has interacted with, or serve a brand-new user. That is the cold start problem. Content-based methods describe items by their features (genre, text, audio, images, often as embeddings) and users by the features of items they liked, so a new item can be recommended from day one. In practice, systems are hybrids: they combine interaction data with content features and context (time of day, device, location).

Two-tower models

The modern, scalable version of matrix factorisation replaces the lookup tables P\mathbf{P} and Q\mathbf{Q} with Neural Networks. A two-tower model has a user tower that turns everything known about the user (history, demographics, context) into a vector, and an item tower that turns the item's ID and features into a vector of the same size. The score is the dot product of the two vectors.

User features history, location, time Item features title, genre, text, image User tower neural network Item tower neural network user vector u e.g. 128 numbers item vector v e.g. 128 numbers score = u · v high = likely to engage A production pipeline Candidate retrieval millions → ~1,000 nearest item vectors to u Ranking ~1,000 → ~100 bigger model, many features Re-ranking ~100 → 10 shown diversity, freshness, rules item vectors are precomputed and kept in a vector index, so retrieval is a fast nearest-neighbour search
Fig. 2 Left: a two-tower model. A user tower and an item tower, both neural networks, map their inputs to vectors of the same length, and the score is their dot product. Right: a typical production pipeline. A fast retrieval stage narrows millions of items to about a thousand candidates, a heavier ranking model orders them, and a re-ranking step applies business rules and diversity before about ten items are shown.

Because the score is a dot product, you can compute every item's vector in advance and store them in a vector index. At request time, you run the user tower once and look up the nearest item vectors with approximate nearest-neighbour search (k-Nearest Neighbours). This is candidate retrieval: millions of items narrowed to a few hundred in milliseconds. Towers are usually trained on implicit feedback with a contrastive loss: each user's real interaction should score higher than other items in the batch.

The full pipeline

Large systems work in stages, from cheap and broad to expensive and precise:

  1. Retrieval (candidate generation): several fast sources, such as two-tower nearest neighbours, "similar to what you just watched", trending and new items, produce a few thousand candidates.
  2. Ranking: a richer model scores each candidate using many features, including cross-features between user and item that a two-tower model can't use. Often gradient-boosted trees or a deep network, predicting several outcomes at once (click, watch time, like).
  3. Re-ranking: adjust the final list for diversity, freshness, fairness, already-seen items and business rules.

Evaluating recommenders

  • Rating prediction: root mean squared error (RMSE) on held-out ratings. The Netflix Prize used this, but users never see a rating prediction, they see a ranked list.
  • Ranking metrics: of the top kk items shown, how many did the user actually interact with later (precision@k, recall@k), and how high up were they (NDCG, MAP)?
  • Split by time, not at random: train on the past, test on the future, as in Time Series Forecasting. A random split lets the model peek at the future.
  • Online A/B tests: the final judge. Offline metrics often disagree with what users do when the system changes.

In code

Matrix factorisation with biases from scratch, trained by stochastic gradient descent. The data is synthetic: 300 users and 200 films whose true ratings come from 3 hidden factors, plus noise. Each user has rated about 15% of the films, and 20% of the known ratings are held out for testing.

import numpy as np

# Synthetic ratings: 300 users x 200 films, generated from 3 hidden "taste" factors
rng = np.random.default_rng(0)
n_users, n_items, k_true = 300, 200, 3
U_true = rng.normal(0, 1, (n_users, k_true))
V_true = rng.normal(0, 1, (n_items, k_true))
full = 3 + U_true @ V_true.T * 0.6 + rng.normal(0, 0.3, (n_users, n_items))
mask = rng.random((n_users, n_items)) < 0.15              # each user rated about 15% of films
users, items = np.nonzero(mask)
ratings = full[users, items]
test = rng.random(len(ratings)) < 0.2                     # hold out 20% of the known ratings

k, lr, reg = 3, 0.05, 0.1                                 # factors, learning rate, L2 penalty
P = rng.normal(0, 0.1, (n_users, k))                      # user factors
Q = rng.normal(0, 0.1, (n_items, k))                      # item factors
mu = ratings[~test].mean()                                # global average rating
bu, bi = np.zeros(n_users), np.zeros(n_items)             # user and item biases

def rmse(sel):
    pred = mu + bu[users[sel]] + bi[items[sel]] + (P[users[sel]] * Q[items[sel]]).sum(1)
    return np.sqrt(np.mean((ratings[sel] - pred) ** 2))

print(f"predict the average  : test RMSE {np.sqrt(np.mean((ratings[test] - mu) ** 2)):.3f}")
train_idx = np.flatnonzero(~test)
for epoch in range(1, 41):
    for n in rng.permutation(train_idx):                  # stochastic gradient descent, one rating at a time
        u, i = users[n], items[n]
        err = ratings[n] - (mu + bu[u] + bi[i] + P[u] @ Q[i])
        bu[u] += lr * (err - reg * bu[u])
        bi[i] += lr * (err - reg * bi[i])
        P[u], Q[i] = P[u] + lr * (err * Q[i] - reg * P[u]), Q[i] + lr * (err * P[u] - reg * Q[i])
    if epoch in (1, 10, 40):
        print(f"epoch {epoch:2d}  train RMSE {rmse(~test):.3f}   test RMSE {rmse(test):.3f}")

# predict the average  : test RMSE 1.065
# epoch  1  train RMSE 1.038   test RMSE 1.067
# epoch 10  train RMSE 0.411   test RMSE 0.551
# epoch 40  train RMSE 0.312   test RMSE 0.413

The test error falls from 1.07 (always predicting the average) to 0.41, close to the 0.3 noise we added. For implicit feedback, here is item-based collaborative filtering on a tiny "who watched what" matrix, using scikit-learn's cosine similarity:

import numpy as np
from sklearn.metrics.pairwise import cosine_similarity

films = ["Alien", "Terminator", "Notting Hill", "Love Actually", "Blade Runner"]
# Implicit feedback: 1 = the user watched the film to the end, 0 = no signal
watched = np.array([
    [1, 1, 0, 0, 1],
    [1, 1, 0, 0, 0],
    [0, 0, 1, 1, 0],
    [0, 1, 1, 1, 0],
    [1, 0, 0, 0, 1],
])
item_sim = cosine_similarity(watched.T)              # film-to-film similarity from co-watching
np.fill_diagonal(item_sim, 0)

user = watched[1]                                    # this user watched Alien and Terminator
scores = item_sim @ user                             # sum of similarities to what they watched
scores[user == 1] = -np.inf                          # don't recommend what they've already seen
for i in np.argsort(scores)[::-1][:2]:
    print(f"{films[i]:14} score {scores[i]:.2f}")

# Blade Runner   score 1.22
# Love Actually  score 0.41

For real projects, libraries such as implicit (ALS for implicit feedback), LightFM (hybrid), and TensorFlow Recommenders or TorchRec (two-tower and ranking models) save a lot of work.

Common pitfalls

  • Random train/test splits. They leak the future: the model learns from interactions that happened after the ones it is tested on. Split by time.
  • Treating missing as negative. In implicit data an unclicked item is mostly unseen, not disliked. Weight observed and unobserved entries differently, or sample negatives carefully.
  • Popularity bias. Models trained on interactions recommend what is already popular, which gets more interactions, which makes it more popular. Measure coverage and diversity, not just accuracy.
  • Feedback loops. The system only learns about items it showed. Items it never shows never get the data to prove themselves. Reserve some traffic for exploration.
  • Optimising the wrong target. Maximising clicks rewards clickbait; maximising watch time can reward outrage. Choose objectives that reflect long-term satisfaction, and watch for harms (see Bias and Fairness).
  • Ignoring cold start. A model with only ID embeddings has nothing for new users and items. Add content features and sensible fallbacks.

Watch out Offline accuracy is a weak guide for recommenders. A model can score better on held-out clicks and still make the product worse, for example by narrowing what users see. Always confirm with an online A/B test, and track diversity and long-term engagement as well as clicks.

Where it leads

A bit of history

The term collaborative filtering comes from Tapestry, an email-filtering system built at Xerox PARC in 1992. The GroupLens project (1994) automated it, recommending Usenet news articles from the ratings of similar users. Amazon described its item-to-item collaborative filtering in 2003, a design that scaled to millions of customers and products.

The Netflix Prize (2006–2009) offered $1 million to anyone who could improve Netflix's rating-prediction RMSE by 10%. Early in the contest, Simon Funk's blog post on training matrix factorisation by gradient descent showed how powerful latent factors were, and the winning team, BellKor's Pragmatic Chaos, blended hundreds of models built mostly around factorisation. Koren, Bell and Volinsky summarised the approach in their 2009 article. Hu, Koren and Volinsky adapted it to implicit feedback in 2008. In 2016 Google described YouTube's two-stage deep recommender (candidate generation, then ranking), and two-tower retrieval models with neural ranking became the standard industrial design.

Try it

  1. In the hand example, predict Ann's rating for Love Actually with the factors in the figure. Does it agree with what you'd guess from the table?
  2. In the matrix factorisation code, set reg = 0 and run it. What happens to the train and test RMSE? Then try k = 10.
  3. Harder: add a time split to the item-based example: hide each user's last watch, recommend from the rest, and measure how often the hidden film is in the top 2 (this is recall@2).

Hint for 1: Ann is (2.2,0.3)(2.2, 0.3) and Love Actually is (0.2,2.2)(0.2, 2.2).

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. A brand-new film has no views or ratings yet. Which approach can still recommend it?

  2. In implicit feedback (clicks, plays), what should you assume about an item a user never clicked?

  3. Bob's latent factors are (1.8, 0.4) and Terminator's are (1.8, 0.3). What rating does matrix factorisation predict (ignoring biases)?

  4. Why can a two-tower model pick a few hundred candidates from millions of items in milliseconds?

  5. A new recommender beats the old one on held-out clicks offline. What should you do before declaring victory?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Course

Recommendation Systems course

Google · Beginner · Free

Candidate generation, matrix factorisation, two-tower deep models and re-ranking, in a few short lessons.

Book

Mining of Massive Datasets

Leskovec, Rajaraman & Ullman · Intermediate · Free

The Stanford book behind CS246. Its chapters on recommender systems, clustering and dimensionality reduction are excellent and free.

Course

Machine Learning Specialization

Andrew Ng (DeepLearning.AI & Stanford) · Beginner · free to audit

The best-known first course in ML. Covers regression, classification, neural nets, trees, clustering, recommenders and RL with Python labs.

Book

Designing Machine Learning Systems

Chip Huyen · 2022 · Intermediate · Paid

The practical guide to data, features, deployment, monitoring and iteration in production ML.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/ml/recommender-systems.md