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 users, indexed by , and items, indexed by . The feedback of user on item is : a rating from 1 to 5 stars, or a count such as the number of plays. is the set of pairs with known , is the number of items user rated, and is a prediction.
Everything a collaborative recommender knows sits in one matrix : 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 , 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:
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 , so that a harsh critic and a generous one become comparable. The adjusted cosine similarity is
with the sums over users who rated both and . The prediction for is their mean plus a weighted average of their own centred ratings of the similar items :
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.85Film 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 , 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 gets a vector , item a vector , and their interaction is the dot product. Here 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 of a linear model, not the bias of the bias–variance decomposition. With the global mean the model is
Say , the film is rated above average, and the user rates below average. The baseline is , 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 penalty on every parameter each time it appears in a rating:
Here and are the matrices with rows and . Drop the biases and the penalty, and suppose every entry is known. Then the problem is the best rank- approximation of , 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- matrix of size is fixed by about numbers, not . For 600 users, 400 items and 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 , and move the parameters of this rating a step against the gradient:
The factor 2 of the derivative is absorbed into . The four updates use the values from before the step, and each costs . This loop, popularized during the Netflix Prize, made factorization famous.
The objective is not convex. is a product of unknowns, and rescaling , 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 be the matrix whose rows are the vectors of the items rated, and the vector of those ratings with and the biases subtracted. The normal equations give
with the factor 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 and , with centred ratings 2 and 1. With :
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 by ALS and 0.702 by mini-batch SGD on the same objective. With it grows to 0.756: the extra factors fit noise. Like the degree of a polynomial, 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, if and otherwise. The confidence grows with the count:
The model fits the preferences of all cells, weighted by confidence:
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 , a show played 3 times gets : the fit cares about it as much as about seven unplayed shows. With , the value the authors found good for their television data, the same cell weighs as much as 121.
The sum has terms, billions in practice, which rules out SGD. ALS still works. The user solve becomes a weighted ridge regression, , with the diagonal matrix of 's confidences. One identity makes it cheap:
is the same for every user and is computed once per sweep. is zero except on the items the user touched, so the user's own part costs .
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 chosen on a separate validation item, gives 32.7% with , 34.8% with and 28.5% with , which trusts the counts too much for these data. is a hyperparameter like .
A pairwise alternative trains on triples: for user , an item they interacted with should rank above an item they did not. Bayesian personalized ranking (BPR) maximizes 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 , and 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- list. The metrics of the topic Learning to rank, precision at , MAP and NDCG, are computed per user over the held-out items, together with recall at 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 and and fall back to , 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 , the item's id a row of . Two-tower models replace the lookups with neural networks. A user tower maps the history, context and features to a vector ; an item tower maps the item's id and content to ; the score is . 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.
Answers are saved on the server and tied to this browser until you sign in.