Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Learning pathEnd-to-End ML Use Cases: Fraud, Recommendations, Forecasting and Ticket Routing
  1. 1
    Fraud Scoring, Part 1: The Problem, the Metric and the Baseline
  2. 2
    Fraud Scoring, Part 2: Training With Time Splits, Leak-Free Features and a Cost-Picked Threshold
  3. 3
    Fraud Scoring, Part 3: Serving It With FastAPI, Docker and a 50 ms Budget
  4. 4
    Fraud Scoring, Part 4: Release and Monitoring With Shadow, Drift and Late Labels
  5. 5
    Recommendations, Part 1: Two Stages, Candidates Then Ranking
  6. 6
    Recommendations, Part 2: Candidate Generation With Embeddings
  7. 7
    Recommendations, Part 3: The Ranker and Offline Metrics (Recall@k and nDCG)
  8. 8
    Recommendations, Part 4: Serving With FastAPI, a Cache and a Popular Fallback
  9. 9
    Demand Forecasting, Part 1: The Business Problem, a Price per Mistake and the Line to Beat
  10. 10
    Demand Forecasting, Part 2: Walk-Forward Backtesting, Ridge vs Boosting and the Slices an Average Hides
  11. 11
    Demand Forecasting, Part 3: The Nightly Batch Pipeline That Survives a Crash
  12. 12
    Demand Forecasting, Part 4: Serving the Forecasts, the Outcome Join and a Retrain Rule
  13. 13
    Ticket Routing, Part 1: A Safe Split, Keyword Rules and a TF-IDF Baseline
  14. 14
    Ticket Routing, Part 2: Fine-Tuning a Small Encoder on a CPU, With a Run Log and Honest Ranges
  15. 15
    Ticket Routing, Part 3: Quantise to int8, Host Behind FastAPI and Measure the Server
  16. 16
    Ticket Routing, Part 4: Canary, Automatic Rollback and "Does Your Small Model Reason?"
  1. Blog
  2. /
  3. Machine Learning
  4. /
  5. End-to-End Use Cases

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.

Chaand Sheikh

·27 November 2026End-to-End Use Cases

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:

  1. The embedding score, the same one stage one used. For user 0 and item 30, that's 0.59.
  2. The log of how popular the item is.
  3. 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

PositionCandidates (stage one)After the ranker
16565
277
33030
49297
5975
67192
72560
8525
96071
104332 (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.

nDCG gain by position 1.0001 0.6312 0.5003 0.4314 0.3875 0.3566 0.3337 0.3158 0.3019 0.28910 position of the hit in the list
Gains computed from the formula. User 0's hidden item sits at position 3, so it earns 0.5.

So recall says "did it make the list?" and nDCG says "did it make the list near the top?"

What the numbers said

ListRecall@10nDCG@10Recall@30nDCG@30
Popularity0.2630.1220.6570.215
Candidates0.5230.2820.8070.350
Candidates + ranker0.5370.2750.8070.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

IdeaResult
Ranker3 features per candidate, trained on the second-last event
Recall@100.523 to 0.537 (four more users)
Recall@300.807 for both, by design
nDCG@100.282 to 0.275, a small drop on one split
Importanceembedding 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 →
← Previous
Recommendations, Part 2: Candidate Generation With Embeddings
Next →
Recommendations, Part 4: Serving With FastAPI, a Cache and a Popular Fallback
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool
Go deeper with a course

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.

On this page
  • A shortlist interview
  • The careful questions
  • Teaching the ranker without touching the test events
  • What it did for one user
  • Recall at k
  • nDCG: position matters
  • What the numbers said
  • Common mistakes
  • Recap
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool
Go deeper with a course

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.