Skip to content
BIASED

Recommender systems

The user–item matrix, content-based and collaborative filtering, neighbours, matrix factorization with biases by ALS and SGD, implicit feedback, honest time-split evaluation, cold start, and a recap of the whole course.

The query is a user

The topic Learning to rank ordered documents for a query. Every (query, document) pair came with features, such as text matches, links and embeddings, and with a graded label or a click. A recommender orders items for a person: the next film, the songs of a playlist, the products for a basket. The query is now a user. Often nothing describes the user except what they did: which items they rated, bought, played or skipped.

That record is enough. People who agreed in the past tend to agree in the future, and items liked by the same people tend to be liked together. This topic turns that observation into models. It is the matrix of user ratings promised in the topic What machine learning is, and the last topic of the course.

Notation. There are mm users, indexed by uu, and nn items, indexed by ii. The feedback of user uu on item ii is ruir_{ui}: a rating from 1 to 5 stars, or a count such as the number of plays. Ω\Omega is the set of pairs (u,i)(u, i) with known ruir_{ui}, nun_u is the number of items user uu rated, and r^ui\hat r_{ui} is a prediction.

Everything a collaborative recommender knows sits in one matrix RR: a row per user, a column per item, an entry wherever the user left feedback. Three properties of this matrix shape every method below.

  • It is almost empty. The Netflix Prize data held more than 100 million ratings by about 500,000 users of more than 17,000 films: about 1% of the cells.
  • It is skewed. A few items collect most of the feedback. In the synthetic data of this topic, 18,872 ratings of 400 items by 600 users (7.9% of the cells), the 10% most popular items hold 53% of all ratings.
  • Its gaps are not random. A user rates the films they chose to watch, and they chose them because they expected to like them. Whether a cell is filled depends on exposure, availability and the user's own choice. An empty cell is not a low rating, and it is not a neutral unknown either.

Explicit feedback, such as stars or thumbs, says how much a user liked an item, in both directions, and it is scarce. Implicit feedback, such as plays, purchases, clicks and watch time, is plentiful but has no negatives: a film not watched may be disliked or simply unknown. The first half of the topic works with ratings, the second with implicit feedback.

The product shows a short list, so the real task is to rank the items a user has not seen yet. It is the problem of the previous topic with users in place of queries. Predicting ratings is only a means, and the evaluation must measure the list.

Content and neighbours

The first approach ignores the other users altogether. Content-based filtering describes each item by a feature vector ϕi\phi_i, such as genres or an embedding of the description, and fits one model per user. With a linear model it is one ridge regression per user, as in the topic Regularization:

wu=arg⁡min⁡w∑i: (u,i)∈Ω(rui−w⊤ϕi)2+λ∥w∥2,r^ui=wu⊤ϕi.w_u = \arg\min_w \sum_{i:\,(u, i) \in \Omega} \big(r_{ui} - w^\top \phi_i\big)^2 + \lambda \lVert w \rVert^2, \qquad \hat r_{ui} = w_u^\top \phi_i .

It scores a new item on the day it appears and explains itself ("because you liked other jazz records"). Its limits are those of the features. It cannot learn that fans of one director like a particular composer unless a feature records it, and it shows each user more of the same.

Collaborative filtering uses no item features. Similarity is computed from the matrix itself. The oldest methods are the Nearest neighbours of topic 4. The item-based version compares two items through the users who rated both. Each rating is first centred by its user's mean rˉu\bar r_u, so that a harsh critic and a generous one become comparable. The adjusted cosine similarity is

sij=∑u(rui−rˉu)(ruj−rˉu)∑u(rui−rˉu)2 ∑u(ruj−rˉu)2,s_{ij} = \frac{\sum_u (r_{ui} - \bar r_u)(r_{uj} - \bar r_u)}{\sqrt{\sum_u (r_{ui} - \bar r_u)^2}\,\sqrt{\sum_u (r_{uj} - \bar r_u)^2}},

with the sums over users who rated both ii and jj. The prediction for uu is their mean plus a weighted average of their own centred ratings of the similar items jj:

r^ui=rˉu+∑jsij (ruj−rˉu)∑j∣sij∣.\hat r_{ui} = \bar r_u + \frac{\sum_j s_{ij}\,(r_{uj} - \bar r_u)}{\sum_j \lvert s_{ij} \rvert} .

Five users rated five films (· = not rated):

film 1 film 2 film 3 film 4 film 5 mean
Ann 5 4 · 1 · 3.333
Ben 4 5 1 · 2 3
Cat · 4 2 1 1 2
Dan 1 · 5 4 · 3.333
Eve 2 1 4 · 5 3

How will Ann rate film 3? The code compares film 3 with films 1, 2 and 4, the ones Ann rated:

import numpy as np
 
nan = np.nan
R = np.array([[5, 4, nan, 1, nan],     # Ann
              [4, 5, 1, nan, 2],       # Ben
              [nan, 4, 2, 1, 1],       # Cat
              [1, nan, 5, 4, nan],     # Dan
              [2, 1, 4, nan, 5]])      # Eve
seen = ~np.isnan(R)
mean = np.nanmean(R, axis=1, keepdims=True)
C = np.where(seen, R - mean, 0)        # centre each user's ratings
 
def sim(i, j):                         # adjusted cosine over users who rated both
    both = seen[:, i] & seen[:, j]
    a, b = C[both, i], C[both, j]
    return a @ b / np.sqrt((a @ a) * (b @ b))
 
s = np.array([sim(2, j) for j in (0, 1, 3)])
pred = mean[0, 0] + s @ C[0, [0, 1, 3]] / np.abs(s).sum()
print(s.round(3), pred.round(2))
[-0.905 -0.775  0.555] 1.85

Film 3 is liked by the people who dislike films 1 and 2, and Ann likes those two and dislikes film 4. The prediction, 1.85, is low. Item similarities change slowly and can be computed offline, and the answer comes with a reason ("because you watched..."). Amazon's early recommender was built this way.

Neighbours struggle exactly where the matrix is sparsest. Two users with two items in common have a correlation of exactly ±1\pm 1, and the similarity of a rare item rests on a handful of people. Each similarity is estimated on its own, and the neighbourhood size and the normalization are heuristics with no objective to optimize.

Latent factors

A latent factor model explains every rating by a few hidden properties of the user and of the item. User uu gets a vector pu∈Rdp_u \in \mathbb R^d, item ii a vector qi∈Rdq_i \in \mathbb R^d, and their interaction is the dot product. Here dd is the number of factors, not of features. One coordinate might come to measure how much a film is a comedy and how much a user likes comedies. Nothing forces the coordinates to be readable, but a few dozen describe much of the taste in a large catalogue.

Before any interaction, much of a rating is explained by who rates and what is rated. Some users rate everything high; some films are rated high by everyone. These effects get their own parameters, the biases: offsets like bb of a linear model, not the bias of the bias–variance decomposition. With the global mean μ\mu the model is

r^ui=μ+bu+bi+pu⊤qi.\hat r_{ui} = \mu + b_u + b_i + p_u^\top q_i .

Say μ=3.6\mu = 3.6, the film is rated 0.40.4 above average, and the user rates 0.50.5 below average. The baseline is 3.6+0.4−0.5=3.53.6 + 0.4 - 0.5 = 3.5, and the dot product adds or subtracts what this user's taste says about this film.

The model is fitted to the known ratings only, with an ℓ2\ell_2 penalty on every parameter each time it appears in a rating:

min⁡P,Q,b∑(u,i)∈Ω[(rui−μ−bu−bi−pu⊤qi)2+λ(∥pu∥2+∥qi∥2+bu2+bi2)].\min_{P, Q, b} \sum_{(u, i) \in \Omega} \Big[ \big(r_{ui} - \mu - b_u - b_i - p_u^\top q_i\big)^2 + \lambda \big( \lVert p_u \rVert^2 + \lVert q_i \rVert^2 + b_u^2 + b_i^2 \big) \Big].

Here PP and QQ are the matrices with rows pup_u and qiq_i. Drop the biases and the penalty, and suppose every entry is known. Then the problem is the best rank-dd approximation of RR, solved exactly by the truncated SVD: the Eckart–Young theorem from the topic The singular value decomposition of Mathematics for ML, the same computation as PCA in the topic Dimensionality reduction. With 99% of the entries missing, the SVD is not even defined. Filling the gaps with zeros or means would teach the model ratings nobody gave.

The penalty is what keeps a fit to the known cells honest. A user with three ratings could otherwise get a vector that reproduces them exactly and predicts nonsense elsewhere. The topic Bayesian inference of Probability Theory explains the penalty as it did for ridge regression. Gaussian noise on the ratings and Gaussian priors on the factors make this objective, up to constants, the negative log-posterior, and the fit is a MAP estimate.

Why can a few known cells fill in the rest? A rank-dd matrix of size m×nm \times n is fixed by about (m+n) d(m + n)\,d numbers, not mnmn. For 600 users, 400 items and d=3d = 3 that is 3,000 numbers against 240,000 cells. Real rating matrices are not exactly low-rank, but their main directions of taste are few, and those are what the factors capture.

Fitting: SGD and ALS

The objective is a sum over known ratings, so it suits the SGD of the topic Stochastic and adaptive optimizers. Loop over the ratings in random order, compute the error eui=rui−r^uie_{ui} = r_{ui} - \hat r_{ui}, and move the parameters of this rating a step η\eta against the gradient:

bu←bu+η (eui−λbu),pu←pu+η (eui qi−λpu),bi←bi+η (eui−λbi),qi←qi+η (eui pu−λqi).\begin{aligned} b_u &\leftarrow b_u + \eta\,(e_{ui} - \lambda b_u), & p_u &\leftarrow p_u + \eta\,(e_{ui}\, q_i - \lambda p_u),\\ b_i &\leftarrow b_i + \eta\,(e_{ui} - \lambda b_i), & q_i &\leftarrow q_i + \eta\,(e_{ui}\, p_u - \lambda q_i). \end{aligned}

The factor 2 of the derivative is absorbed into η\eta. The four updates use the values from before the step, and each costs O(d)O(d). This loop, popularized during the Netflix Prize, made factorization famous.

The objective is not convex. pu⊤qip_u^\top q_i is a product of unknowns, and rescaling pu→c pup_u \to c\,p_u, qi→qi/cq_i \to q_i / c changes nothing. But fix all item vectors, and the problem for one user is the least squares of topic 5 with a ridge penalty, which has a closed form. Ignore the biases for a moment. Let QuQ_u be the matrix whose rows are the vectors of the nun_u items uu rated, and rur_u the vector of those ratings with μ\mu and the biases subtracted. The normal equations give

pu=(Qu⊤Qu+λnuI)−1Qu⊤ru,p_u = \big(Q_u^\top Q_u + \lambda n_u I\big)^{-1} Q_u^\top r_u ,

with the factor nun_u because the penalty is paid once per rating. Alternating least squares (ALS) fixes the items and solves every user, then fixes the users and solves every item, and repeats. Each half-step solves its subproblem exactly, so the objective never increases. A bias joins the same solve as one more coordinate whose regressor is 1. ALS needs no learning rate, and its users, then its items, are independent problems that run in parallel.

A user rated two items with vectors q1=(1,0)q_1 = (1, 0) and q2=(1,1)q_2 = (1, 1), with centred ratings 2 and 1. With λnu=0.1\lambda n_u = 0.1:

import numpy as np
 
Qu = np.array([[1.0, 0.0], [1.0, 1.0]])   # vectors of the two items
ru = np.array([2.0, 1.0])                 # centred ratings
pu = np.linalg.solve(Qu.T @ Qu + 0.1 * np.eye(2), Qu.T @ ru)
print(pu.round(3), (Qu @ pu).round(3))
[ 1.756 -0.687] [1.756 1.069]

The predictions 1.756 and 1.069 are close to 2 and 1, shrunk slightly by the penalty.

On the synthetic ratings of this topic, generated from biases, three taste factors and noise, rounded to stars, with item popularity drifting over time, the test set is the last 20% of the time. The root mean squared error is 0.969 for the global mean, 0.835 for the biases alone, 0.705 for factorization with d=3d = 3 by ALS and 0.702 by mini-batch SGD on the same objective. With d=10d = 10 it grows to 0.756: the extra factors fit noise. Like the degree of a polynomial, dd is a capacity to choose by validation.

Implicit feedback

Plays, purchases and clicks change the problem in three ways. There are no negatives, so the empty cells cannot be ignored: a model fitted to observed cells only would see nothing but positive evidence. The signal is noisy: a show played once may have run while the viewer slept. And the value of an entry measures confidence, not preference: a favourite film watched once and a series watched weekly are both liked, the weekly count just makes the evidence stronger.

Hu, Koren and Volinsky (2008) separate the two meanings. The preference is binary, sui=1s_{ui} = 1 if rui>0r_{ui} > 0 and 00 otherwise. The confidence grows with the count:

cui=1+α rui.c_{ui} = 1 + \alpha\, r_{ui} .

The model fits the preferences of all m⋅nm \cdot n cells, weighted by confidence:

min⁡P,Q∑u,icui(sui−pu⊤qi)2+λ(∑u∥pu∥2+∑i∥qi∥2).\min_{P, Q} \sum_{u, i} c_{ui} \big( s_{ui} - p_u^\top q_i \big)^2 + \lambda \Big( \sum_u \lVert p_u \rVert^2 + \sum_i \lVert q_i \rVert^2 \Big).

Every empty cell says "probably not" with the minimum confidence 1. Every observed cell says "probably yes", more firmly the more often it happened. With α=2\alpha = 2, a show played 3 times gets c=7c = 7: the fit cares about it as much as about seven unplayed shows. With α=40\alpha = 40, the value the authors found good for their television data, the same cell weighs as much as 121.

The sum has m⋅nm \cdot n terms, billions in practice, which rules out SGD. ALS still works. The user solve becomes a weighted ridge regression, pu=(Q⊤CuQ+λI)−1Q⊤Cusup_u = (Q^\top C^u Q + \lambda I)^{-1} Q^\top C^u s_u, with CuC^u the diagonal matrix of uu's confidences. One identity makes it cheap:

Q⊤CuQ=Q⊤Q+Q⊤(Cu−I) Q.Q^\top C^u Q = Q^\top Q + Q^\top (C^u - I)\, Q .

Q⊤QQ^\top Q is the same for every user and is computed once per sweep. Cu−IC^u - I is zero except on the nun_u items the user touched, so the user's own part costs O(d2nu)O(d^2 n_u).

In a simulation, the same 600 users play liked items several times and random items once, and one liked item per user is held out. The hit rate is the share of users whose held-out item lands in the top 10 of their unplayed items. Recommending the most popular items gives 19.8%. Implicit ALS, with λ\lambda chosen on a separate validation item, gives 32.7% with α=0\alpha = 0, 34.8% with α=2\alpha = 2 and 28.5% with α=40\alpha = 40, which trusts the counts too much for these data. α\alpha is a hyperparameter like λ\lambda.

A pairwise alternative trains on triples: for user uu, an item ii they interacted with should rank above an item jj they did not. Bayesian personalized ranking (BPR) maximizes ∑log⁡σ(r^ui−r^uj)\sum \log \sigma(\hat r_{ui} - \hat r_{uj}) over sampled triples, with a Gaussian prior on the parameters. It is the RankNet loss of the previous topic with a user in place of a query, and a smooth version of each user's AUC from the topic Classification metrics.

Evaluating without fooling yourself

A recommender is unusually easy to evaluate wrongly, and every such error makes it look better than it is.

Split by time. A random split lets the model train on ratings made after the ones it is tested on. It learns which items will become popular and what each user will come to like, which it cannot know when deployed. The honest split mirrors deployment: train on everything before a cutoff, test on what came after. This is the time split of the topic Validation and overfitting and a common form of the leakage from the topic Data, features and leakage. On the synthetic ratings, whose popularity drifts, a random split gives the rank-3 model an error of 0.670 instead of 0.705 on a time split. It flatters every model: the biases get 0.800 instead of 0.835. Hyperparameters such as dd, λ\lambda and α\alpha are chosen on a validation period before the test period. Choosing them on the test period brings back the selection bias of reusing a test set.

Measure the list. The Netflix Prize scored the error of predicted ratings, but users see a top-kk list. The metrics of the topic Learning to rank, precision at kk, MAP and NDCG, are computed per user over the held-out items, together with recall at kk and the hit rate. Items the user has already seen are removed from the candidates. A recommended item the user did not touch in the test period is not known to be irrelevant, so precision underestimates the truth; with implicit data, recall-type metrics are the safer choice.

Beat popularity. Recommending the most popular items is a strong baseline, especially for metrics dominated by popular items. A model that does not beat it clearly has learned nothing personal.

Beyond accuracy. A list can be accurate and useless: ten near-copies of one item, or bestsellers the user would have found anyway. Coverage (the share of the catalogue that ever gets recommended), diversity within a list and novelty (how unknown the items are to the user) are measured next to accuracy.

Offline metrics answer one question: how well does the model predict what users did under the old system? Whether recommendations change behaviour only an online experiment can tell, the A/B test of the topic Hypothesis tests and A/B testing of Probability Theory, run on watch time, purchases or retention.

Cold start and two towers

A new user has an empty row, and a new item an empty column. Collaborative filtering has nothing to work with. This is cold start, and every remedy brings in information from outside the matrix. Before any feedback, show popular or hand-picked items, or ask a new user to pick a few favourites. Use content features for new items and context, such as device, country and time, for new users. Factorization can absorb them too: a user's vector can include the sum of the vectors of their known attributes, so a user with no ratings still gets one. In the ALS above, users with no training ratings get pu=0p_u = 0 and bu=0b_u = 0 and fall back to μ+bi\mu + b_i, the item's average corrected for who rated it.

Matrix factorization is two lookups and a dot product: the user's id selects a row of PP, the item's id a row of QQ. Two-tower models replace the lookups with neural networks. A user tower maps the history, context and features to a vector u(x)u(x); an item tower maps the item's id and content to v(y)v(y); the score is ⟨u(x),v(y)⟩\langle u(x), v(y) \rangle. The item tower reads content, so a new item gets a vector from its features alone.

Training treats recommendation as classification over the catalogue: given the user, which item did they choose? The softmax over millions of items is replaced by a softmax over the items of the mini-batch, the other items serving as negatives. Popular items land in batches more often and would be pushed down too often, so each logit is corrected by subtracting the log-probability that its item is sampled.

At serving time the item vectors are computed in advance. A nearest-neighbour search by dot product returns a few hundred candidates out of millions in milliseconds, and a feature-rich ranker from the previous topic, such as LambdaMART, orders them. Retrieval and reranking, once more.

Two warnings close the method. A recommender learns from items it chose to show, so it reinforces its own past choices and popular items grow more popular: a feedback loop, corrected only by inverse propensity weighting, as with the examination propensities of the topic Learning to rank, or by deliberate exploration. And predicted stars or clicks are not the goal: clickbait collects clicks. Choosing the target is part of the design.

The course as a whole

The course began with one question: how does a program learn a rule from examples, and how do we know the rule will work on data it has not seen? This topic used almost every answer the course gave. Neighbours came from topic 4, least squares and ridge from topics 5 and 8, SGD from topic 7, the SVD from Mathematics for ML, MAP from Probability Theory, the ranking metrics from topic 26 and the time split from topic 3.

Learning the rule. Choose a family of models and a loss, then minimize the empirical risk. Least squares found a global linear rule and read it as the maximum likelihood of Gaussian noise. Gradient descent and its stochastic versions fitted what has no closed form. Regularization stopped the fit from chasing noise and turned out to be a prior. Logistic regression, margins and kernels drew class boundaries. Trees expressed interactions, the bias–variance decomposition explained why bagging and boosting help, and networks learned the features themselves through backpropagation. Without labels, clustering, EM, PCA and anomaly scores found structure. The last two topics turned scores into orders.

Knowing it will work. Training error lies, so the risk is estimated on data the model never touched. The split must mirror deployment: by group, by time, without leakage. A validation score is a noisy average, and reusing a test set to choose among models biases it. The metric must count the errors that matter: precision and recall for rare classes, NDCG and hit rate for lists, against a baseline that is hard to beat.

Topic 1 named three limits of all this. A recommender hits each of them. Its world changes: new items, drifting tastes, so the validated risk expires. It optimizes the loss it was given, stars or clicks, not what users value. And its predictions are not causes: only an experiment shows whether a recommendation changed what a user did.

The next courses pick up from here.

  • Deep Learning scales up the networks of the last modules, with convolutional networks, transformers and the practice of training them; the towers of a two-tower model are built from them.
  • Natural Language Processing turns text into features and models: logistic regression on a Bag of words, word embeddings as factorized co-occurrences in Word2Vec and GloVe, and retrieval with reranking in Embeddings and semantic search and Retrieval-augmented generation.
  • MLOps: Machine Learning in Production is where the validated model meets a changing world: Features and training–serving skew, Rolling out models, Monitoring and drift, Retraining and continual learning.

Bayesian Methods in Machine Learning replaces the point estimates of this course with posteriors, and Generative Models grows PCA into autoencoders and EM into the VAE. This course ends here: with a rule learned from examples, and an honest estimate of how it will do on the next one.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.