Learning to rank
When the answer is an order, not a label: queries, documents and graded relevance; precision at k, MAP, MRR and NDCG; why the metric cannot be trained directly; pointwise, pairwise and listwise losses (RankNet, ListNet); LambdaRank and LambdaMART, whose forces are weighted by the change in NDCG; clicks and position bias.
An order, not a label
The topic Anomaly detection ended with a score for every point and an analyst who reads the list from the top. Only the order of the scores mattered there: a detector is useful if the true anomalies come first, and nobody reads the thousandth line. That was already a ranking problem, solved without labels. This topic adds labels. A search engine, a product catalogue and a news feed all return an ordered list, and people judge the list by its top. The answer is an order, not a label.
Ranking data are grouped. A query comes with candidate documents, usually a few hundred that a cheap first stage picked out of millions. Document has a feature vector that describes the pair (query, document). An assessor who read both gives it a graded relevance label , from irrelevant to perfect. Binary relevance, , is the special case. A model gives each document a score , and the ranking sorts the documents by decreasing score. We write for the label of the document in position .
The features come in three kinds:
- Query features depend only on the query: its length, its frequency in the logs. They are the same for every document of the query.
- Document features depend only on the document: its length, its freshness, its link-based importance such as PageRank, the stationary distribution of a random surfer from the topic Markov chains.
- Query–document features measure the match: a text-matching score such as BM25, the cosine between embeddings, the share of query words in the title.
Orders are compared only within a query. Whether a page about the jaguar the animal should come before one about Jaguar the car depends on what was asked. So adding a constant to all scores of one query changes nothing, and scores mean something only up to a shift per query.
Two practical rules follow. Validation splits by query, never by row: this is the group split of the topic Validation and overfitting, and documents of one query on both sides would be the train–test contamination of Data, features and leakage. And a learned ranker is usually the second stage of a cascade. A fast retriever narrows millions of documents to hundreds, and the ranker orders those.
Precision at k, MAP and MRR
Classification metrics count errors on single objects. A ranking metric must weigh errors by position. An irrelevant document in first place costs more than one in fortieth place, because the reader sees the first and never the fortieth. Every metric below is computed per query and then averaged over queries, so each query counts equally, however long its list.
The running example is one query with six documents. In the order the model ranks them, their labels are
For the binary metrics a document is relevant if : here positions 2, 3 and 5.
Precision at already appeared in the topic Classification metrics as the call-centre budget. It is the share of relevant documents among the first :
Here , and . It is easy to read, but it ignores the order inside the top .
Average precision is the AP of the same topic, the area under the precision–recall staircase. It averages the precision at the position of each relevant document, over all relevant documents of the query:
With relevant documents at positions 2, 3 and 5, . A relevant document that was never retrieved adds precision 0 but still counts in , so AP punishes misses. Its mean over queries is MAP. Truncated versions, AP@, divide by in some libraries and by in others, so check which one a reported number used.
Reciprocal rank looks only at the first relevant document: , where is its position, and 0 if there is none. Here . Its mean over queries, MRR, suits tasks with one right answer, such as a question with one passage that answers it.
A second query with binary labels in ranked order has and . Over the two queries and .
Graded relevance: NDCG
Binary metrics lose the difference between a perfect answer and a passable one. Discounted cumulative gain keeps it. Each document adds a gain that grows with its label, divided by a discount that grows with its position:
The exponential gain makes one perfect document worth more than several fair ones. DCG has no fixed scale: a query with many relevant documents reaches higher values than a query with one good answer. NDCG divides by the DCG of the ideal order, the documents sorted by label, so that 1 means a perfect ranking:
For the running example:
| position | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| label | 0 | 3 | 1 | 0 | 2 | 0 |
| gain | 0 | 7 | 1 | 0 | 3 | 0 |
| discount | 1 | 0.631 | 0.5 | 0.431 | 0.387 | 0.356 |
| contribution | 0 | 4.417 | 0.5 | 0 | 1.161 | 0 |
So . The ideal order gives , and . At the label-2 document drops out of the numerator, and . The same in code:
import numpy as np
def dcg(labels, k):
y = np.asarray(labels, float)[:k]
return ((2 ** y - 1) / np.log2(np.arange(2, len(y) + 2))).sum()
ranked = [0, 3, 1, 0, 2, 0]
ideal = sorted(ranked, reverse=True)
for k in (3, 6):
print(k, round(dcg(ranked, k), 3), round(dcg(ranked, k) / dcg(ideal, k), 3))3 4.917 0.523
6 6.077 0.647Conventions change the numbers. NDCG is undefined for a query without relevant documents; some code drops such queries from the mean, some scores them 0 or 1. scikit-learn's ndcg_score uses the label itself as the gain and gives 0.665 on this list. State the convention next to the number.
The AUC from the topic Classification metrics is also a ranking metric: the share of (relevant, irrelevant) pairs that the scores put in the right order. Here pairs, 5 of them in the right order, so AUC . Every pair counts the same wherever it sits in the list. This is why a classifier with a good AUC can still put junk at the top.
Why the metric cannot be trained directly
Every metric above depends on the scores only through the order they induce. A small change of one score either keeps the order, and the metric with it, or swaps two neighbours, and the metric jumps. As a function of the scores, and so of the model's parameters, NDCG is piecewise constant. Its gradient is zero almost everywhere and undefined at the jumps, and gradient descent gets no signal from it.
The topic Linear classifiers and surrogate losses met the same wall with the 0–1 loss, and the answer is the same. Train a smooth surrogate whose minimum tends to improve the metric, and use the metric itself for validation and early stopping. The surrogates differ in what they look at: one document, a pair, or the whole list.
The simplest, pointwise approach forgets that the task is ranking. Treat every (query, document) pair as an object with target , fit a regression, and sort by the prediction. Any model of the course works, gradient boosting included, and the result is a strong baseline.
Its loss, however, measures the wrong thing. Take two documents of one query with labels 1 and 2. Predictions are close to the labels, with mean squared error , but they put the documents in the wrong order. Predictions are far from the labels, with mean squared error , but the order is right. Regression prefers the first. A pointwise loss also spends effort on things that never change the order: the exact score of every irrelevant document at the bottom, and the overall level of a query's labels, which shifts all its scores together.
Pairs and lists: RankNet and ListNet
Ranking is a statement about pairs: document should come before document whenever . RankNet (Burges et al., 2005) models the probability of this preference with the difference of the two scores,
and maximizes the likelihood of the preferences in the labels. For every pair of one query with the loss is the negative log-likelihood
This is the log-loss of the topic Logistic regression, applied to pairs. With a linear score it is literally logistic regression on the differences , with no intercept, since a common shift of the scores cancels. With the hinge loss instead, it is RankSVM. A misordered pair with and costs . At equal scores the cost is ; ordered by a margin of 2 it is . Since , the loss bounds the number of misordered pairs, the count behind the AUC.
The derivative of with respect to is negative, and the one with respect to is its opposite. Write for the size of this push. It is close to 1 for a badly misordered pair and close to 0 for a pair ordered with a large margin. A gradient step raises and lowers by . Summing over all pairs that contain a document gives its total force
positive if the document should move up. The forces are the negative gradient of the total loss in the scores. A network then needs one backward pass per document, not per pair.
A listwise loss compares the whole predicted list with the ideal one. As for classes, turn scores into a distribution. ListNet (Cao et al., 2007) uses the probability that each document comes first, a softmax over the list:
The labels give a target in the same way, and the loss is the cross-entropy . It is the softmax and cross-entropy of Multiclass and multilabel classification, over documents instead of classes. Scores give . With labels the target is , and the cross-entropy, , asks to swap the last two. Pairs or lists, both losses treat all positions alike: nothing in them says that first place matters more than fifth.
LambdaRank: forces weighted by NDCG
On the running example RankNet gets its priorities wrong. Give the six documents scores in their current order. RankNet's strongest upward force, , goes to the label-2 document in fifth place, which loses three pairs to weaker documents above it. NDCG cares more about the label-3 document in second place: one swap with the irrelevant document at the top would raise NDCG more than anything that can happen at position 5.
LambdaRank (Burges, Ragno and Le, 2006) starts from an observation. Training needs only the forces, not a loss whose gradient they are. So write the forces down directly: keep RankNet's force for each pair and multiply it by how much the pair matters to the metric,
where is the change in NDCG if documents and swapped places in the current ranking and all others stayed put. The per-document forces are summed as before.
The swap changes only two terms of the DCG. With gains and discounts for documents at positions and ,
Swapping the label-3 document at position 2 with the irrelevant one at position 1 changes NDCG by . Swapping it with the label-2 document at position 5 gives . Swapping the documents with labels 1 and 2 at positions 3 and 5 gives only . The total forces:
| position | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| label | 0 | 3 | 1 | 0 | 2 | 0 |
| RankNet | ||||||
| LambdaRank |
LambdaRank's strongest upward push now goes to second place. Both push the irrelevant document at the top down hardest.
Is there a loss behind the lambdas? For a fixed order they are the gradients of a RankNet loss with weights . But the weights change whenever the order changes, so no single smooth function of the scores has them as its gradient (Burges, 2010). In practice training with them appears to reach a local maximum of NDCG. Replace by the change in MAP or MRR, and the same recipe trains for that metric.
LambdaMART: boosting on the forces
The topic Gradient boosting needs nothing but the gradient of the loss with respect to the current scores. Each new tree is fitted to the negative gradients, and its leaves take a Newton step: the XGBoost leaf value with gradient and curvature sums and . The lambdas play exactly this role, even without a loss behind them. LambdaMART (Wu et al., 2010) is gradient boosting of regression trees with the targets replaced by the forces. In this block are the forces, and the leaf penalty is zero.
One stage goes like this. For every query, sort the documents by the current scores . Compute each document's force and its curvature
over all pairs that contain . Fit a regression tree by least squares to the of all documents of all queries. Set the value of leaf to , and add the tree with a learning rate: .
The forces of one query sum to zero: each pair adds to one document and to the other. A split on a query feature sends whole queries to each side, so each side still has forces summing to zero, and the split reduces no squared error. The overall level of a query, which a pointwise booster has to model, gives LambdaMART nothing to fit.
A synthetic test: 300 training and 1,000 test queries of 30 documents with six features, one of them a query feature that shifts every label of its query. NDCG@5 on the test queries:
| ranker | NDCG@5 | split gain on the query feature |
|---|---|---|
| random order | 0.190 | — |
| linear, pointwise (ridge) | 0.647 | — |
| linear, RankNet | 0.646 | — |
| 100 trees of depth 3, pointwise | 0.766 | 51% |
| 100 trees of depth 3, LambdaMART | 0.814 | 0% |
The two linear models tie. The pointwise booster spends half of its split gain on the query feature. On data without a query-level effect the two boosters come much closer: LambdaMART's edge is real but often small, and a tuned pointwise booster is a hard baseline. In libraries the method is the lambdarank objective of LightGBM and rank:ndcg of XGBoost; both need the query of each row.
Clicks and position bias
Assessor labels are expensive, and a search engine sees millions of clicks a day. Clicks are labels too, but biased ones. A user clicks only on what they examine, and people examine the top of a list far more than the bottom. In an eye-tracking study, Joachims et al. (2005) swapped the top two results for some users: the first position still drew more clicks than its relevance justified. A model trained on raw clicks learns to put first whatever was shown first.
The position-based model separates two steps. A click requires examination, examination depends only on the position , and once examined, the click depends only on the document. By the chain rule of probability,
where the propensity is the probability of examining position , and the second factor stands for relevance. Inverse propensity scoring divides each click by the propensity of its position. This is importance sampling from the topic Monte Carlo methods, with the logged ranking as the proposal. The estimate is unbiased under the model if every position used has and the propensities are right. The propensities come from small randomized experiments, such as swapping two positions for a fraction of users.
A simulation: a document that 30% of users click once they examine it is shown 100,000 times at position 1, always examined, and 100,000 times at position 3, examined 40% of the time. The click rates are 0.299 and 0.119, so raw clicks call it two and a half times worse at position 3. Divided by the propensities 1.0 and 0.4, the estimates are 0.299 and 0.297: the same document.
Whatever the labels, the final judgement of a new ranker is an online experiment, the A/B test of Hypothesis tests and A/B testing.
This topic assumed that every (query, document) pair has features and that an assessor can judge relevance. Recommendation is ranking where the query is a person: the next film, the songs of a playlist, the products for a basket. Often nothing describes either side, and all we have is a record of who chose what. The topic Recommender systems learns from that record alone: the user–item matrix, the neighbours and low-rank factors hidden in it, and evaluation with the ranking metrics of this topic.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Answers are saved on the server and tied to this browser until you sign in.