Learning path: End-to-End ML Use Cases: Fraud, Recommendations, Forecasting and Ticket Routing · Step 5 of 16
Recommendations, Part 1: Two Stages, Candidates Then Ranking
How does a shop pick ten items out of millions? A cheap score takes 4.83 ms over a million items where a careful one takes 1,246 ms, so stage one narrows 120 items to 30 and stage two orders them. Hit rate: popularity 0.263, two stages 0.537, ceiling 0.807.
What you will learn
- Measure why a careful model can't score every item for every user
- Explain the two-stage funnel and why stage one sets the ceiling
- Recognise implicit feedback and the popularity lean in event data
- Handle cold-start users with a popularity fallback
Before you start
- Recommender Systems: Item-Based Collaborative Filtering
- Basic NumPy
This is the second end-to-end use case: recommendations. Over four parts we build a small recommender, check it offline and serve it. Today answers one question. How does a shop pick ten things for you out of millions?
The project's data is synthetic: 300 users, 120 items in 6 genres, seed 0. It has 5,663 events, who had what and in what order.
A buyer and an assistant
Think about a bookshop. Far away there's a warehouse, say a million books. A buyer goes through it quickly, looks at the covers and the sales figures, and picks five hundred for this shop. Nobody can read a million books, so the buyer keeps it rough.
Now you walk in. The assistant asks what you read last, thinks about those five hundred, and puts three in your hands. The first step is quick because it has to look at everything. The second is careful because it only looks at a few.
Why not score everything?
Is careful scoring really that slow? score_cost.py times two ways of scoring for one user. The cheap way is one matrix multiply, items @ user. The careful way is a gradient boosted classifier, predict_proba, one row per item:
rng = np.random.default_rng(0)
user = rng.normal(size=8)
for size in [120, 10_000, 1_000_000]:
items = rng.normal(size=(size, 8))
rows = rng.normal(size=(size, 3))
cheap = ms(lambda: items @ user)
careful = ms(lambda: clf.predict_proba(rows))
print(f"{size:>9} items cheap {cheap:9.2f} ms"
f" careful {careful:10.2f} ms")
print("careful, 300 rows", round(ms(
lambda: clf.predict_proba(rng.normal(size=(300, 3)))), 2), "ms")
120 items cheap 0.04 ms careful 2.09 ms
10000 items cheap 0.15 ms careful 14.38 ms
1000000 items cheap 4.83 ms careful 1246.07 ms
careful, 300 rows 2.09 ms
With 120 items nobody would notice either. At a simulated million, cheap takes about 5 ms and careful takes about one and a quarter seconds. That's for one person opening one page, and we haven't even built the features yet. These catalogues are random numbers, timed once on one CPU, so yours will differ. Look at the shape: cheap can look at everything, careful can't. Give careful only 300 rows and it's back to about 2 ms.
The funnel
Stage one is candidates: a cheap score over every item, keeping a few hundred (here, 120 down to 30). Stage two is the ranker: it looks only at those few, uses more information, and the top ten become the list. And one rule comes with it: stage one sets the ceiling.
The two stages in code
Here's the same shape in evaluate.py, inside run:
def run(k=10, n=30):
events, genre = make_data()
train, test = split(events)
older, label = split(train)
users = sorted(set(int(u) for u in test[:, 0]))
pop = {u: recommend(train, u, k) for u in users}
model = fit(train)
cand = {u: candidates(model, u, n)[0] for u in users}
clf = train_ranker(older, label, genre, n)
top = {u: rank(clf, model, train, genre, u, n, k)
for u in users}
return events, genre, train, test, pop, cand, top
fit trains the embeddings and candidates gets 30 items per user. That's stage one, built in Part 2. train_ranker and rank re-order those 30 and keep ten. That's stage two, built in Part 3.
To check it, we hide each user's last event and ask: is it on the list? For user 0, the hidden item is item 30. Stage one puts it third, and stage two keeps it third. Across all 300 users:
The popular list finds the hidden item 0.263 of the time, the top ten candidates 0.523, the ranker's ten 0.537. Anywhere in all 30 candidates, it's 0.807. That's the ceiling.
Nobody rates anything
Notice what this data doesn't have: star ratings. We only know what people did. In candidates.py, one line sets a 1 wherever a user had an item:
m = np.zeros((N_USERS, N_ITEMS))
m[train[:, 0], train[:, 1]] = 1
That's implicit feedback. Here it's 5,363 ones in a grid of 36,000 cells. Everything else is a zero, and here's the catch: a zero doesn't mean they disliked it. Maybe they never saw it. We can't tell.
And the ones lean towards what's already popular. The top ten items, out of 120, hold about 24% of the training events. So we never get a clear no, and popular items get extra votes. Keep both in mind whenever you read a score. (The ratings-based version, with explicit stars, is in Recommender Systems: Collaborative Filtering.)
Cold start
The second problem is the new user. Thirty of our users have only one event in training, so stage one has almost nothing to go on.
| Users | Popular, 10 | Two stages, 10 |
|---|---|---|
| 30 users with one training event | 0.333 | 0.467 |
| Users with more history | 0.256 | 0.544 |
Thirty is a small group: that's 10 hits against 14. More events do help. And with no events at all? Every candidate score comes out 0, so the order means nothing. There, the popular list is the sensible answer. That's why you keep the baseline around, even after you've beaten it. Part 4 wires exactly that fallback into the service.
Common mistakes
- Running the careful model over the whole catalogue. 1,246 ms for one user at a million items, before features.
- Tuning the ranker while ignoring stage one. The ranker can't beat the candidate ceiling (0.807 here).
- Reading a zero as a dislike. In implicit data it usually means "never seen".
- Dropping the popularity baseline. It's the answer for users with no events.
Recap
| Idea | Number from this project |
|---|---|
| Cheap vs careful, 1M simulated items | 4.83 ms vs 1,246.07 ms |
| Funnel | 120 items, 30 candidates, 10 on the list |
| Hit rate at 10 | popular 0.263, candidates 0.523, ranker 0.537 |
| Ceiling (30 candidates) | 0.807 |
| Cold start (30 users) | popular 0.333, two stages 0.467 |
Try it yourself: in evaluate.py, change n from 30 to 10 and run it again. What happens to the ceiling, and does the ranker still have anything to do? The project files are in the community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Fraud Scoring, Part 4: Release and Monitoring With Shadow, Drift and Late Labels
Next →Recommendations, Part 2: Candidate Generation With Embeddings
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.