Learning path: End-to-End ML Use Cases: Fraud, Recommendations, Forecasting and Ticket Routing · Step 6 of 16
Recommendations, Part 2: Candidate Generation With Embeddings
Build stage one of a recommender from nothing but who had what: TruncatedSVD squeezes a 300 by 120 grid into 8 numbers per user and item, one matrix multiply finds 30 candidates (hit rate 0.807 vs 0.657 for popularity), and dim 8 beats both 2 and 32.
What you will learn
- Turn a user-item event grid into 8-number user and item embeddings with TruncatedSVD
- Generate 30 candidates per user with one matrix multiply and a sort
- Check what the embeddings learned with cosine nearest neighbours
- Choose the candidate list length and embedding size as trade-offs
Before you start
- Recommendations, Part 1: Two Stages, Candidates Then Ranking
- Similarity Search: Finding the Closest Vectors
In Part 1 we saw why a recommender has two stages. Today we build stage one, the part that pulls a short list of 30 out of the whole catalogue. We start from nothing but who had what. Same synthetic data: 300 users, 120 items, seed 0.
A seating plan
Picture a host planning the seating for a big dinner. Nobody fills in a form about their taste. The host only has a list of who ordered what at past dinners, so people who ordered the same things get seated near each other. Then the dishes get seats too, close to the people who order them.
So what should you try tonight? The dishes sitting close to you that you haven't had yet. Closeness is the whole idea, and in our model a seat is just a few numbers: an embedding.
Squeezing the grid
We start with the grid: one row per user, one column per item, and a 1 wherever that user had that item. Matrix factorisation splits that big grid into two small tables, 8 numbers per user and 8 per item. Multiply them back and you get a blurred copy of the grid.
The blur is the useful part. Cells that were zero now get a score, and the score is high where people with a similar history had that item. A small two-tower neural model does the same job. We stay with matrix factorisation because it's small and needs no training loop.
Building the embeddings
In candidates.py, fit does it in a few lines:
"""Stage one: embedding candidates from past events."""
import numpy as np
from sklearn.decomposition import TruncatedSVD
from data import N_USERS, N_ITEMS
def fit(train, dim=8):
m = np.zeros((N_USERS, N_ITEMS))
m[train[:, 0], train[:, 1]] = 1
svd = TruncatedSVD(dim, random_state=0)
users = svd.fit_transform(m)
return users, svd.components_.T, m
An empty 300 by 120 grid, the ones from the training events, then TruncatedSVD with dim=8 and a fixed random_state. fit_transform gives the users table, 300 rows of 8 numbers. components_.T gives the items table, 120 rows of 8 numbers. Notice what we never passed in: no genres, no descriptions. Only who had what. (SVD is the same family of maths as PCA.)
The search
Finding candidates is the search from Similarity Search: score one query against every row, then sort.
def candidates(model, user, n=30):
users, items, m = model
score = items @ users[user]
score[m[user] > 0] = -np.inf
top = np.argsort(-score, kind="stable")[:n]
return [int(i) for i in top], score
items @ users[user] is one matrix multiply, so every item gets a score for this user. The next line gives anything they already had minus infinity, so it can't come back. Then sort and keep 30.
For user 0, item 65 comes first with 0.775, then item 7 with 0.618, then item 30 with 0.59. And item 30 is the one user 0 picked next, the one we hid. That's why this search is worth having.
Who sits near whom
Why did item 30 score so well? neighbours.py asks who sits near it, using NearestNeighbors with the cosine metric:
nn = NearestNeighbors(n_neighbors=6, metric="cosine").fit(items)
dist, idx = nn.kneighbors(items[[30]])
print("near item 30", idx[0][1:].tolist())
print("their genres", genre[idx[0][1:]].tolist(),
"item 30 genre", int(genre[30]))
print("similarity", np.round(1 - dist[0][1:], 3).tolist())
near item 30 [60, 25, 68, 0, 91]
their genres [5, 5, 5, 5, 5] item 30 genre 5
similarity [0.969, 0.965, 0.959, 0.953, 0.94]
same genre, 5 nearest 1.0
same genre, by chance 0.17
near user 0 [223, 34, 255] shared [12, 11, 12]
shared, average user 4.97
All five neighbours are genre 5, the same as item 30. Across all items, the five nearest always share the genre, where chance would give 0.17. The embeddings found genres we never mentioned. This data is synthetic and tidy, so don't expect a perfect score on real shoppers.
Now look at user 0's history: items 68 and 0 are in it. So user 0 already had two of item 30's closest neighbours, a good hint why it landed third. The same works for people. User 0's three nearest users share 12, 11 and 12 items with them, while the average user shares about 5. People who sit close really have had similar things.
How many candidates?
candidates 10 hit 0.523
candidates 30 hit 0.807
candidates 60 hit 0.927
popularity 30 hit 0.657
With 10 candidates, the hidden item is on the list 0.523 of the time. With 30, it's 0.807, the ceiling for everything after. The 30 most popular items only reach 0.657, so the embeddings are doing something the popular list can't. Sixty gets 0.927, but sixty is half of our catalogue. A longer list always finds more and gives the ranker more work, so this is a trade, not a free win.
How many numbers per seat?
One more dial: dim, the number of values in each embedding. You'd think more is better.
More numbers made it worse. My guess is that extra dimensions start copying noise from each person's few events, but we didn't test that. And be careful with this chart: it uses the same hidden events we score with. If you choose dim from it, you need a separate split to confirm it.
Common mistakes
- Recommending what the user already had. Set seen items to minus infinity before sorting.
- Assuming a bigger embedding is better. Here dim 32 scored 0.553 against 0.807 for dim 8.
- Tuning dim or list length on the test events. Use a separate validation split, then confirm.
- Comparing candidate lists of different lengths without a baseline. Popularity at the same length (0.657 at 30) tells you what the embeddings add.
Recap
| Step | Result |
|---|---|
| TruncatedSVD, dim 8 | users 300 x 8, items 120 x 8, from events only |
| Top 30 by matrix multiply | hit 0.807 (popularity at 30: 0.657) |
| Nearest neighbours of item 30 | all genre 5, similarity 0.969 to 0.94 |
| List length | 10: 0.523, 30: 0.807, 60: 0.927 |
| dim | peak at 8; 32 falls to 0.553 |
Try it yourself: in data.py, change the taste value a from 0.3 to 3, so tastes blur together, and run neighbours.py. Do neighbours still share a genre?
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Recommendations, Part 1: Two Stages, Candidates Then Ranking
Next →Recommendations, Part 3: The Ranker and Offline Metrics (Recall@k and nDCG)
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Project: Car Price Predictor End to End, from CSV to a FastAPI Price API
The whole ML workflow on 205 cars: clean the brand out of CarName, split first, audition five regressors on the same folds, tune the random forest, test once (RMSE 2,195, R2 0.939), save it and serve prices with FastAPI.
Fraud Scoring, Part 1: The Problem, the Metric and the Baseline
Before training a fraud model, write down what good means. On 6,000 synthetic validation transactions, a rule that never flags is 96.13% accurate and costs 23,200, flagging everyone costs 28,840, and a small contract.py fixes the rules first.
Fraud Scoring, Part 2: Training With Time Splits, Leak-Free Features and a Cost-Picked Threshold
Train the fraud model against its contract: a time split of 30,000 synthetic transactions, a card_n_1h feature that never looks ahead, XGBoost that pays 23,200 at 0.5, and a cost-picked threshold of 0.045 that brings validation to 14,955 and test to 16,765.
Fraud Scoring, Part 3: Serving It With FastAPI, Docker and a 50 ms Budget
A payment is waiting on the fraud score. Time each stage (the model takes 0.43 ms of a 3.3 ms request), then load test: p99 is 6.1 ms with one client and 163.3 ms with 32, against an example 50 ms budget. Then a Dockerfile, built and run once.