Learning to rank (LTR)
Train a model to order candidates for a query or user so the best land on top: pointwise, pairwise or listwise losses, LambdaMART as the workhorse, NDCG@k to measure, debiased clicks as labels.
Analogy: A sommelier finds it easier to say "A beats B" than to give each wine an absolute score, and what matters is getting the top three right, not #40 vs #41.
How it works
- It runs after retrieval: score ~100–1,000 candidates with rich features, then apply diversity and business rules.
- Pointwise is simple and calibrated but blind to order; pairwise learns order but weighs every rank equally.
- LambdaMART scales pairwise gradients by the NDCG change of each swap, so errors at the top cost most.
- NDCG@k rewards the top with a log discount; MRR fits one-answer tasks.
- Raw clicks carry position bias; weight them by 1/propensity or the model relearns the old ranker.
Check yourself
Answer to mark it learned; your answers aren't scored.
Your new LambdaMART ranker beats the old one by a wide margin on offline NDCG@10, but the A/B test is flat. Labels are human grades 0–4, and you split the (query, doc) rows randomly 80/20. Most likely cause?
Go deeper
Full explanation
Learning to rank trains a scoring function f(query, item) whose order matches relevance. It sits after retrieval: BM25 or ANN return ~100–1,000 candidates, the LTR model scores each with rich features (text match, embedding similarity, quality, popularity, personalization), then a re-ranker applies diversity and business rules.
Three ways to define the loss:
- Pointwise: predict each item's label alone (regression, or pCTR via log loss). Simple and calibrated, but blind to relative order.
- Pairwise: for two items of one query, learn which goes higher (RankNet). Better order, but an error at rank 1 costs the same as at rank 50.
- Listwise: optimize the list. LambdaMART scales RankNet's pairwise gradients by the |ΔNDCG| of swapping each pair and boosts trees on them: the default for feature-based search ranking.
Metrics reward the top: NDCG@k (graded gains, log discount, normalized by the ideal order), MRR (1/rank of the first relevant hit, for one-answer tasks), MAP (binary relevance, all relevant hits).
Clicks are biased labels: users click higher positions regardless of relevance, so a model trained on raw clicks relearns the old ranker. Unbiased LTR estimates each position's examination propensity (randomized swaps, intervention harvesting) and weights clicks by 1 / propensity (IPS), or trains with position as a feature and fixes it at serving.
Code LambdaMART with XGBoost, evaluated on NDCG@10
import xgboost as xgb
# One row per (query, doc): features + graded label 0-4 (or clicks); rows sorted by qid
X_tr, y_tr, qid_tr = load_split("train") # split by query, never by row
X_va, y_va, qid_va = load_split("valid")
ranker = xgb.XGBRanker(
objective="rank:ndcg", # LambdaMART: pairwise lambdas weighted by |delta NDCG|
lambdarank_pair_method="topk", # build pairs around the top of each list...
lambdarank_num_pair_per_sample=10, # ...truncated at k=10, what users actually see
eval_metric=["ndcg@10", "map@10"],
n_estimators=2000, learning_rate=0.05, max_depth=6,
early_stopping_rounds=100,
# lambdarank_unbiased=True, # click labels: learn position bias (XGBoost >= 2.0)
)
ranker.fit(X_tr, y_tr, qid=qid_tr, eval_set=[(X_va, y_va)], eval_qid=[qid_va])
def rank(query, candidates, k=10):
# Serve: score the ~1,000 retrieved candidates for one query, keep the top k
scores = ranker.predict(features(query, candidates))
order = scores.argsort()[::-1][:k]
return [candidates[i] for i in order]Real example
A marketplace ranks ~1,000 BM25 + ANN candidates per query with LambdaMART over ~200 features. Retrained on 30 days of raw clicks, it gains 4% offline NDCG@10 but loses the A/B test: most clicks sat in positions 1–3, so it mostly relearned the old order. The team swaps random adjacent pairs in the top 5 on 1% of traffic to estimate examination propensities, weights clicks by 1/propensity, and validates on human-graded queries. The next A/B test wins on purchases per search.
Trade-offs +3 · −3
+ You gain
- Optimizes what users experience, the top of the list, instead of per-item accuracy.
- LambdaMART is cheap to train and serve and uses hundreds of heterogeneous features.
- Click logs give labels at scale for free, once debiased.
− You pay
- Click labels carry position, selection and trust bias; debiasing needs randomization traffic.
- Pairwise and listwise scores aren't probabilities, so they can't feed auctions or blends as-is.
- Offline NDCG often disagrees with online metrics; you still need interleaving or A/B tests.
Use it when
The ranking stage of search, recommendations, feeds and RAG, when you have relevance judgments or logged interactions and only the top k positions matter.
Avoid it when
When the score feeds another computation (ad auctions, multi-objective blends): use calibrated pointwise models. With tiny traffic and no labels, a tuned BM25 plus a cross-encoder may be enough.
Numbers to know 5
- NDCG discount 1/log2(rank + 1): rank 1 = 1.0, rank 3 = 0.5, rank 10 ≈ 0.29.
- An ensemble of LambdaMART rankers won Track 1 of the 2010 Yahoo! Learning to Rank Challenge (Burges, 2010).
- MSLR-WEB30K benchmark: ~30K queries, 136 features per query–document pair, labels 0–4.
- Rule of thumb: retrieve 100–1,000, rank with LTR, show 10–20.
- XGBoost's
rank:ndcguses gain 2^rel − 1 by default, so labels must be ≤ 31.
Common pitfalls 4
- Treating raw clicks as relevance: the model learns position bias and the old ranker's order.
- Splitting train and test by row instead of by query, so the same query leaks across sets.
- Queries with no relevant item have IDCG = 0; libraries score them as 1 or 0, silently skewing the average.
- Measuring NDCG over the whole list when the UI shows 10: evaluate @k at the cutoff users see.
Interview questions 2
Answer out loud first, then reveal.
Pointwise, pairwise or listwise: which would you use for a ranker?Show answer
It depends on what consumes the score. For search with graded labels and hand-built features, I start with LambdaMART: it targets the top of the list through ΔNDCG-weighted pairs and is cheap to train and serve. When the score feeds another computation, like an auction's bid times pCTR or a feed's weighted blend of pLike, pComment and pWatch, I go pointwise with calibrated multi-task probabilities, because order alone isn't enough. Pairwise losses fit preference data such as 'A clicked over B'. Whatever the loss, I judge it on NDCG@k offline and interleaving or an A/B test online.
You train a ranker on click logs. What goes wrong, and how do you fix it?Show answer
Clicks are biased: position bias (people click what's on top), trust bias, and selection bias (items never shown get no clicks). A model trained on raw clicks relearns the old ranker and locks in a feedback loop. I'd estimate examination propensity per position with small randomized swaps or by harvesting existing A/B tests, then weight clicks by inverse propensity, as in Joachims' unbiased LTR, or use XGBoost's unbiased LambdaMART. Alternatively, train with position as a feature and set it to a constant at serving. I'd add exploration for unseen items and validate on human-graded queries.