Learning to rank: from pairwise preferences to a list
排序学习
Train a shared scalar RankNet-style scorer, verify its gradient and distinguish pairwise loss from NDCG.
learning-to-rankWhich result should appear first?
A search engine can retrieve several relevant pages and still show them in an unhelpful order. Learning to rank learns a scoring rule for ordering candidates within a query. Its training observations can be relevance grades, pairwise preferences or feedback collected from users.
The query matters. A document highly relevant to one question can be irrelevant to another. Comparisons and evaluation should preserve their query groups. We will train one shared scalar weight on two tiny queries, inspect its gradient, and then measure the resulting rankings. Read logistic regression and gradient descent first.
Learn score differences from preferences
Pointwise methods predict an individual relevance target, pairwise methods compare candidates, and listwise methods use a list-level training objective. These categories describe objectives, not whether the scorer must be a neural network or a tree.
For an ordered pair where document i is preferred to j, let Δ=sᵢ−sⱼ. A logistic preference model and its negative log likelihood are:
The RankNet paper, Section 3, develops a probabilistic pairwise cost, including soft preference targets. Here every retained unequal-grade pair has a hard target; equal-grade pairs are omitted. The scalar linear scorer is a teaching simplification, not the paper’s full neural model.
With sᵢ=w xᵢ, differentiating the loss gives:
We average pairs within each query, then average queries, so a query with many pairs does not automatically dominate. This weighting is an explicit design choice. A scorer intercept shared within a query cancels from every difference. Likewise, adding the same constant to all scores in a query leaves the pairwise loss and ordering unchanged.
Check the first gradient by hand
The first query has features(0,1,2) and relevance grades(2,1,0). Its preferred-pair feature differences are−1,−2,−1. At w=0, all preference probabilities are 1/2. The average loss is log 2 and the gradient is(1/2+1+1/2)/3=2/3. A descent step moves w negative, making lower feature values rank higher, as these grades require.
The second query has features(1,3), grades(1,0). Both queries favor a negative weight. The demonstration starts at w=1 and uses λ=0.1. The penalty gives a finite optimum even when increasing the magnitude of a separating score would keep reducing the unregularized pairwise loss.
Train a small scorer and evaluate each query
This complete Python 3.12 program uses a stable softplus expression and a stable logistic derivative. It actually updates the shared parameter; evaluation sorts the resulting scores. Tied scores are ordered by original index, an explicit deterministic convention.
from math import exp, isfinite, log1p, log2
def real(v,bound):
return type(v) in (int,float) and isfinite(v) and abs(v)<=bound
def pairwise_objective(queries, weight, penalty=.1):
queries=[list(q) for q in queries]
if not 1<=len(queries)<=8 or not real(weight,1000) or not real(penalty,10) or penalty<0:
raise ValueError('bounded queries, weight and nonnegative penalty required')
losses=[];gradients=[]
for query in queries:
if not 2<=len(query)<=16 or any(len(row)!=2 or not real(row[0],10) or type(row[1]) is not int or not 0<=row[1]<=4 for row in query):
raise ValueError('each query needs two to16 feature/grade pairs')
loss=gradient=0.;count=0
for xi,ri in query:
for xj,rj in query:
if ri<=rj:continue
difference=xi-xj;margin=weight*difference
loss+=max(-margin,0)+log1p(exp(-abs(margin)))
wrong=exp(-margin)/(1+exp(-margin)) if margin>=0 else 1/(1+exp(margin))
gradient-=wrong*difference;count+=1
if not count:raise ValueError('each training query must contain an unequal-grade pair')
losses.append(loss/count);gradients.append(gradient/count)
return sum(losses)/len(queries)+penalty*weight*weight/2,sum(gradients)/len(queries)+penalty*weight
def fit_ranker(queries, steps=300, rate=.1):
queries=[list(q) for q in queries]
if type(steps) is not int or not 1<=steps<=2000 or not real(rate,.1) or rate<=0:
raise ValueError('one to2000 steps and learning rate in(0,.1] required')
weight=1.;history=[pairwise_objective(queries,weight)[0]]
for _ in range(steps):
_,gradient=pairwise_objective(queries,weight)
weight-=rate*gradient;history.append(pairwise_objective(queries,weight)[0])
return weight,history
def ndcg(scores, grades, k):
scores,grades=list(scores),list(grades);n=len(scores)
if not 1<=n<=16 or len(grades)!=n or any(not real(v,1e6) for v in scores) or any(type(r) is not int or not 0<=r<=4 for r in grades):
raise ValueError('matching bounded scores and integer grades required')
if type(k) is not int or not 1<=k<=n:raise ValueError('valid integer cutoff required')
order=sorted(range(n),key=lambda i:(-scores[i],i))
dcg=sum((2**grades[i]-1)/log2(pos+2) for pos,i in enumerate(order[:k]))
ideal=sum((2**r-1)/log2(pos+2) for pos,r in enumerate(sorted(grades,reverse=True)[:k]))
return dcg/ideal if ideal else None
if __name__=='__main__':
queries=[[(0,2),(1,1),(2,0)],[(1,1),(3,0)]]
weight,history=fit_ranker(queries)
print('initial and final objective:',f'{history[0]:.12f}',f'{history[-1]:.12f}')
print('fitted scalar weight:',f'{weight:.12f}')
for i,query in enumerate(queries):
x=[v for v,_ in query];grades=[r for _,r in query]
print('query',i,'NDCG before/after:',f'{ndcg(x,grades,len(x)):.12f}',f'{ndcg([weight*v for v in x],grades,len(x)):.12f}')
print('zero-weight single-query loss/gradient:',*[f'{v:.12f}' for v in pairwise_objective([queries[0]],0)])
Output:
initial and final objective: 1.905705903201 0.210818201574
fitted scalar weight: -1.407893063105
query 0 NDCG before/after: 0.586882671436 1.000000000000
query 1 NDCG before/after: 0.630929753571 1.000000000000
zero-weight single-query loss/gradient: 0.693147180560 0.666666666667
The input contract is 1–8 queries,2–16 documents per training query, finite bounded scalar features and integer grades 0–4. Each training query must contain an unequal-grade pair. The code reports its training objective; it does not claim that a fixed learning rate is stable for every permitted dataset. The tests verify objective improvement for the displayed dataset and compare gradients with central finite differences.
Enumerating pairs costs O(Σn_q²) per objective/gradient evaluation. Sorting for evaluation costs O(n_qlogn_q). A production scorer has its own feature and model costs; pair sampling and score-gradient aggregation can reduce work. This program intentionally keeps all tiny-query pairs visible.
A smooth loss and a useful ranking are different quantities
For nonnegative relevance grades r, one common metric is:
IDCG uses the ideal descending grade order for that query. When all grades are zero, its denominator is zero; our helper returns None. Other systems may define a convention, which must be stated before averaging queries. Burges’s 2010 overview, Sections 3–4, discusses ranking metrics and their mismatch with uniform pairwise objectives.
NDCG changes with rank positions, while the logistic loss changes with score gaps even when the order stays fixed. Reducing the training loss does not guarantee that every query’s NDCG increases. Our two training rankings reach NDCG 1, but that says nothing about unseen queries or unseen candidate distributions.
Clicks are affected by position and exposure; an unclicked item may never have been examined. Split evaluation by query or another justified deployment unit to avoid leakage. Candidate generation also limits what any ranker can recover. Report the cutoff, gain convention, tie policy and aggregation weights alongside the metric.
Follow the preference, then check the list
- What is the first query’s gradient at zero weight?
Answer 1: 2/3; descent moves the weight negative.
- Does adding 10 to every score in one query change pairwise loss?
Answer 2: No. Every score difference is unchanged.
- Does a lower pairwise loss force higher NDCG for every query?
Answer 3: No. The objectives respond to different aspects of scores and ordering.
- What does the helper return for an all-zero relevance list?
Answer 4: None, because ideal DCG is zero; an aggregation policy must handle that case explicitly.
Match training choices to the evaluation problem
Project: build held-out query groups, compare a fixed feature-order baseline with the trained scorer, and report per-query as well as mean NDCG. Duplicate the documents in one query and inspect how pair weighting changes the objective. Do not tune on the final test queries.
RankNet provides one pairwise construction. LambdaRank changes score-gradient weighting using rank-sensitive changes, and LambdaMART uses boosted trees. Their empirical results and implementation details should be read in the source reports, not inferred from this scalar demonstration. Continue with ranking metrics and information retrieval for evaluation and candidate-generation context.
Make a prediction, then check
What is invariant to a shared score offset within one query?
Learning objectives
- Derive a pairwise logistic ranking gradient.
- Keep query grouping and objective weights explicit.
- Distinguish ranking loss from held-out list metrics.
Prerequisites & connections
Explore related knowledge →References
- Learning to Rank using Gradient Descent
Chris Burges; Tal Shaked; Erin Renshaw; Ari Lazier; Matt Deeds; Nicole Hamilton; Greg Hullender · 2005 - From RankNet to LambdaRank to LambdaMART: An Overview
Christopher J. C. Burges · 2010
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source scope, explicit assumptions, original calculations and counterexamples, runnable tests and bilingual review; not independent human or second-agent review.
- Single-agent authored technical review: bounded primary-source locations, assumptions, original derivations, exact/literal references and matching bilingual equations/examples/exercises. Not independent human or second-agent review.
- Four focused CPython3.12.4 tests passed per chapter. Graph scores use analytic references; KM and random-query expectations use exact fractions; ranking gradients use literal and finite-difference checks. No NumPy dependency in these examples.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
Source locations checked:
- Learning to Rank using Gradient Descent · OriginalICML2005 PDF Sections2–3: within-query comparisons, score-offset invariance, logistic pairwise cross entropy, soft targets and consistency. Official report landing dateAugust2005 is not inferred as conference day.
- From RankNet to LambdaRank to LambdaMART: An Overview · MSR-TR-2010-82, Sections3–4, physical pages5–8: DCG/NDCG, rank-position dependence, pairwise-error mismatch and LambdaRank weighting. No claim of general direct-gradient NDCG optimization.
Related topics