Back to Tutorials
Machine Learning
Intermediate

Recommendation Systems: How “You Might Also Like” Works

Rate a few dishes and get recommendations from a model trained in your browser, then watch a recommender trap itself in a loop of its own making.

11 minInteractive: drag, click and try things as you read


“Because you watched…”, “Customers also bought…”, the next song, the next video: recommendation systems choose much of what we see online. Most of them rest on one idea, collaborative filtering: people who agreed in the past tend to agree again, so your ratings can be predicted from other people’s. A recommender learns a few hidden numbers for every person and every item, and nobody tells it what the numbers mean. Here you’ll rate dishes and get recommendations from a model trained in your browser, then watch a recommender trap itself in a loop of its own making.

Two ways to recommend#

Say you run a takeaway app with 30 dishes. There are two classic ways to suggest what someone should order next:

  • Content-based: describe every dish (spicy, vegetarian, creamy, noodles…) and suggest dishes that resemble what the person liked. It needs someone, or something, to write good descriptions, and it only ever finds more of the same.
  • Collaborative filtering: ignore what the dishes are, and look only at who rated what. If the people who loved your favourites also loved a dish you haven’t tried, it’s probably a good bet. No descriptions needed, and it can find connections nobody would think to write down.

The most famous version of the second idea is matrix factorisation. Put every rating in a giant table, one row per person, one column per dish, mostly empty because each person has tried only a few. Then give every person a short list of numbers, say two, and every dish two numbers as well, chosen so that combining a person’s numbers with a dish’s numbers (multiply them pair by pair and add, plus an adjustment for generous raters and well-loved dishes) predicts the ratings you do have. The same numbers then fill in every empty cell. It’s the same idea as word embeddings: each thing becomes a point in space, learned from how things go together.

Train one and try it#

The figure below has 600 made-up diners who have each rated 5 to 11 dishes, from 1 to 5 stars: about 4,300 ratings to learn from, with one in ten held back to test on. Behind the scenes each diner has a taste for spice, meat and rich food, but the model is given only the stars. It learns two numbers per dish and per diner by alternating least squares: fix the dishes’ numbers and find the best numbers for every diner, then fix the diners’ and find the best for every dish, and repeat.

Predict first

The model learns two numbers per dish from star ratings alone. Plot each dish at its two numbers. What do you expect to see?

Try it
Made-up diners and ratings, generated in your browser; the model is trained there too. Your ratings are fitted on the spot, holding the dishes’ numbers fixed, and every dish you haven’t rated gets a predicted score.

The two numbers the model learned for each dish line up closely with what’s in it: right on the map is spicier, up is meatier. Together they predict how much meat a dish contains with an R² of 0.92 and how spicy it is with 0.74, though the model never saw either. (We labelled the directions afterwards, by looking at where the dishes landed.) The hidden numbers are a summary of taste, discovered from behaviour alone.

And they predict well. Guessing each held-back rating from the dish’s average misses by 1.13 stars (the root mean square error); the two-number model misses by 0.89. Rate a couple of curries and dismiss the macaroni cheese, and your star on the map swings towards the spicy side and pulls the hot dishes up your list.

Rate nothing, and the model can only fall back on which dishes are generally well liked. That’s the cold-start problem: a new diner has no ratings to place them, and a new dish has no ratings to place it either, so collaborative filtering can’t recommend it at all. Real systems fill the gap with content: describe the new dish, ask new users a few questions, or start them on the popular list.

The loop that feeds itself#

A recommender learns from what people click, order and watch. But people mostly click what they’re shown, and what they’re shown is chosen by the recommender. Its training data is shaped by its own past recommendations. That’s a feedback loop, and it can lock in early accidents.

Take the simplest home screen there is: show the four most-ordered dishes. A restaurant adds 40 new dishes, all with zero orders, and each has a hidden chance of being ordered when a diner sees it. A hundred diners visit each day.

Predict first

After 60 days of showing the four most-ordered dishes, how many of the four truly most appealing dishes will be on the home screen?

Try it
A simulation run in your browser: 40 made-up dishes, each with a hidden chance of being ordered when shown, and 100 diners a day. “Another town” keeps the dishes and changes the luck.

Across the eight towns, the plain most-ordered screen ended up with at most one of the four best dishes, and 35 or 36 of the 40 dishes were never shown at all. Diners averaged half an order per visit, against 1.18 for an app that knew which dishes were best. Give one of the four slots to a random dish each day, and between 29 and 34 dishes get a chance, up to three of the best are found, and orders rise to three quarters of a dish per visit on average, even though a quarter of the screen is spent on random picks. A recommender that only exploits what it already knows never learns what it’s missing.

Trading a little of today’s performance to learn something is called exploration, and balancing it against exploiting what works is the classic problem in reinforcement learning. Real systems explore more cleverly than a random slot, favouring items that might be good but have little data. In 2018 Allison Chaney, Brandon Stewart and Barbara Engelhardt showed in simulations that recommenders retrained on data their own recommendations shaped make users’ behaviour more alike without making them better off: the same loop, at the scale of a whole platform.

Building one in practice#

  • Start with a baseline. Most popular, or most popular in a category, is hard to beat at the start and is what you’ll show cold-start users anyway.
  • Use the signals you have. Most apps have clicks, plays and purchases rather than stars. Those are “implicit feedback”: a play is a weak yes, and a skip isn’t necessarily a no. Libraries such as implicit and LightFM are built for it.
  • Test on the future. Hold out each user’s most recent interactions, not random ones, and measure whether they appear in the top 10 you would have shown (the same metrics as search). Then run an A/B test, because offline scores and real behaviour often disagree.
  • Watch beyond accuracy: how many different items get recommended, how new users fare, and whether a few items are crowding out everything else.

In code#

Matrix factorisation by alternating least squares in plain NumPy (pip install numpy), on a tiny made-up table of six diners and six dishes:

import numpy as np

dishes = ["vindaloo", "green curry", "chana masala", "dal", "cheeseburger", "mac and cheese"]
nan = np.nan
stars = np.array([            # rows are diners, nan = not rated yet
    [5, 5, nan, 3, 2, 1],
    [4, nan, 4, 3, nan, 1],
    [nan, 2, 5, 5, 1, nan],
    [1, 1, 3, nan, 5, 5],
    [2, nan, 1, 2, 5, nan],
    [5, 4, 2, nan, nan, 2],
])
known = ~np.isnan(stars)
mean = np.nanmean(stars)
k, lam = 2, 0.5
rng = np.random.default_rng(0)
users = rng.normal(0, 0.1, (6, k))
items = rng.normal(0, 0.1, (6, k))

for _ in range(30):                     # alternating least squares
    for u in range(6):                  # best diner vectors, dishes fixed
        V = items[known[u]]
        users[u] = np.linalg.solve(V.T @ V + lam * np.eye(k), V.T @ (stars[u, known[u]] - mean))
    for i in range(6):                  # best dish vectors, diners fixed
        U = users[known[:, i]]
        items[i] = np.linalg.solve(U.T @ U + lam * np.eye(k), U.T @ (stars[known[:, i], i] - mean))

guess = np.clip(mean + users @ items.T, 1, 5)
for u, i in zip(*np.where(~known)):
    print(f"diner {u} would give {dishes[i]}: {guess[u, i]:.1f} stars")
# diner 0 would give chana masala: 3.1 stars
# diner 1 would give green curry: 4.1 stars
# diner 1 would give cheeseburger: 1.6 stars
# diner 2 would give vindaloo: 2.3 stars
# diner 2 would give mac and cheese: 2.7 stars
# diner 3 would give dal: 3.1 stars
# diner 4 would give green curry: 2.5 stars
# diner 4 would give mac and cheese: 4.5 stars
# diner 5 would give dal: 2.2 stars
# diner 5 would give cheeseburger: 3.0 stars

Diner 1 loves spice and gets green curry at 4.1 stars and the cheeseburger at 1.6; diner 4 likes comfort food and gets macaroni cheese at 4.5. The figure’s model is the same, plus a separate adjustment for each diner and dish, on 600 diners instead of 6.

What to remember

  • Collaborative filtering predicts what you’ll like from people whose ratings resemble yours; content-based methods use descriptions of the items instead.
  • Matrix factorisation learns a few hidden numbers per person and per item; here they rediscovered spice and meat from star ratings alone.
  • Recommenders shape the data they learn from, so they need exploration, cold-start fallbacks, and tests on future behaviour.

Keep going

Sign in to save your place and keep a learning streak. Free, with Google.