Learning path: End-to-End ML Use Cases: Fraud, Recommendations, Forecasting and Ticket Routing · Step 7 of 16
Recommendations, Part 3: The Ranker and Offline Metrics (Recall@k and nDCG)
Stage two re-orders 30 candidates with three features and a gradient boosted classifier trained on a second split. Recall@10 rises from 0.523 to 0.537, recall@30 can't move from 0.807, and nDCG@10 slips from 0.282 to 0.275. Here's why.
What you will learn
- Build ranker features for each candidate and train a gradient boosted ranker on a second split
- Measure recall at k and explain why the ranker can't change recall at the candidate count
- Compute nDCG with one hidden item per user and read what position adds
- Use feature importance to see why a ranker barely helps
Before you start
- Recommendations, Part 2: Candidate Generation With Embeddings
- Boosting: AdaBoost, Gradient Boosting and XGBoost
Stage one from Part 2 hands us 30 candidates per user. Today we put them in a careful order with a gradient boosted ranker, and then we score the result two ways: recall at k asks whether the right item made the list, and nDCG asks how high up it landed. The result is not quite what you'd hope for, and that's worth seeing.
Same synthetic data: 300 users, 120 items, seed 0, one hidden last event per user.
A shortlist interview
Think about hiring. A quick CV screen takes a big pile down to a shortlist. Then comes the interview: fewer people, more careful questions, and the panel puts them in order. You judge that panel two ways. Did the right person make the list? How close to the top did they end up? And the panel can only order who's in the room. If the screen threw out the right person, no interview brings them back.
The careful questions
The ranker's features are in ranker.py:
def features(model, hist, genre, user, cands, score):
pop = np.log1p(popularity(hist))
seen = hist[hist[:, 0] == user, 1]
share = np.bincount(genre[seen], minlength=6)
share = share / max(len(seen), 1)
return np.array([[score[i], pop[i], share[genre[i]]]
for i in cands])
Each candidate becomes one row of three numbers:
- The embedding score, the same one stage one used. For user 0 and item 30, that's 0.59.
- The log of how popular the item is.
- How much of this user's history is in the item's genre.
Three isn't many, and we'll come back to that.
Teaching the ranker without touching the test events
To train it we need answers, but the hidden test events stay locked. So we split again: each user's second-last event becomes the answer, and everything older is the history.
def train_ranker(hist, label, genre, n=30):
"""hist: older events; label: one later each."""
model = fit(hist)
X, y = [], []
for u, item, _ in label:
if not (hist[:, 0] == u).any():
continue
c, s = candidates(model, u, n)
X.append(features(model, hist, genre, u, c, s))
y += [int(i == item) for i in c]
clf = GradientBoostingClassifier(random_state=0)
clf.fit(np.vstack(X), y)
return clf
def rank(clf, model, hist, genre, user, n=30, k=10):
c, s = candidates(model, user, n)
p = clf.predict_proba(
features(model, hist, genre, user, c, s))[:, 1]
order = np.argsort(-p, kind="stable")[:k]
return [c[j] for j in order]
For each user we get 30 candidates. The label is 1 if that candidate is what they picked next, and 0 if not, so there's at most a single 1 in those 30 rows. One small classifier with default settings learns from all of them. rank scores the 30, sorts by predict_proba and keeps ten. The same "split by time so the label comes after the history" idea is in Time Splits and Group Splits.
What it did for one user
| Position | Candidates (stage one) | After the ranker |
|---|---|---|
| 1 | 65 | 65 |
| 2 | 7 | 7 |
| 3 | 30 | 30 |
| 4 | 92 | 97 |
| 5 | 97 | 5 |
| 6 | 71 | 92 |
| 7 | 25 | 60 |
| 8 | 5 | 25 |
| 9 | 60 | 71 |
| 10 | 43 | 32 (was 12th) |
Item 97 goes from fifth to fourth, item 5 jumps from eighth to fifth, item 92 falls from fourth to sixth. Item 32 climbs from twelfth into tenth, and item 43 falls off. Item 30, the hidden one, stays third. Plenty moved, and for this user the result didn't change. To judge it, we need everyone.
Recall at k
metrics.py has both metrics:
def recall_at(lists, test, k):
return np.mean([int(i) in lists[int(u)][:k]
for u, i, _ in test])
def ndcg_at(lists, test, k):
# one hidden item per user, so the best possible score is 1
gains = []
for u, i, _ in test:
top = lists[int(u)][:k]
hit = int(i) in top
gains.append(1 / np.log2(top.index(int(i)) + 2) if hit else 0)
return np.mean(gains)
Recall at k asks how much of what the user wanted is in the top k. With one hidden item per user, it's simply yes or no, averaged. Running python metrics.py:
popularity k=10 recall 0.263 ndcg 0.122
popularity k=30 recall 0.657 ndcg 0.215
candidates k=10 recall 0.523 ndcg 0.282
candidates k=30 recall 0.807 ndcg 0.350
cand+ranker k=10 recall 0.537 ndcg 0.275
cand+ranker k=30 recall 0.807 ndcg 0.340
embedding score 0.696
item popularity 0.111
genre share 0.192
At 10, the ranker gets 0.537 against 0.523 for candidates. That's four more users out of 300, a small win. At 30, candidates and ranker both score 0.807, exactly the same. That has to happen: the ranker has the same 30 items and only moves them around.
nDCG: position matters
Recall has a blind spot: being first and being tenth count the same. nDCG fixes that. A hit at position p earns 1 / log2(p + 1). A miss earns 0, and we average across users. Normally you'd divide by the best possible score, but with one hidden item, that best score is 1.
So recall says "did it make the list?" and nDCG says "did it make the list near the top?"
What the numbers said
| List | Recall@10 | nDCG@10 | Recall@30 | nDCG@30 |
|---|---|---|---|---|
| Popularity | 0.263 | 0.122 | 0.657 | 0.215 |
| Candidates | 0.523 | 0.282 | 0.807 | 0.350 |
| Candidates + ranker | 0.537 | 0.275 | 0.807 | 0.340 |
Personal lists more than double popularity's nDCG@10 (0.282 against 0.122). The ranker gets 0.275, slightly lower than candidates. It got four more users onto the list, but overall it placed the hits a little lower.
That stays as it is. This is one split on synthetic data and the gap is small, so we can't claim the ranker hurts. We can't claim it helps either.
Why so little? Look at what it relied on. The embedding score has an importance of 0.696, genre share 0.192 and popularity 0.111. It mostly repeats stage one's opinion. That points to the fix: better features are the first thing to try, and the ceiling of 0.807 says there's room. (How feature importance works, and its limits, is in Feature Importance: Permutation and SHAP.)
Common mistakes
- Training the ranker on the test events. Use an earlier event as the label so the test stays locked.
- Reporting recall at the candidate count. At k = 30 the ranker can't change it. Compare at the list size users see.
- Only reporting recall. nDCG shows whether hits land near the top, and here it told a different story.
- Feeding the ranker only what stage one knew. With the embedding score at 0.696 importance, the ranker mostly echoes stage one.
Recap
| Idea | Result |
|---|---|
| Ranker | 3 features per candidate, trained on the second-last event |
| Recall@10 | 0.523 to 0.537 (four more users) |
| Recall@30 | 0.807 for both, by design |
| nDCG@10 | 0.282 to 0.275, a small drop on one split |
| Importance | embedding 0.696, genre 0.192, popularity 0.111 |
Try it yourself: in ranker.py, give the classifier n_estimators=300 and run metrics.py again. Does nDCG@10 move?
Next: Part 4, serving recommendations with a cache and a fallback.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Recommendations, Part 2: Candidate Generation With Embeddings
Next →Recommendations, Part 4: Serving With FastAPI, a Cache and a Popular Fallback
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.