Algorithmadvanced
RankNet
Also called Burges RankNet.
Trains a neural scoring function with a cross-entropy loss on the logistic probability that one document ranks above another.
- Solves
- Learning to rank
- Time
- O(T (P + N d)) totalO(P + N d) per_step
- Space
- O(N + d) extra
- Where
- N = the number of documents; P = the number of preferred pairs; T = the number of steps; d = the number of features
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Chris Burges, Tal Shaked, Erin Renshaw, Ari Lazier, Matt Deeds, Nicole Hamilton, Greg Hullender, 2005
RankNet trains a scoring function for learning to rank from pairs of documents of one query. It models the probability that document should rank above document as a -scaled logistic function of the score difference and minimizes the cross-entropy of that probability against the label order. The logistic-loss page treats one example with one label; here the "example" is a pair, and the useful step is the factorization of the gradient into one number per document, so that one pass over the documents replaces one pass over the pairs. The learning-to-rank page shows one RankNet step on three documents; this page gives the algorithm, the factorization, a safe step size for the linear model, and a full training trace. The code uses a linear scorer ; the original paper uses neural networks, which change only how is computed.
In plain words
For one search request, take two results where we know which one is better. The model gives each result a score. A large score gap in the right direction means the model is confident and right, and costs almost nothing. A gap in the wrong direction costs a lot. We add these costs over all such pairs. To improve the model, we work out how much each result should move up or down, by adding the pushes from all its pairs. Then we change the model so that each result moves by that amount. Results that sit below many worse results get a strong push up.
The problem
The input is a set of queries. Query has documents with feature vectors and integer labels . The preferred pairs of the query are the pairs with . For a scale and scores , the model probability that ranks above is
and the cost of a preferred pair is the cross-entropy against the target probability 1:
Burges (2010), Section 2, allows a general target with ; for a preferred pair and the cost is the one above, and pairs with equal labels add a cost that pulls their scores together. The code keeps only the preferred pairs. The output is the scorer, and a query is ranked by sorting its documents by score, ties to the smaller id.
The algorithm
For each pair, . Call this number . Summing the pairs that touch each document gives , and by the chain rule . For the linear scorer, .
RANKNET(queries, σ, T)- 1
w ← 0; η ← 1 / L, where L = (σ² / 4) Σ_{(i,j) ∈ P} ‖x_i - x_j‖² - 2
repeat T times: - 3
for each query: s_i ← w · x_i - 4
for each (i, j) ∈ P: λ_ij ← -σ / (1 + e^{σ (s_i - s_j)}) - 5
λ_i ← Σ_j λ_ij - Σ_j λ_ji - 6
g ← Σ_queries Σ_i λ_i x_i - 7
w ← w - η g - 8
return w
Line L4 is the only work per pair, and it is a scalar. Line L6 is the only work per feature, and it is done once per document, not once per pair. With a neural scorer, line L6 becomes one back-propagation per document with the output gradient , and line L7 any gradient method.
Example
One query has three documents with features A , B , C and labels 1, 0, 2, and . The preferred pairs are (A, B), (C, A) and (C, B), with the differences , and . So and .
At every score is 0 and every . Document A is the better one of (A, B) and the worse one of (C, A), so ; B is the worse one twice, so ; C is the better one twice, so . Then , and line L7 gives .
| step | scores (A, B, C) | (A, B, C) | |||
|---|---|---|---|---|---|
| 0 | 2.0794 | ||||
| 1 | 1.3197 |
The cost at step 0 is . After step 1 the pair (C, A) is a tie and still has the push on C, while A gets from (A, B) and from (C, A). The cost after 0, 10, 20, 30, 40 and 50 steps is 2.0794, 0.3707, 0.2100, 0.1471, 0.1133 and 0.0922, and after 50 steps is about , which orders the documents C, A, B. The cost keeps falling but never reaches 0, because every pair can be ordered correctly and a larger always helps (see the remark in the proof file).
Correctness
The proof in proofs/correctness.md shows:
- The factorization. with from lines L4 and L5. The tests check it against the sum over pairs and against finite differences of .
- Zero sum. The lambdas of one query sum to 0, since each pair adds to one document and subtracts it from the other.
- Convex and smooth. For the linear scorer, is convex in and its Hessian is at most , because .
- Descent. With , , so the cost never increases.
These are statements about the pairwise cost. A smaller cost does not imply a larger NDCG, and the rise of NDCG in the tests is measured on one planted data set, not proved.
Proof: The RankNet gradient factorizes into lambdas, and gradient descent with step 1/L never increases the costfull
Fix . A query has documents with feature vectors and integer labels . The scores are . Let be the preferred pairs of the query. The cost of the query is
and the cost of a training set is the sum over its queries. This is the cross-entropy of Burges et al. (2005) with the target probability , since for and .
Lemma 1 (the lambdas). Let for , and
Then and .
Proof. The term of the pair depends on only through . With , . So the pair adds to and to . Summing over the pairs gives . The chain rule with gives the second claim.
In the code, lines L4 and L5 add to document and subtract it from document , and line L6 forms . The cost of one gradient is one pass over the pairs for the lambdas and one pass over the documents for the sum, in place of one vector operation per pair. This is the factorization of Burges (2010), Section 2.1.
Lemma 2. The lambdas of one query sum to zero.
Proof. Each enters with the sign and with the sign , and no other lambda.
Lemma 3 (convex and smooth). For the linear model, is convex in , and its Hessian satisfies with
summed over all queries.
Proof. With , the pair term is and with . So the Hessian of the term is . It is positive semidefinite, and since and , it is at most . Sum over the pairs.
Theorem (monotone descent). Let , as in line L7 with . Then
Proof. By Lemma 3 and Taylor's theorem with the integral remainder, for all . Put and .
So the cost never increases, and since , , so the gradients tend to zero. If , every preferred pair has , the cost is the constant , and the code returns .
Remark (no minimizer). If some has for every preferred pair, then as while everywhere. The infimum is not attained and grows without bound. The theorem still holds, but the iterates do not converge. A target or a weight penalty gives a minimizer.
What is not proved. The theorem is about the pairwise cost. A smaller cost does not imply a larger NDCG, and nothing here bounds the error on new queries. The tests measure NDCG before and after training on one planted set and nothing more.
The tests in impl/python/test_ranknet.py check Lemma 1 against central finite differences of , the factorized gradient against the pair-by-pair gradient, Lemma 2, the theorem along 200 steps, and the worked example of the page.
Complexity
Let be the number of documents and the number of preferred pairs, at most . One step computes the scores in , the pair lambdas in and the gradient in , so it costs . Without the factorization, summing over the pairs costs . The extra space is for the scores, the lambdas and the gradient. With a neural scorer, the factorization replaces back-propagations by .
Properties
- Shift invariant. Adding the same constant to all scores of a query changes nothing, because only differences enter.
- Smooth surrogate of the pair order. when , so bounds the number of misordered pairs, as the hinge loss does for the Ranking SVM.
- Equal weight per pair. A pair at ranks 1 and 2 counts the same as a pair at ranks 50 and 51. This is the property that LambdaRank changes.
- No minimizer on separable data. If a linear orders all pairs, as and the weights grow without bound. A weight penalty or a target fixes it.
- Bounded pushes. , so one badly ordered pair cannot dominate the gradient, unlike a squared loss on the score difference.
Variants and improvements
- LambdaRank multiplies each by the change of NDCG from swapping and .
- LambdaMART fits gradient-boosted trees to the lambdas instead of a neural network.
- Neural scorers. The original paper trains neural networks with back-propagation. With the factorization, one query is a natural mini-batch: one forward pass per document, then one backward pass per document with the output gradient .
- Ties and soft targets. The target of Burges (2010) puts a cost on pairs of equal label.
- Listwise costs. ListNet replaces the sum over pairs by a cross-entropy between distributions over the whole list.
When to use it
Use RankNet when the scorer is a neural network and the training signal is pairwise preferences, for example from graded labels or from clicks. It is the base of the LambdaRank family, and its lambdas are the right first step to understand LambdaMART. If the metric weights the top of the list heavily, LambdaRank or LambdaMART usually do better on feature-based benchmarks, which is a measured result. For a linear scorer with a margin, the Ranking SVM gives a similar problem with a unique solution.
Pitfalls
- Overflow in the cost. Computing directly overflows for large . Use the stable softplus for , and in line L4 compute through a stable sigmoid.
- The sign of the update. Line L5 adds to the better document and subtracts it from the worse one. Swapping the two signs trains the model to reverse the order.
- Pairs across queries. Line L4 must loop over pairs of one query. Pairs from two queries ask for one score scale that the problem does not need.
- Step size. A fixed step much larger than in line L7 can make the cost oscillate. The bound of line L1 grows with the number of pairs, so a query set with many pairs needs a smaller step.
- No stopping point on separable data. Running line L2 longer always lowers the cost and grows . Stop by validation NDCG, or add a penalty.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ranknet/. The authors are listed in prov/DHZW3Q.jsonl.
"""RankNet with a linear scoring function s = w . x.
A query is a pair (X, y): X is a list of feature vectors and y the list of
integer labels. For each pair (i, j) of one query with y[i] > y[j] the model
probability that i ranks above j is
P_ij = 1 / (1 + exp(-sigma (s_i - s_j)))
and the cost of the pair is the cross-entropy with the target 1,
C_ij = log(1 + exp(-sigma (s_i - s_j))).
The general cost with a target probability pbar is pair_cost below. The
gradient factorizes (Burges 2010, Section 2.1): dC/dw = sum_i lambda_i x_i,
with lambda_i = dC/ds_i, so one pass over the documents replaces one pass
over the pairs. NDCG is computed here only for the tests and the examples;
it uses the gain 2^g - 1 and the discount 1 / log2(rank + 1).
"""
import math
def dot(a, b):
return sum(p * q for p, q in zip(a, b))
def softplus(z):
"""log(1 + e^z), without overflow."""
if z > 0:
return z + math.log1p(math.exp(-z))
return math.log1p(math.exp(z))
def sigmoid(z):
if z >= 0:
return 1.0 / (1.0 + math.exp(-z))
e = math.exp(z)
return e / (1.0 + e)
def scores(w, xs):
return [dot(w, x) for x in xs]
def preferred_pairs(y):
"""All (i, j) with y[i] > y[j]."""
n = len(y)
return [(i, j) for i in range(n) for j in range(n) if y[i] > y[j]]
def pair_cost(o, pbar, sigma=1.0):
"""Cross-entropy -pbar log P - (1 - pbar) log(1 - P), with P = sigmoid(sigma o)."""
# -log P = softplus(-sigma o) and -log(1 - P) = softplus(sigma o).
return pbar * softplus(-sigma * o) + (1.0 - pbar) * softplus(sigma * o)
def query_cost(s, y, sigma=1.0):
"""Sum of C_ij over the preferred pairs of one query, given the scores s."""
return sum(softplus(-sigma * (s[i] - s[j])) for i, j in preferred_pairs(y))
def cost(w, queries, sigma=1.0):
return sum(query_cost(scores(w, xs), y, sigma) for xs, y in queries)
def lambdas(s, y, sigma=1.0):
"""lambda_i = dC/ds_i for one query (Burges 2010, Section 2.1)."""
lam = [0.0] * len(s)
for i, j in preferred_pairs(y):
lij = -sigma * sigmoid(-sigma * (s[i] - s[j])) # dC_ij/ds_i # @line L4
lam[i] += lij # @line L5
lam[j] -= lij
return lam
def gradient(w, queries, sigma=1.0):
"""dC/dw by the factorization sum over documents of lambda_i x_i."""
g = [0.0] * len(w)
for xs, y in queries:
lam = lambdas(scores(w, xs), y, sigma) # @line L3
for li, x in zip(lam, xs):
for k in range(len(w)):
g[k] += li * x[k] # @line L6
return g
def gradient_by_pairs(w, queries, sigma=1.0):
"""dC/dw summed pair by pair, without the factorization."""
g = [0.0] * len(w)
for xs, y in queries:
s = scores(w, xs)
for i, j in preferred_pairs(y):
c = -sigma * sigmoid(-sigma * (s[i] - s[j]))
for k in range(len(w)):
g[k] += c * (xs[i][k] - xs[j][k])
return g
def lipschitz(queries, sigma=1.0):
"""L = sigma^2 / 4 times the sum of |x_i - x_j|^2 over the preferred pairs.
The Hessian of C_ij in w is sigma^2 p (1 - p) z z^T with z = x_i - x_j,
and p (1 - p) <= 1/4, so L bounds the curvature of the whole cost.
"""
total = 0.0
for xs, y in queries:
for i, j in preferred_pairs(y):
total += sum((a - b) ** 2 for a, b in zip(xs[i], xs[j]))
return sigma * sigma * total / 4.0
def train(queries, d, sigma=1.0, steps=100):
"""Full-batch gradient descent from w = 0 with the step 1/L.
Returns w and the list of costs, one per iterate. With this step the
cost never increases (descent lemma for an L-smooth function).
"""
w = [0.0] * d # @line L1
big_l = lipschitz(queries, sigma)
history = [cost(w, queries, sigma)]
if big_l == 0.0:
return w, history
eta = 1.0 / big_l
for _ in range(steps): # @line L2
g = gradient(w, queries, sigma)
w = [wk - eta * gk for wk, gk in zip(w, g)] # @line L7
history.append(cost(w, queries, sigma))
return w, history # @line L8
def ranking(s):
"""Indices by score descending, then index ascending."""
return sorted(range(len(s)), key=lambda i: (-s[i], i))
def dcg(labels):
return sum((2 ** g - 1) / math.log2(r + 2) for r, g in enumerate(labels))
def ndcg(s, y, k=None):
"""NDCG@k with gain 2^g - 1; None when the query has no positive label."""
k = len(y) if k is None else k
ideal = dcg(sorted(y, reverse=True)[:k])
if ideal == 0:
return None
return dcg([y[i] for i in ranking(s)[:k]]) / ideal
test_ranknet.py 123 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ranknet/. The authors are listed in prov/DHZW3Q.jsonl.
import math
import random
from ranknet import (
cost,
gradient,
gradient_by_pairs,
lambdas,
ndcg,
pair_cost,
preferred_pairs,
query_cost,
ranking,
scores,
train,
)
TOL = 1e-6
def planted(seed, n_queries=6, n_docs=6, d=3):
"""Queries whose labels 0..2 come from a hidden linear score plus noise."""
rng = random.Random(seed)
w_true = [rng.uniform(-1, 1) for _ in range(d)]
queries = []
for _ in range(n_queries):
xs = [[rng.uniform(-1, 1) for _ in range(d)] for _ in range(n_docs)]
t = [sum(a * b for a, b in zip(w_true, x)) + rng.gauss(0, 0.1) for x in xs]
order = sorted(t)
lo, hi = order[n_docs // 3], order[2 * n_docs // 3]
y = [0 if v < lo else (1 if v < hi else 2) for v in t]
queries.append((xs, y))
return queries
def numeric_gradient(f, w, h=1e-6):
g = []
for k in range(len(w)):
a = list(w)
b = list(w)
a[k] += h
b[k] -= h
g.append((f(a) - f(b)) / (2 * h))
return g
def test_page_example():
# Two features, documents A, B, C with labels 1, 0, 2, sigma = 1.
xs = [[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]]
y = [1, 0, 2]
queries = [(xs, y)]
assert abs(cost([0.0, 0.0], queries) - 3 * math.log(2)) < 1e-12
assert lambdas([0.0, 0.0, 0.0], y) == [0.0, 1.0, -1.0]
assert gradient([0.0, 0.0], queries) == [-1.0, 0.0]
w, history = train(queries, 2, steps=1)
assert w == [1.0, 0.0]
s = scores(w, xs)
assert round(query_cost(s, y), 4) == 1.3197
assert [round(v, 4) for v in lambdas(s, y)] == [0.2311, 0.5379, -0.7689]
assert [round(v, 4) for v in gradient(w, queries)] == [-0.5379, -0.2311]
def test_pair_cost_forms():
# With pbar = 1 the general cross-entropy is softplus(-sigma o).
for o in (-3.0, -0.5, 0.0, 0.7, 4.0):
for sigma in (0.5, 1.0, 2.0):
assert abs(pair_cost(o, 1.0, sigma) - math.log1p(math.exp(-sigma * o))) < 1e-12
# With pbar = 1/2 the cost is log 2 at o = 0 and grows on both sides.
assert abs(pair_cost(0.0, 0.5) - math.log(2)) < 1e-12
assert pair_cost(1.0, 0.5) > math.log(2) and pair_cost(-1.0, 0.5) > math.log(2)
def test_gradient_against_finite_differences():
rng = random.Random(1)
for sigma in (0.5, 1.0, 2.0):
queries = planted(seed=7)
for _ in range(5):
w = [rng.uniform(-2, 2) for _ in range(3)]
g = gradient(w, queries, sigma)
num = numeric_gradient(lambda v: cost(v, queries, sigma), w)
assert all(abs(a - b) < TOL * max(1.0, abs(b)) for a, b in zip(g, num))
def test_factorized_equals_pairwise():
rng = random.Random(2)
queries = planted(seed=3)
for _ in range(10):
w = [rng.uniform(-2, 2) for _ in range(3)]
a = gradient(w, queries)
b = gradient_by_pairs(w, queries)
assert all(abs(p - q) < 1e-9 for p, q in zip(a, b))
def test_lambdas_sum_to_zero():
rng = random.Random(4)
for xs, y in planted(seed=5):
s = [rng.uniform(-1, 1) for _ in xs]
assert abs(sum(lambdas(s, y))) < 1e-12
def test_cost_never_increases_and_falls():
queries = planted(seed=11)
w, history = train(queries, 3, steps=200)
assert all(b <= a + 1e-12 for a, b in zip(history, history[1:]))
assert history[-1] < history[0]
# Measured on this planted set, not a theorem: the learned w ranks
# better than w = 0, whose ranking is by document index only.
before = sum(ndcg([0.0] * len(y), y) for _, y in queries)
after = sum(ndcg(scores(w, xs), y) for xs, y in queries)
assert after > before
def test_equal_labels_add_no_pair():
assert preferred_pairs([1, 1, 1]) == []
assert query_cost([0.3, -2.0, 5.0], [1, 1, 1]) == 0.0
def test_ranking_ties_by_index():
assert ranking([1.0, 2.0, 2.0, 0.5]) == [1, 2, 0, 3]
assert ndcg([0.0, 0.0], [0, 0]) is None
History
Burges, Shaked, Renshaw, Lazier, Deeds, Hamilton and Hullender (2005) introduced the probabilistic pairwise cost and trained neural network scorers with it on web search data. In his 2010 overview, Burges wrote the gradient as a sum over documents of the lambdas, which made training faster and suggested changing the lambdas directly. That idea gave LambdaRank, and fitting boosted trees to the same lambdas gave LambdaMART.
References
- Chris Burges, Tal Shaked, Erin Renshaw, Ari Lazier, Matt Deeds, Nicole Hamilton and Greg Hullender, Learning to rank using gradient descent, Proceedings of the 22nd International Conference on Machine Learning (ICML 2005), pp. 89-96 (the logistic model of the pair probability, the cross-entropy cost, and its training by back-propagation)
- Christopher J. C. Burges, From RankNet to LambdaRank to LambdaMART: an overview, Microsoft Research Technical Report MSR-TR-2010-82, 2010, Section 2 (the cost with a target probability) and Section 2.1 (the factorization of the gradient into lambdas)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag DHZW3Q Edit this page History Report an error Markdown