Recommender Systems

Eight people, eight films, and we know only 40 of the 64 ratings. From that pattern alone, matrix factorization guesses the 24 missing ratings with an average error of 0.44 stars. Showing everyone the most popular films misses by 1.13.

Pick a predictor and watch it fill the blank cells. Then turn on Truth to see how close it came. Then we build, piece by piece, the neighbour method, matrix factorization, the two-tower model, the ranking funnel and the metrics that score it.

You need a little Python, what an average is and what a vector is. We build the rest from zero.

The 8 × 8 rating matrix is a toy made for this page. Every predictor runs live in your browser, and a short numpy script checked every number in the text.

Fill the empty matrix

Illustrative toy: ratings from 1 to 5 stars, made from two tastes (action and romance) plus small per-person and per-film offsets. Error is the root mean square error (RMSE) on the 24 hidden cells.

Chapter 0

The Empty Matrix

See why a recommender must guess, and why the popular list is a weak guess

You open a film app. It has 17,770 films and you have rated 40 of them. The app must choose ten to show you. Most of the films it picks from, you have never touched.

Write every person as a row and every item as a column. Put a rating in a cell when the person rated the item. This is the rating matrix. A recommender system is a program that guesses the blank cells and shows each person the items with the highest guesses.

The hard part is how blank the matrix is. Call the share of filled cells the density: filled cells divided by people times items. The Netflix Prize data had 100,480,507 ratings from 480,189 people on 17,770 films. That is 100,480,507 / (480,189 × 17,770) = 1.18%. So 98.8 of every 100 cells are blank.

See how empty real data is

Each square is one person and one item. Filled squares are ratings. Pick a dataset and count the filled squares.

Densities: MovieLens 100K has 100,000 ratings from 943 people on 1,682 films; the Netflix Prize training set has 100,480,507 ratings from 480,189 people on 17,770 films. The position of each filled square is random; only the share is real.

The first guess anyone tries is the popularity baseline: predict every blank cell with that item's average rating. It is cheap and it is a fair yardstick. But it gives everyone the same list. In the hero, it misses by 1.13 stars, because the action fans and the romance fans want opposite films.

The fix is personalization: use the pattern of what you rated, and what people like you rated, to guess your blanks. The whole lesson is ways to do that cheaply, at the scale of millions of items.

The failure, as symptom, measurement and fix

Symptom: every user sees the same top ten. Measurement: count how many distinct items appear across all users' top ten lists; a popularity system shows only ten. Fix: a personal model, which the next chapters build.

The road

  1. Neighbours: find people who rate like you and borrow their ratings.
  2. Matrix factorization: give every person and every item a short vector.
  3. Training the factors: fit the vectors, and stop them from memorizing.
  4. Two towers: compute the vectors from features, and train with in-batch negatives.
  5. Retrieve, then rank: a cheap model narrows millions, a heavy model orders hundreds.
  6. The ranker: DLRM, embedding tables and feature crosses.
  7. Scoring a ranked list: recall@k, average precision and NDCG.
  8. Recommending, live: the whole pipeline on one map, with diversity.
  9. Hard problems: cold start, exploration and the feedback loop.
  10. Field guide: terms, numbers, code and where to go next.
A matrix has 1,000 users, 2,000 items and 40,000 ratings. What is its density, and what does a recommender do with it?

Chapter 1

Neighbours: People Who Rate Like You

Measure how alike two people rate, then borrow the ratings of your closest matches

Ana has not rated the film Ripcord. Ben and Cy rated it 4 and 5, and on the films they share with Ana, they rate as she does. So Ana will probably like it.

This is collaborative filtering: predict from the pattern of who rated what, with no facts about the items. The neighbour version scores how alike two people are, then averages the neighbours' ratings by that score.

Step 1: how alike are two people?

Ana gives 2.4 stars on average and Cy gives 3.4. So first subtract each person's own average. Call user u's rating of item i minus u's average the centred rating xui. Compare two users only on the items both rated. The score is the cosine similarity of their centred ratings.

Say it aloud

Sim of u and v equals the sum over shared items i of x-u-i times x-v-i, divided by the root of the sum of x-u-i squared times the root of the sum of x-v-i squared.

sim(u, v)
sim of u and v how alike users u and v rate, from −1 (opposite) to +1 (the same).
Σi
the sum over i add one term for each item that both users rated.
xui
x-u-i user u's rating of item i minus u's own average rating.
xvi
x-v-i the same for user v.
√Σ x2
the root of the sum of squares the length of each user's centred vector; it keeps the score between −1 and +1.
In plain words

Multiply u's and v's centred ratings item by item, add them, and divide by both lengths. Same signs push sim(u, v) up.

With numbers

Ana and Ben share two films. Ana's centred ratings are 1.6 and −0.4; Ben's are 1.2 and −0.8. The sum is 1.6 × 1.2 + 0.4 × 0.8 = 2.24. The lengths are 1.649 and 1.442. So sim = 2.24 / 2.378 = 0.94.

Step 2: borrow the neighbours' ratings

Call the K most similar users who rated item i the set N, and user u's average r̄u.

Say it aloud

R-hat-u-i equals r-bar-u plus the sum over neighbours v of sim of u and v times r-v-i minus r-bar-v, divided by the sum over neighbours of the size of sim of u and v.

r̂ui
r-hat-u-i the predicted rating of user u for item i.
r̄u
r-bar-u user u's average rating: the starting point.
Σv∈N
the sum over v in N add one term for each of the K nearest neighbours who rated item i.
sim(u, v)
sim of u and v the weight: closer neighbours count more.
rvi − r̄v
r-v-i minus r-bar-v how far above or below their own average neighbour v rated item i.
Σ |sim|
the sum of the sizes of sim divides by the total weight, so the result is a weighted average.
In plain words

Take how far each neighbour v rated item i above their own average. Average those, weighted by sim(u, v), and add r-bar-u.

With numbers

Ana's average is 2.4. Ben (sim 0.94, average 2.8) gave Ripcord 4; Cy (sim 0.93, average 3.4) gave 5. r̂ = 2.4 + (0.94 × 1.2 + 0.93 × 1.6) / (0.94 + 0.93) = 2.4 + 1.40 = 3.80. Ana's hidden true rating is 4.

Borrow from your neighbours

Pick a person and one of their blank films. The bars are each other person's similarity. Change K, the number of neighbours used.

Same toy matrix as the hero. The method uses only neighbours who rated the film and have a positive similarity. Several similarities rest on two or three shared films, so they are noisy.

The failure, as symptom, measurement and fix

Symptom: odd neighbours. Ana and Ben score 0.94 from only two shared films. Measurement: log how many shared items each similarity uses. Fix: require a minimum overlap, or use a model that pools all the data (next chapter).

Why does the neighbour method subtract each person's average before it compares two people?

Chapter 2

Matrix Factorization: A Vector for Everyone

Describe each person and each item with a few numbers, and predict a rating with one dot product

Suppose each film has two hidden amounts: how much action it has and how much romance. Suppose each person has two hidden weights: how much they like action and how much they like romance. Multiply the matching pairs and add. You get a guess of how much this person likes this film.

This is matrix factorization. Give every user a short vector pu and every item a short vector qi, each with k numbers. The numbers are latent factors: traits the model finds by itself. Nobody labels them "action". The 8 × 8 matrix becomes 8 user vectors and 8 item vectors.

Some people rate everything high, and everyone rates some films high. So the prediction also has three offsets. Call the average of all ratings μ, user u's offset bu and item i's offset bi.

Say it aloud

R-hat-u-i equals mu plus b-u plus b-i plus p-u dot q-i.

r̂ui
r-hat-u-i the predicted rating of user u for item i, in stars.
μ
mu the average of every known rating. 2.95 in our toy.
bu
b-u the user bias: how much higher than average user u rates everything.
bi
b-i the item bias: how much higher than average everyone rates item i.
pu
p-u the user vector: k numbers, one weight per hidden trait.
·
dot the dot product: multiply matching entries and add them up.
qi
q-i the item vector: k numbers, how much of each trait item i has.
In plain words

Start from the global average mu. Add the user bias b-u and the item bias b-i. Then add the match between taste and traits: p-u dot q-i.

With numbers

With made-up numbers: μ = 3, bu = 0.2, user pu = (1.5, −1.0). Ripcord: bi = 0.3, qi = (0.9, 0.1), so r̂ = 3 + 0.2 + 0.3 + (1.35 − 0.10) = 4.75. Petals: bi = 0.1, qi = (0.1, 0.9), so r̂ = 3.3 + (0.15 − 0.90) = 2.55.

Steer one person's taste

The teal arrow is the user vector. The orange dots are films. Drag the two sliders and watch the predicted ratings reorder.

1.5
−1.0

Illustrative vectors with k = 2 and μ = 3, bu = 0.2. Learned factors have no names; here the two axes are named so you can read them.

Why is this better than neighbours? Every rating trains the shared vectors. Ana and Ben need not share any film: if both rated films with high action, their vectors both point toward action. The model pools all the data. It also stores little: 8 + 8 vectors of k numbers, against 64 cells. For 480,189 people and 17,770 films with k = 50, that is about 25 million numbers instead of 8.5 billion cells.

The failure, as symptom, measurement and fix

Symptom: everyone gets the same top items. Measurement: check the item biases bi; if a few are large and k is tiny, the bias term drowns the dot product. Fix: raise k, or regularize the biases, which Chapter 3 does.

μ = 3, bu = −0.5, bi = 0.5, pu = (1, 1), qi = (0.5, 0.5). What is the predicted rating?

Chapter 3

Training the Factors

Fit the vectors to the known ratings, and add a penalty so they predict the unknown ones

Nobody hands you pu and qi. You start them small and nudge them until they fit the known ratings, by shrinking one number: the loss.

Call the set of known (user, item) cells K. For each one, the error is the true rating rui minus the prediction r̂ui. A penalty with strength λ keeps the vectors short, so they cannot memorize the 40 known cells.

Say it aloud

L equals the sum over known cells u, i of r-u-i minus r-hat-u-i, squared, plus lambda times the squared length of p-u plus the squared length of q-i plus b-u squared plus b-i squared.

L
L the loss: one number that training makes small.
Σ(u,i)∈K
the sum over known cells add one term per known rating. Blank cells add nothing.
rui
r-u-i the true rating user u gave item i.
r̂ui
r-hat-u-i the model's prediction from Chapter 2.
λ
lambda the regularization strength: how hard to pull every vector toward zero.
‖p‖2 + …
the squared length of p-u, and so on the sum of the squares of every number in the vectors and the biases.
In plain words

For every known cell, square the miss r-u-i minus r-hat-u-i and add them up. Add lambda times the size of all the vectors. Small L means a good fit with short vectors.

With numbers

With made-up numbers: one known cell, r = 4, prediction 3.5, so the miss term is 0.25. The vectors hold the numbers 1, −1, 0.5 and 0.5, so their size is 2.5. With λ = 0.1, L = 0.25 + 0.25 = 0.50.

Gradient descent makes L small: compute the error e = r − r̂ on each known cell, then move each vector a small step that shrinks L. With step size 0.03, e = 0.5, pu = (1, −1), qi = (0.5, 0.5) and λ = 0.1: qi moves by 0.03 × (0.5 × (1, −1) − 0.1 × (0.5, 0.5)) = (0.0135, −0.0165). The device runs 3,000 such steps on all 40 known cells at once.

Train it and watch two errors

Purple is the error on the 40 known ratings. Blue is the error on the 24 hidden ones. Pick k and λ, then press Train.

0

Full-batch gradient descent, step 0.03, 3,000 steps, fixed starting vectors, on the hero's toy matrix. The device clips predictions to 1 to 5 stars before it measures the hidden error.

With k = 2 and no penalty, the known error falls to 0.00 and the hidden error is 0.86: the vectors memorized the 40 cells. With λ = 0.3 the known error is 0.12 and the hidden error drops to 0.44. With λ = 10 both are about 1.1: the penalty crushes the vectors and the model barely beats popularity.

Biases plus factors plus a penalty was a core part of the Netflix Prize. Netflix's Cinematch scored a test RMSE of 0.9525. The 2009 winners, BellKor's Pragmatic Chaos, reached 0.8567, a 10.06% cut, with a blend of factorization and neighbour models.

The failure, as symptom, measurement and fix

Symptom: training error near zero, but users see poor picks. Measurement: hold out some known ratings and track their error; a gap between the two curves is overfitting. Fix: raise λ until the held-out error stops falling.

Known error 0.00, hidden error 0.86. What should you change?

Chapter 4

Two Towers: Vectors From Features

Compute the user and item vectors with two networks, and train them by picking the right item out of a batch

A new film arrives today. Nobody has rated it, so matrix factorization has no vector for it. But you know its genre, cast and description. Could a network turn those facts into qi?

That is the two-tower model (a dual encoder). The user tower maps a user's features (recent watches, searches, device) to a user vector. The item tower maps an item's features to an item vector of the same length. The score is their dot product. Matrix factorization is the case where each tower is a lookup table keyed by ID.

The towers never see each other's input, so item vectors do not depend on the user. Compute them once and store them. At request time, run only the user tower and search the stored vectors.

Training with in-batch negatives

The logs say which item each user picked, not what they disliked. So take a batch of B (user, picked item) pairs and treat the other users' items as the wrong answers for each user. Call the dot product of user u and item j suj, and user u's picked item i.

Say it aloud

L-u equals minus the log of e to the s-u-i, divided by the sum over j in the batch of e to the s-u-j.

Lu
L-u the loss for user u. The batch loss is the average over the B users.
−log
minus log near 0 when the probability is near 1, large when it is near 0.
esui
e to the s-u-i the exponential of the score of the item user u picked.
Σj∈B
the sum over j in the batch add one term for each of the B items in the batch, the picked one included.
esuj
e to the s-u-j the exponential of the score of item j. s-u-j is the user vector dot the item vector.
In plain words

Score user u against every item in the batch. The softmax turns scores into probabilities: e to each score, over the total. L-u is minus the log of the picked item's probability.

With numbers

With made-up numbers: B = 4 and user u's scores are 2.0 (picked), 0.5, −0.5 and 0.0. The exponentials 7.39, 1.65, 0.61 and 1.00 add to 10.64. The picked item's probability is 7.39 / 10.64 = 0.69, so Lu = −log 0.69 = 0.37. A blind guess gives log 4 = 1.39.

Train four users against four items

Left: user vectors (teal) and item vectors (orange); a line joins each user to the item they picked. Right: each row is one user's softmax over the batch. Press Train and watch the diagonal light up.

Illustrative: 2-number vectors, plain dot-product scores, gradient descent with step 0.3 on the batch loss. Real towers are deep networks with vectors of 32 to 256 numbers.

YouTube's 2016 candidate model treats the next watch as a choice among millions of videos. It samples several thousand wrong videos per example, more than 100 times faster than a full softmax. In-batch negatives are a cheaper version of the same idea.

The failure, as symptom, measurement and fix

Symptom: in-batch negatives over-sample popular items, so the model pushes them down. Measurement: compare each item's rate as a negative with its rate as a pick. Fix: subtract the log of its sampling frequency from its training score.

Why can a two-tower model store item vectors ahead of time?

Chapter 5

Retrieve, Then Rank

Split the work into a cheap pass over everything and a careful pass over a few hundred

You have a careful model that scores one (user, item) pair in 20 microseconds. The catalogue has 10 million items. Scoring all of them for one page load takes 10,000,000 × 20 µs = 200 seconds. The user leaves after one.

So production systems use a funnel with two stages:

  1. Retrieval (candidate generation): a cheap model, such as the two towers, finds a few hundred items that might fit. It does not score every item. An approximate nearest neighbour (ANN) index finds the stored item vectors with the largest dot products and visits only a small part of the catalogue.
  2. Ranking: the careful model scores only those candidates and sorts them. 500 candidates × 20 µs = 10 ms.

Even brute-force retrieval is cheap: 10 million dot products of 64 numbers is 640 million multiply-adds, a fraction of a second on one core, and ANN cuts it far more. The YouTube paper draws the same funnel: millions of videos, then hundreds of candidates, then dozens shown, under a serving budget of tens of milliseconds.

StageItems inCost per itemGoal
Retrievalmillionsone dot productdo not miss good items (recall)
Rankinghundredsa deep network, hundreds of featuresget the order right (precision)
Re-rankingdozensrulesvariety, freshness, policy

Size the funnel

Retrieval passes K candidates to the ranker. Green counts how many of the true best 10 survive. Yellow is the ranker's time. Drag K.

100

Illustrative simulation: 5,000 items with a true score; retrieval sees the true score plus noise (standard deviation 0.5 of the score spread). Over many random catalogues, K = 10 keeps about 4 of the best 10, K = 100 about 9.4, K = 500 nearly all. Ranker time is K × 20 µs.

K is a trade. Small K is fast but drops good items the ranker never sees. Large K finds them but costs ranking time. Teams pick K where recall stops rising.

The failure, as symptom, measurement and fix

Symptom: a better ranker brings no gain online. Measurement: compute retrieval recall: the share of items users later engaged with that were in the candidate set. If it is low, the ranker never saw them. Fix: improve retrieval, raise K, or add more candidate sources.

A ranker costs 20 µs per item. How long does it take to rank 2,000 candidates, and what does retrieval try to maximize?

Chapter 6

The Ranker: DLRM and Feature Crosses

Turn every feature into a vector, multiply every pair, and predict the chance of a click

The ranker sees one (user, candidate) pair with many features: user ID, item ID, country, device, hour, price. A click may depend on a combination: this user, on a phone, at night, likes short videos. No single feature says that.

Meta's DLRM (Deep Learning Recommendation Model, 2019) builds the ranker in four steps:

  1. Each categorical feature (an ID from a fixed set) looks up a vector in its own embedding table.
  2. The dense features (numbers such as age or price) go through a small network, the bottom MLP, into one vector of the same length.
  3. DLRM takes the dot product of every pair of these vectors. Each dot product is a feature cross: how well two features fit together.
  4. The crosses and the dense vector go through a top MLP and a sigmoid, which gives the click probability.

How many crosses? Call the number of vectors n: one per categorical feature, plus one for the dense features. Call the number of pairs C.

Say it aloud

C equals n times n minus one, over two.

C
C the number of feature crosses: one dot product per pair of vectors.
n
n the number of vectors: categorical features plus one dense vector.
n − 1
n minus one each vector pairs with every other vector, not with itself.
/ 2
over two the pair (a, b) is the same as (b, a), so each pair counts once.
In plain words

Each of the n vectors meets the other n minus one. That counts every pair twice, so halve it. The result C is how many crosses the top MLP reads.

With numbers

The Criteo ad dataset in the DLRM paper has 26 categorical and 13 dense features. So n = 26 + 1 = 27 and C = 27 × 26 / 2 = 351. With 16-number vectors, the top MLP reads 351 + 16 = 367 numbers.

Count the crosses and the memory

Each lit cell is one dot product between two feature vectors. Drag the feature count. Then drag the table size and see where the memory goes.

26
1 B

Memory = IDs × d × 4 bytes (32-bit numbers), for one table. The table sizes are illustrative; the 26 + 13 features and d = 16 are from the DLRM paper's Criteo test.

The memory is in the tables, not the MLPs. One table of 1 billion user IDs with d = 64 takes 1,000,000,000 × 64 × 4 bytes = 256 GB. The paper's bottom MLP has layers of 512, 256 and 64 units, and both MLPs together hold well under a million weights. Its Criteo model has about 540 million parameters in total, nearly all in the tables. So DLRM splits the tables across machines (model parallelism) and copies the MLPs (data parallelism).

The failure, as symptom, measurement and fix

Symptom: the model will not fit on one GPU. Measurement: add up rows × d × 4 bytes for each table. Fix: shard the tables, hash rare IDs into shared rows, or use fewer bytes per number.

A ranker has 9 categorical features and one dense vector. How many crosses does DLRM compute?

Chapter 7

Scoring a Ranked List

Measure a list by what it found, and where it put it

Two systems show you eight films. One puts your favourite first, the other puts it eighth. RMSE scores ratings, not positions, so it cannot tell them apart. A feed is a list, so score the list.

Mark an item relevant if the user later watched it. Call the user's total of relevant items R.

Say it aloud

Recall at k equals the hits in the top k, divided by R.

Recall@k
recall at k the share of the user's relevant items that made the first k places.
hits in the top k
hits in the top k how many of the first k items are relevant.
R
R how many relevant items the user has in total, in the list or not.
In plain words

Count the relevant items in the first k places and divide by R.

With numbers

The device's list has hits at places 1, 3 and 6, and one relevant item is missing, so R = 4. Recall@5 = 2 / 4 = 0.50.

Average precision (AP) rewards putting hits early. At each place where a hit lands, compute the precision so far: hits so far divided by the place number. Call the place of the n-th hit kn.

Say it aloud

AP equals one over R times the sum over hits n of n over k-n.

AP
A-P average precision for one user, from 0 to 1.
1/R
one over R divide by all the user's relevant items; a missing one adds zero.
Σn
the sum over n one term for each hit in the list: the first, the second, and so on.
n / kn
n over k-n the precision at the n-th hit: n hits in the first k-n places.
In plain words

Walk down the list. At each hit, write down hits so far over the place number. Add those and divide by R. AP averaged over all users is MAP, the mean average precision.

With numbers

Hits at places 1, 3 and 6, with R = 4: AP = (1/1 + 2/3 + 3/6) / 4 = (1 + 0.667 + 0.5) / 4 = 0.54. Swap places 2 and 3: AP = (1 + 1 + 0.5) / 4 = 0.63.

A film you rewatched matters more than one you sampled. Give each item a grade gk from 0 to 3. DCG (discounted cumulative gain) adds the grades, each divided by a discount that grows with the place k. NDCG divides DCG by its best possible value.

Say it aloud

NDCG at k equals the sum over places k of g-k over log base two of k plus one, all divided by IDCG.

NDCG@k
N-D-C-G at k normalized discounted cumulative gain of the first k places, from 0 to 1.
Σk
the sum over places k one term for each of the first k places.
gk
g-k the grade of the item at place k: 0 (not relevant) to 3 (loved).
log2(k + 1)
log base two of k plus one the discount: 1 at place 1, 1.58 at place 2, 2 at place 3.
/ IDCG
divided by I-D-C-G the same sum for the best possible order, so a perfect list scores 1.
In plain words

Divide each grade g-k by its place's discount and add: that is DCG. NDCG is DCG over IDCG, the same sum for the ideal order.

With numbers

Grades in places 1 to 5 are 3, 0, 2, 0, 0. DCG = 3/1 + 2/2 = 4.00. The user's grades are 3, 2, 2 and 1, so IDCG = 3/1 + 2/1.585 + 2/2 + 1/2.322 = 5.69. NDCG@5 = 4.00 / 5.69 = 0.70.

Reorder the list, watch three scores

Each row is one recommended film; green dots are its grade. Tap a row to move it up one place. The dashed line marks the top 5.

Illustrative grades. The user has four relevant films; the one graded 2 that is not in the list is why no order reaches 1.0.

The failure, as symptom, measurement and fix

Symptom: offline NDCG rises but users click less. Measurement: check the labels: logs contain only items the old system showed. Fix: confirm with an online A/B test, and add exploration traffic (Chapter 9).

A list has its only two hits at places 2 and 4, and the user has 2 relevant items. What is AP?

Chapter 8

Recommending, Live

Run retrieval, ranking and a diversity re-rank on one map, and trade hits for variety

Here is the whole pipeline on one map. Items sit where their vectors put them, in four groups drawn as four shapes. You are the teal star.

  1. Retrieve: take the K items nearest to you (ringed in purple).
  2. Rank: score each candidate by closeness plus its quality, a hidden number the ranker knows.
  3. Re-rank: build a six-item feed, one pick at a time, with a diversity rule.

Pure ranking often fills the feed with six near copies from the group nearest you. The maximal marginal relevance (MMR) rule scores each candidate for the next slot as its relevance minus a penalty for being like an item already picked. A weight λ from 0 to 1 sets the balance: new score = λ × relevance − (1 − λ) × the highest similarity to a picked item.

A worked number, with made-up values and λ = 0.7. Candidate A has relevance 0.9 and similarity 0.95 to an item already picked: 0.63 − 0.285 = 0.345. Candidate B has relevance 0.8 and similarity 0.2: 0.56 − 0.06 = 0.50. B wins the slot, though A is more relevant.

Run the whole pipeline

Drag the star or tap the map. Purple rings are the K retrieved candidates. Numbers 1 to 6 are the feed. Move the diversity slider and watch the feed spread.

14
0%

Illustrative: 64 items in four groups with a hidden quality. Diversity is 1 − λ in the MMR rule. Hits count feed items that are in your true top 6 by closeness plus quality.

Push diversity up: hits fall a little and groups covered rise. A feed of one group scores better offline and bores the user sooner. Real systems tune this weight with online tests.

With λ = 0.5, candidate A has relevance 0.8 and similarity 0.9 to a picked item; B has relevance 0.6 and similarity 0.1. Which wins?

Chapter 9

Hard Problems: Cold Start and the Feedback Loop

See how a recommender that learns only from what it showed can trap itself, and how exploration frees it

A recommender learns from its own logs. But it logs only the items it showed. An item it never shows never gets a click, so its estimate never improves. The system shows what it already believes is best, and it learns only about those items. This is the feedback loop.

The device has 30 items, each with a hidden click-through rate (CTR): the chance a user clicks it when shown. Every new item starts with an estimate of 5%. Each round the feed shows 5 items, chosen by estimate, and updates the estimates from the clicks. This is exploitation: always show the current best guess.

Let the feed learn from itself

Blue bars are each item's true click rate, best on the left. Purple ticks are the system's estimates; grey ones were never shown. Set the exploration rate ε, then press Run.

0%

Illustrative simulation with fixed random numbers. Estimate = (clicks + 1) / (shows + 20), so an unshown item stays at 5%. With ε, each slot shows a random item instead, with probability ε.

With ε = 0, the feed locks onto the first items that beat 5% and barely tries the rest. In the device, the best item gets 3 of the 10,000 slots. With ε = 0.1 it gets 1,904.

Exploration fixes this: with probability ε, fill a slot with a random item. With ε = 0.1 and 5 slots, each feed spends 0.5 slots on exploring. Over 2,000 feeds that is 1,000 random shows, about 33 per item, enough to find the good ones. Smarter bandit methods explore the items they are least sure about.

ProblemWhat goes wrongCommon fix
Cold starta new user or item has no history, so it has no vectorcompute the vector from features (Chapter 4); explore new items
Feedback loopthe model learns only about what it showedexploration, bandits, logging every show
Implicit feedbacka click is not a like, and a missing click is not a dislikeweight by watch time; treat unshown as unknown
Popularity biaspopular items get more shows, so more clicks, so more showssampling-bias correction, diversity re-ranking

YouTube's 2016 ranker shows the implicit-feedback fix. It predicts expected watch time, not clicks: a weighted logistic regression where each clicked impression counts by its watch time. A click-bait video gets clicks but little watch time, so it scores low.

The failure, as symptom, measurement and fix

Symptom: the catalogue grows but the feed shows the same few items. Measurement: track coverage: the share of items shown at least once a week. Fix: reserve a small, fixed share of slots for exploration and log it, so you can also measure without the old model's bias.

A feed with ε = 0 never shows item 7, which has the highest true CTR. Why?

Chapter 10

Field Guide

Keep the terms, the numbers, a checklist and the core code in one place

A recommender guesses the blank cells of a sparse matrix. Neighbours borrow from similar people. Matrix factorization gives everyone a short vector and predicts with a dot product plus biases. Two towers compute those vectors from features, so you can store and search the item vectors. A cheap retrieval stage feeds a heavy ranker, and ranked-list metrics judge the result.

TermWhat it isNumber to remember
Densityfilled cells / (users × items)Netflix Prize: 1.18%
Neighbour predictionyour average + weighted, centred ratings of similar usersAna, Ripcord: 3.80 (truth 4)
Matrix factorizationμ + bu + bi + pu · qitoy: 0.44 RMSE vs 1.13 popular
Regularization λpenalty that keeps vectors shortλ = 0: 0.86; λ = 0.3: 0.44
Two-tower losssoftmax over the batch, minus log of the picked itemblind guess, B = 4: 1.39
Funnelretrieve hundreds, rank them, show dozens500 × 20 µs = 10 ms
DLRM crossesn(n − 1)/2 dot products of feature vectors27 vectors: 351
Recall@khits in top k / all relevant2 / 4 = 0.50
AP, MAPmean of precision at each hit; MAP averages usershits 1, 3, 6 of 4: 0.54
NDCG@kdiscounted grades / best possible4.00 / 5.69 = 0.70
Exploration εshare of slots given to random items0.1 × 5 slots = 0.5 per feed

Checklist before you ship a recommender

  1. Beat the popularity baseline on held-out data, by a margin larger than run-to-run noise.
  2. Measure retrieval recall separately from ranking quality.
  3. Report a ranked metric (NDCG or MAP) at the k you show, not RMSE alone.
  4. Add up embedding-table memory before you pick d.
  5. Plan for new items: a feature path into the item tower.
  6. Reserve logged exploration traffic, and track coverage.
  7. Confirm offline gains with an online A/B test.

The core, as code

pythonimport numpy as np

def train_mf(R, known, k=2, lam=0.3, lr=0.03, steps=3000, seed=0):
    # R: (users, items) ratings; known: same-shape bool mask of observed cells
    rng = np.random.default_rng(seed)
    n, m = R.shape
    P, Q = 0.1 * rng.standard_normal((n, k)), 0.1 * rng.standard_normal((m, k))
    bu, bi, mu = np.zeros(n), np.zeros(m), R[known].mean()
    for _ in range(steps):
        E = np.where(known, R - (mu + bu[:, None] + bi[None, :] + P @ Q.T), 0)  # errors on known cells only
        P, Q = P + lr * (E @ Q - lam * P), Q + lr * (E.T @ P - lam * Q)
        bu += lr * (E.sum(1) - lam * bu)
        bi += lr * (E.sum(0) - lam * bi)
    return mu + bu[:, None] + bi[None, :] + P @ Q.T                      # (users, items) predictions

def ndcg_at_k(grades_in_order, all_grades, k):
    disc = np.log2(np.arange(2, k + 2))                           # 1, 1.585, 2, ...
    dcg = (np.asarray(grades_in_order[:k]) / disc[:len(grades_in_order[:k])]).sum()
    ideal = np.sort(all_grades)[::-1][:k]
    return dcg / (ideal / disc[:len(ideal)]).sum()

print(round(ndcg_at_k([3, 0, 2, 0, 0, 1, 0, 0], [3, 2, 2, 1], 5), 2))   # 0.7

Where it sits, and where to go next

Newer recommenders read your recent actions in order with a transformer and predict the next item (SASRec, 2018; BERT4Rec, 2019). Graph methods run a graph neural network over the user–item graph (PinSage at Pinterest, 2018). The backbone underneath is the same: vectors, a retrieval stage, a ranker and ranked-list metrics.

Sources

  1. Bennett and Lanning, “The Netflix Prize”, KDD Cup and Workshop, 2007 (dataset counts); Netflix Prize final results, 2009 (Cinematch 0.9525, winning test RMSE 0.8567).
  2. Koren, Bell and Volinsky, “Matrix Factorization Techniques for Recommender Systems”, IEEE Computer, 2009.
  3. Harper and Konstan, “The MovieLens Datasets: History and Context”, ACM TiiS, 2015.
  4. Covington, Adams and Sargin, “Deep Neural Networks for YouTube Recommendations”, RecSys 2016. Paper
  5. Yi et al., “Sampling-Bias-Corrected Neural Modeling for Large Corpus Item Recommendations”, RecSys 2019.
  6. Naumov et al., “Deep Learning Recommendation Model for Personalization and Recommendation Systems”, 2019. arXiv:1906.00091
  7. Carbonell and Goldstein, “The Use of MMR, Diversity-Based Reranking”, SIGIR 1998.
  8. Järvelin and Kekäläinen, “Cumulated Gain-Based Evaluation of IR Techniques”, ACM TOIS, 2002 (NDCG).
The takeaway. Turn people and items into vectors, find candidates fast with a dot product, rank a few hundred with care, and judge the list by where it puts the hits.

Teach it back: open Present or Teach and predict Ana's rating of Ripcord out loud, first with neighbours, then with factors. Then go back to the empty matrix and guess which predictor wins before you press it.

Recommender Systems: Personalization at Scale
Back to Gleams