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
- Builds on
- 6 concepts →
- Quiz
- 5 questions ↓
This leads to
—The full path from zero — 6 concepts before this one
- What Is AI?
- Vectors
- How Machines Learn
- Matrices and Matrix Multiplication
- Supervised, Unsupervised and Reinforcement Learning
- Supervised Learning
- 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 will like item . 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.
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 , so his centred ratings are . 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 | |
| Cat | −0.79 | |
| Dan | −1.00 |
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:
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: . Both methods agree that Bob will like it.
Matrix factorisation
Write the user–item matrix as , with users and items, mostly unknown. Matrix factorisation approximates it as the product of two thin Matrices and Matrix Multiplication:
has one row of factors for each user; has one row for each item. Typically 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 and bias terms that capture "this user rates everything high" and "this film is generally loved":
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:
Two standard ways to solve it:
- Stochastic gradient descent: loop over known ratings, compute the error, nudge and towards reducing it. Simple and flexible (the code below).
- Alternating least squares (ALS): fix and solve exactly for every (a small Linear Regression per user), then fix and solve for , 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 and 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.
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:
- 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.
- 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).
- 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 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
- Embeddings and vector search are the backbone of retrieval. See Vector Databases and Embeddings and Semantic Search.
- Learning to rank with gradient-boosted trees or deep networks orders candidates. See Gradient Boosting: XGBoost and LightGBM.
- Sequence models: The Transformer-based recommenders treat a user's history as a sentence of item IDs and predict the next "word".
- LLM-powered recommendations: Large language models can describe items, explain recommendations and handle conversational requests ("something like Alien but funnier").
- Reinforcement learning frames recommendation as a sequence of decisions with long-term reward. See Reinforcement Learning: The Basics.
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
- 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?
- In the matrix factorisation code, set
reg = 0and run it. What happens to the train and test RMSE? Then tryk = 10.- 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 and Love Actually is .
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Recommendation Systems course
Candidate generation, matrix factorisation, two-tower deep models and re-ranking, in a few short lessons.
Mining of Massive Datasets
The Stanford book behind CS246. Its chapters on recommender systems, clustering and dimensionality reduction are excellent and free.
Matrix Factorization Techniques for Recommender Systems
A readable summary of the latent-factor methods that won the Netflix Prize.
Machine Learning Specialization
The best-known first course in ML. Covers regression, classification, neural nets, trees, clustering, recommenders and RL with Python labs.
Designing Machine Learning Systems
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