Algorithmadvanced
ListNet
Also called listwise top-one probability loss.
Trains a scorer by minimizing the cross-entropy between top-one probability distributions induced by predicted and true scores.
- Solves
- Learning to rank
- Time
- O(T N d) totalO(N d) per_step
- Space
- O(N + d) extra
- Where
- N = the number of documents; T = the number of steps; d = the number of features
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Zhe Cao, Tao Qin, Tie Yan Liu, Ming Feng Tsai, Hang Li, 2007
ListNet trains a scoring function for learning to rank with a loss on the whole list of a query. It turns the scores into a probability distribution over the documents with a softmax, does the same with the labels, and minimizes the cross-entropy between the two. The cross-entropy-loss page treats a fixed target class; here the target is itself a distribution made from graded labels, and the classes are the documents of one query, so the number of classes changes from query to query. Unlike RankNet and the Ranking SVM, no pairs are formed. This page gives the loss, the reason the softmax is the probability of being ranked first, the gradient , a safe step for the linear model, and its known limits.
In plain words
For one search request, we turn the scores of the results into shares that add up to 1. A result with a much higher score gets a much larger share. We also turn the true labels into shares in the same way. The method changes the scoring rule so that the two sets of shares agree. The share of a result can be read as the chance that it comes out first if we draw the results one by one at random, with better results more likely. The method looks at the whole list at once, and its cost grows with the number of results, not with the number of pairs.
The problem
The input is a set of queries; query has documents and labels . The code uses the linear scorer ; Cao et al. (2007) train a neural network scorer, which changes only how is computed. With , the top-one probabilities of the scores and of the labels are
and the loss is
is the probability that comes first under the Plackett-Luce model, which draws document first with probability proportional to , then the next one among those left in the same way. So the loss compares the first-place marginals of two distributions over the permutations, at the cost of numbers instead of .
The algorithm
LISTNET(queries, T)- 1
w ← 0; η ← 1 / M, where M = Σ_queries max_j ‖x_j‖² - 2
repeat T times: - 3
for each query: s_j ← w · x_j - 4
P_s ← softmax(s), P_y ← softmax(y) - 5
g ← Σ_queries Σ_j (P_s(j) - P_y(j)) x_j - 6
w ← w - η g - 7
return w
Line L4 is the whole loss computation. The gradient in the scores is , so line L5 is one pass over the documents. Cao et al. (2007) train with a fixed learning rate; the step of line L1 is the one for which the proof shows that the loss never increases.
Example
One query has three documents with labels and current scores .
| document | |||||
|---|---|---|---|---|---|
| 0 | 2 | 1.0 | 0.6652 | 0.5065 | -0.1588 |
| 1 | 0 | 0.0 | 0.0900 | 0.1863 | 0.0963 |
| 2 | 1 | 0.5 | 0.2447 | 0.3072 | 0.0625 |
The loss is . The scores already rank the documents in the label order, so NDCG is 1, but the loss is not at its minimum: document 0 should have a larger share, and the gradient asks for a higher and lower and . The minimum of the loss for this query is the entropy of , , reached exactly when is a constant vector. At the loss is and the score gradient is .
Correctness
The proof in proofs/correctness.md shows:
- Top-one probability. Under the Plackett-Luce model with weights , the probability that is ranked first is . The tests check it by a sum over the 24 permutations of 4 documents.
- Gradient. and . The tests check both by central finite differences.
- Convex and smooth. For the linear model, is convex and its Hessian is at most , because the Hessian of one query is a covariance of under .
- Descent. With the step , .
- Minimum. For each query, , with equality exactly when is constant.
On the planted set of the tests (6 queries of 5 documents), 200 steps lower the loss from 9.657 to 8.410, against the bound , and the mean NDCG on the training queries rises from 0.713 at to 1.0. The NDCG figures are measured, not proved: a lower loss does not imply a higher NDCG.
Proof: The ListNet top-one loss is convex with gradient P_s minus P_y, and the step 1/M never increases itfull
One query has documents with labels and scores . With , the top-one probabilities are
and the loss of the query is the cross-entropy . The training loss is the sum over the queries.
Lemma 1 (top-one probability). Under the Plackett-Luce model with weights , the probability that document is ranked first is .
Proof. The model picks the first document with probability and then each next document in the same way among those left. Group the permutations by their first element. For first element , the remaining factors are the probabilities of a Plackett-Luce ranking of the other documents, and these sum to 1 over all such rankings, by induction on . So the sum over the permutations that start with is .
This is the theorem of Cao et al. (2007) that lets ListNet replace the permutation probabilities by top-one probabilities.
Lemma 2 (gradient). , and .
Proof. Since , . The derivative of the first term in is , and of the second term . The chain rule with gives the rest.
Line L4 of the code computes , and lines L3 and L5 form the sum. The gradient of one query costs for documents with features, in place of the of a pairwise loss.
Lemma 3 (convex and smooth). The loss is convex in , and its Hessian satisfies with .
Proof. For one query, with and the matrix with rows . For a vector , let . Then , the variance of under . It is at least 0, and at most . Sum over the queries.
Theorem (monotone descent). With , as in lines L1 and L6,
Proof. Lemma 3 and Taylor's theorem give . Put .
Lemma 4 (the minimum and two invariances). For each query, , with equality exactly when , that is when is a constant vector. Adding the same constant to all scores of a query leaves unchanged.
Proof. is the Kullback-Leibler divergence of from , which is nonnegative and zero exactly when the two distributions are equal. The softmax does not change when a constant is added to every entry.
So the loss is not zero at its minimum, and its minimum depends on the label values, not only on their order: the labels and give different targets. With a linear model the minimum over is usually larger than , since no needs to reproduce up to a shift.
What is not proved. A smaller loss 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.
The tests in impl/python/test_listnet.py check Lemma 2 by central finite differences in and in , Lemma 1 by a brute force over the 24 permutations of 4 documents, convexity on random segments, the shift invariance, the theorem along 200 steps, Lemma 4, and the worked example of the page.
Complexity
Each step computes scores in , one softmax per query in , and the gradient in . So a step costs , and steps . A pairwise loss on the same data costs per step with the lambda factorization and without it, with up to . The extra space is . The full permutation distribution would cost terms per query, which the top-one form avoids.
Properties
- Shift invariant per query. Adding a constant to all scores of a query does not change .
- Depends on label values, not only their order. The labels and give different and different minimizers. A rescaling of the label grades is a modeling choice.
- Nonzero minimum. The loss at its minimum is , so its value alone does not show how close the model is to the best possible.
- Not position aware. The loss does not use a discount by rank; errors at the top and errors at the bottom count through the shares only.
- Bounded gradient. Each entry of is in .
Variants and improvements
- Top- probabilities. Cao et al. (2007) define the probability of the first positions in general and use for cost reasons.
- ListMLE. Maximizes the Plackett-Luce likelihood of the label order itself, which fixes one permutation instead of matching marginals.
- Softmax cross-entropy with one positive. If puts all mass on one relevant document, the loss is the softmax loss used to train retrieval models such as dense passage retrieval, with the other documents as negatives.
- Other transforms. A different increasing in place of , or a temperature on , changes how much the top label dominates .
When to use it
Use ListNet when the scorer is trained by gradients and the data have graded labels for every document of a query, and when the cost per step must be linear in the number of documents. Its loss is smooth, convex for a linear model, and simple to implement. If the target metric is NDCG@ with a small , LambdaRank or LambdaMART weight the top positions more directly; which works better on a given data set is a matter of measurement.
Pitfalls
- Overflow. Line L4 must subtract the largest entry before exponentiating, or large scores or labels overflow. Use a log-softmax for the loss.
- Softmax across queries. Line L4 must normalize within one query. A softmax over all documents of all queries compares documents that never compete.
- Large label scales. Labels on a scale of 0 to 100 make almost one-hot. Rescale the labels before line L4, or the loss ignores all but the top document.
- Reading the loss as quality. The loss stays above even for a perfect ranking, as in the example, where NDCG is 1 but the loss is 0.8927. Monitor NDCG on held-out queries.
- Step size. A fixed step much larger than in line L6 can make the loss oscillate. grows with the number of queries in the batch.
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/listnet/. The authors are listed in prov/TRPVZ8.jsonl.
"""ListNet with the top-one probability and a linear scoring function.
For one query with scores s and labels y, the top-one probabilities with
phi = exp are the softmax values
P_s(j) = exp(s_j) / sum_k exp(s_k), P_y(j) = exp(y_j) / sum_k exp(y_k).
The loss of the query is the cross-entropy L = -sum_j P_y(j) log P_s(j),
and its gradient in s is P_s - P_y. With s_j = w . x_j the gradient in w
is sum_j (P_s(j) - P_y(j)) x_j. Training is full-batch gradient descent
with the step 1 / M, where M = sum over queries of max_j ||x_j||^2 bounds
the curvature, so the loss never increases (see proofs/correctness.md).
NDCG 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 softmax(v):
m = max(v)
e = [math.exp(x - m) for x in v]
z = sum(e)
return [x / z for x in e]
def log_softmax(v):
m = max(v)
lz = m + math.log(sum(math.exp(x - m) for x in v))
return [x - lz for x in v]
def scores(w, xs):
return [dot(w, x) for x in xs]
def query_loss(s, y):
py = softmax([float(g) for g in y])
return -sum(p * l for p, l in zip(py, log_softmax(s)))
def query_score_gradient(s, y):
"""dL/ds = P_s - P_y."""
return [a - b for a, b in zip(softmax(s), softmax([float(g) for g in y]))] # @line L4
def loss(w, queries):
return sum(query_loss(scores(w, xs), y) for xs, y in queries)
def gradient(w, queries):
g = [0.0] * len(w)
for xs, y in queries:
for d, x in zip(query_score_gradient(scores(w, xs), y), xs): # @line L3
for c in range(len(w)):
g[c] += d * x[c] # @line L5
return g
def curvature_bound(queries):
"""M = sum over queries of max_j ||x_j||^2; the Hessian of the loss is at most M I."""
return sum(max(dot(x, x) for x in xs) for xs, _ in queries)
def train(queries, d, steps=100):
"""Gradient descent from w = 0 with the step 1 / M. Returns w and the loss history."""
w = [0.0] * d # @line L1
eta = 1.0 / curvature_bound(queries)
history = [loss(w, queries)]
for _ in range(steps): # @line L2
g = gradient(w, queries)
w = [a - eta * b for a, b in zip(w, g)] # @line L6
history.append(loss(w, queries))
return w, history # @line L7
def plackett_luce(s, perm):
"""Probability of the full permutation perm under the Plackett-Luce model with phi = exp."""
p = 1.0
rest = list(perm)
for j in perm:
p *= math.exp(s[j]) / sum(math.exp(s[k]) for k in rest)
rest.remove(j)
return p
def ranking(s):
return sorted(range(len(s)), key=lambda i: (-s[i], i))
def ndcg(s, y, k=None):
k = len(y) if k is None else k
ideal = sum((2 ** g - 1) / math.log2(r + 2) for r, g in enumerate(sorted(y, reverse=True)[:k]))
if ideal == 0:
return None
return sum((2 ** y[d] - 1) / math.log2(r + 2) for r, d in enumerate(ranking(s)[:k])) / ideal
def mean_ndcg(w, queries, k=None):
vals = [ndcg(scores(w, xs), y, k) for xs, y in queries]
vals = [v for v in vals if v is not None]
return sum(vals) / len(vals) if vals else None
test_listnet.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/listnet/. The authors are listed in prov/TRPVZ8.jsonl.
import itertools
import math
import random
from listnet import (
curvature_bound,
gradient,
loss,
mean_ndcg,
plackett_luce,
query_loss,
query_score_gradient,
softmax,
train,
)
def planted(seed, n_queries=6, n_docs=5, d=3):
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)
y = [0 if v < order[2] else (1 if v < order[4] else 2) for v in t]
queries.append((xs, y))
return queries
def test_page_example():
# Labels 2, 0, 1 and scores 1.0, 0.0, 0.5.
s = [1.0, 0.0, 0.5]
y = [2, 0, 1]
assert [round(v, 4) for v in softmax(s)] == [0.5065, 0.1863, 0.3072]
assert [round(v, 4) for v in softmax([2.0, 0.0, 1.0])] == [0.6652, 0.0900, 0.2447]
assert round(query_loss(s, y), 4) == 0.8927
assert [round(v, 4) for v in query_score_gradient(s, y)] == [-0.1588, 0.0963, 0.0625]
# At s = 0 the loss is log 3.
assert abs(query_loss([0.0, 0.0, 0.0], y) - math.log(3)) < 1e-12
def test_score_gradient_by_finite_differences():
rng = random.Random(1)
h = 1e-6
for _ in range(100):
n = rng.randint(1, 6)
y = [rng.randint(0, 3) for _ in range(n)]
s = [rng.uniform(-3, 3) for _ in range(n)]
g = query_score_gradient(s, y)
for i in range(n):
a = list(s)
b = list(s)
a[i] += h
b[i] -= h
assert abs((query_loss(a, y) - query_loss(b, y)) / (2 * h) - g[i]) < 1e-6
def test_weight_gradient_by_finite_differences():
rng = random.Random(2)
queries = planted(seed=3)
h = 1e-6
for _ in range(5):
w = [rng.uniform(-2, 2) for _ in range(3)]
g = gradient(w, queries)
for c in range(3):
a = list(w)
b = list(w)
a[c] += h
b[c] -= h
assert abs((loss(a, queries) - loss(b, queries)) / (2 * h) - g[c]) < 1e-6
def test_top_one_probability_is_sum_of_plackett_luce():
rng = random.Random(4)
s = [rng.uniform(-1, 1) for _ in range(4)]
p = softmax(s)
total = 0.0
for j in range(4):
pj = sum(plackett_luce(s, perm) for perm in itertools.permutations(range(4)) if perm[0] == j)
assert abs(pj - p[j]) < 1e-12
total += pj
assert abs(total - 1.0) < 1e-12
def test_loss_is_convex_in_w_on_segments():
rng = random.Random(5)
queries = planted(seed=6)
for _ in range(30):
u = [rng.uniform(-3, 3) for _ in range(3)]
v = [rng.uniform(-3, 3) for _ in range(3)]
t = rng.random()
mid = [t * a + (1 - t) * b for a, b in zip(u, v)]
assert loss(mid, queries) <= t * loss(u, queries) + (1 - t) * loss(v, queries) + 1e-12
def test_shift_invariance():
s = [0.3, -1.2, 2.0]
y = [1, 0, 2]
assert abs(query_loss(s, y) - query_loss([v + 5.0 for v in s], y)) < 1e-12
def test_step_one_over_m_never_increases_loss():
queries = planted(seed=7)
assert curvature_bound(queries) > 0
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.
assert mean_ndcg(w, queries) > mean_ndcg([0.0, 0.0, 0.0], queries)
def test_minimum_is_not_zero():
# The loss is at least the entropy of P_y, and equals it only if P_s = P_y.
y = [2, 0, 1]
py = softmax([2.0, 0.0, 1.0])
entropy = -sum(p * math.log(p) for p in py)
assert abs(query_loss([2.0, 0.0, 1.0], y) - entropy) < 1e-12
assert query_loss([5.0, 0.0, 1.0], y) > entropy
History
Cao, Qin, Liu, Tsai and Li (2007) argued that pairwise methods such as the Ranking SVM, RankBoost and RankNet optimize a loss on pairs, while ranking quality is a property of whole lists. They defined permutation probabilities by the Plackett-Luce model, showed that the top-one marginals are a softmax of the scores, and trained a neural network scorer with the resulting cross-entropy. ListNet started the listwise family of losses, which includes ListMLE and many later softmax losses.
References
- Zhe Cao, Tao Qin, Tie-Yan Liu, Ming-Feng Tsai and Hang Li, Learning to rank, from pairwise approach to listwise approach, Proceedings of the 24th International Conference on Machine Learning (ICML 2007), pp. 129-136 (the permutation probability, the top-one probability, the cross-entropy loss and its gradient, and training of a neural network scorer by gradient descent)
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 TRPVZ8 Edit this page History Report an error Markdown