Algorithm Search⌘K

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.

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
Properties
deterministicnot exactofflineiterative
Origin
Chris Burges, Tal Shaked, Erin Renshaw, Ari Lazier, Matt Deeds, Nicole Hamilton, Greg Hullender, 2005

RankNet trains a scoring function s=f(x)s = f(x) for learning to rank from pairs of documents of one query. It models the probability that document ii should rank above document jj as a σ\sigma-scaled logistic function of the score difference si−sjs_i - s_j 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 λi\lambda_i 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 s=w⋅xs = w \cdot x; the original paper uses neural networks, which change only how ∂s/∂w\partial s / \partial w 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 qq has documents with feature vectors x1,…,xn∈Rdx_1, \ldots, x_n \in \mathbb R^d and integer labels y1,…,yny_1, \ldots, y_n. The preferred pairs P\mathcal P of the query are the pairs (i,j)(i, j) with yi>yjy_i > y_j. For a scale σ>0\sigma > 0 and scores si=f(xi)s_i = f(x_i), the model probability that ii ranks above jj is

Pij=11+e−σ(si−sj),P_{ij} = \frac{1}{1 + e^{-\sigma (s_i - s_j)}},

and the cost of a preferred pair is the cross-entropy against the target probability 1:

Cij=−log⁡Pij=log⁡(1+e−σ(si−sj)),C=∑queries∑(i,j)∈PCij.C_{ij} = -\log P_{ij} = \log\left(1 + e^{-\sigma (s_i - s_j)}\right), \qquad C = \sum_{\text{queries}} \sum_{(i,j) \in \mathcal P} C_{ij}.

Burges (2010), Section 2, allows a general target Pˉij=12(1+Sij)\bar P_{ij} = \frac{1}{2}(1 + S_{ij}) with Sij∈{−1,0,1}S_{ij} \in \{-1, 0, 1\}; for a preferred pair Pˉij=1\bar P_{ij} = 1 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, ∂Cij/∂si=−σ/(1+eσ(si−sj))=−∂Cij/∂sj\partial C_{ij} / \partial s_i = -\sigma / (1 + e^{\sigma(s_i - s_j)}) = -\partial C_{ij} / \partial s_j. Call this number λij\lambda_{ij}. Summing the pairs that touch each document gives λi=∂C/∂si\lambda_i = \partial C / \partial s_i, and by the chain rule ∇wC=∑iλi∇wsi\nabla_w C = \sum_i \lambda_i \nabla_w s_i. For the linear scorer, ∇wsi=xi\nabla_w s_i = x_i.

  1. RANKNET(queries, σ, T)
  2. 1w ← 0; η ← 1 / L, where L = (σ² / 4) Σ_{(i,j) ∈ P} ‖x_i - x_j‖²
  3. 2repeat T times:
  4. 3for each query: s_i ← w · x_i
  5. 4for each (i, j) ∈ P: λ_ij ← -σ / (1 + e^{σ (s_i - s_j)})
  6. 5λ_i ← Σ_j λ_ij - Σ_j λ_ji
  7. 6g ← Σ_queries Σ_i λ_i x_i
  8. 7w ← w - η g
  9. 8return 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 λi\lambda_i, and line L7 any gradient method.

Example

One query has three documents with features A =(1,0)= (1, 0), B =(0,1)= (0, 1), C =(1,1)= (1, 1) and labels 1, 0, 2, and σ=1\sigma = 1. The preferred pairs are (A, B), (C, A) and (C, B), with the differences (1,−1)(1, -1), (0,1)(0, 1) and (1,0)(1, 0). So L=14(2+1+1)=1L = \frac{1}{4}(2 + 1 + 1) = 1 and η=1\eta = 1.

At w=0w = 0 every score is 0 and every λij=−0.5\lambda_{ij} = -0.5. Document A is the better one of (A, B) and the worse one of (C, A), so λA=−0.5+0.5=0\lambda_A = -0.5 + 0.5 = 0; B is the worse one twice, so λB=1\lambda_B = 1; C is the better one twice, so λC=−1\lambda_C = -1. Then g=0⋅A+1⋅B−1⋅C=(−1,0)g = 0 \cdot A + 1 \cdot B - 1 \cdot C = (-1, 0), and line L7 gives w=(1,0)w = (1, 0).

step ww scores (A, B, C) λ\lambda (A, B, C) gg CC
0 (0,0)(0, 0) (0,0,0)(0, 0, 0) (0,1,−1)(0, 1, -1) (−1,0)(-1, 0) 2.0794
1 (1,0)(1, 0) (1,0,1)(1, 0, 1) (0.2311,0.5379,−0.7689)(0.2311, 0.5379, -0.7689) (−0.5379,−0.2311)(-0.5379, -0.2311) 1.3197

The cost at step 0 is 3ln⁡23 \ln 2. After step 1 the pair (C, A) is a tie and still has the push −0.5-0.5 on C, while A gets −0.2689-0.2689 from (A, B) and +0.5+0.5 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 ww after 50 steps is about (6.201,2.874)(6.201, 2.874), 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 ww always helps (see the remark in the proof file).

Correctness

The proof in proofs/correctness.md shows:

  • The factorization. ∇wC=∑iλixi\nabla_w C = \sum_i \lambda_i x_i with λi\lambda_i from lines L4 and L5. The tests check it against the sum over pairs and against finite differences of CC.
  • Zero sum. The lambdas of one query sum to 0, since each pair adds λij\lambda_{ij} to one document and subtracts it from the other.
  • Convex and smooth. For the linear scorer, CC is convex in ww and its Hessian is at most LIL I, because Pij(1−Pij)≤1/4P_{ij}(1 - P_{ij}) \le 1/4.
  • Descent. With η=1/L\eta = 1/L, C(wt+1)≤C(wt)−12L∥∇C(wt)∥2C(w_{t+1}) \le C(w_t) - \frac{1}{2L}\lVert \nabla C(w_t) \rVert^2, 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 σ>0\sigma > 0. A query has documents with feature vectors x1,…,xnx_1, \ldots, x_n and integer labels y1,…,yny_1, \ldots, y_n. The scores are si=w⋅xis_i = w \cdot x_i. Let P={(i,j):yi>yj}\mathcal P = \{(i, j) : y_i > y_j\} be the preferred pairs of the query. The cost of the query is

C(w)=∑(i,j)∈Plog⁡(1+e−σ(si−sj)),C(w) = \sum_{(i, j) \in \mathcal P} \log\left(1 + e^{-\sigma (s_i - s_j)}\right),

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 Pˉij=1\bar P_{ij} = 1, since −log⁡Pij=log⁡(1+e−σoij)-\log P_{ij} = \log(1 + e^{-\sigma o_{ij}}) for Pij=1/(1+e−σoij)P_{ij} = 1/(1 + e^{-\sigma o_{ij}}) and oij=si−sjo_{ij} = s_i - s_j.

Lemma 1 (the lambdas). Let λij=−σ/(1+eσ(si−sj))\lambda_{ij} = -\sigma / (1 + e^{\sigma (s_i - s_j)}) for (i,j)∈P(i, j) \in \mathcal P, and

λi=∑j:(i,j)∈Pλij−∑j:(j,i)∈Pλji.\lambda_i = \sum_{j : (i, j) \in \mathcal P} \lambda_{ij} - \sum_{j : (j, i) \in \mathcal P} \lambda_{ji}.

Then ∂C/∂si=λi\partial C / \partial s_i = \lambda_i and ∇wC=∑iλixi\nabla_w C = \sum_i \lambda_i x_i.

Proof. The term of the pair (i,j)(i, j) depends on ss only through o=si−sjo = s_i - s_j. With c(o)=log⁡(1+e−σo)c(o) = \log(1 + e^{-\sigma o}), c′(o)=−σe−σo/(1+e−σo)=−σ/(1+eσo)c'(o) = -\sigma e^{-\sigma o} / (1 + e^{-\sigma o}) = -\sigma / (1 + e^{\sigma o}). So the pair adds c′(o)=λijc'(o) = \lambda_{ij} to ∂C/∂si\partial C / \partial s_i and −c′(o)=−λij-c'(o) = -\lambda_{ij} to ∂C/∂sj\partial C / \partial s_j. Summing over the pairs gives ∂C/∂si=λi\partial C / \partial s_i = \lambda_i. The chain rule with ∂si/∂w=xi\partial s_i / \partial w = x_i gives the second claim. □\square

In the code, lines L4 and L5 add λij\lambda_{ij} to document ii and subtract it from document jj, and line L6 forms ∑iλixi\sum_i \lambda_i x_i. 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 λij\lambda_{ij} enters λi\lambda_i with the sign ++ and λj\lambda_j with the sign −-, and no other lambda. □\square

Lemma 3 (convex and smooth). For the linear model, CC is convex in ww, and its Hessian satisfies 0⪯∇2C⪯LI0 \preceq \nabla^2 C \preceq L I with

L=σ24∑(i,j)∈P∥xi−xj∥2,L = \frac{\sigma^2}{4} \sum_{(i, j) \in \mathcal P} \lVert x_i - x_j \rVert^2,

summed over all queries.

Proof. With z=xi−xjz = x_i - x_j, the pair term is c(w⋅z)c(w \cdot z) and c′′(o)=σ2p(1−p)c''(o) = \sigma^2 p (1 - p) with p=1/(1+eσo)p = 1 / (1 + e^{\sigma o}). So the Hessian of the term is σ2p(1−p)zz⊤\sigma^2 p (1 - p) z z^\top. It is positive semidefinite, and since p(1−p)≤1/4p (1 - p) \le 1/4 and zz⊤⪯∥z∥2Iz z^\top \preceq \lVert z \rVert^2 I, it is at most (σ2/4)∥z∥2I(\sigma^2/4) \lVert z \rVert^2 I. Sum over the pairs. □\square

Theorem (monotone descent). Let wt+1=wt−1L∇C(wt)w_{t+1} = w_t - \frac{1}{L} \nabla C(w_t), as in line L7 with η=1/L\eta = 1/L. Then

C(wt+1)≤C(wt)−12L∥∇C(wt)∥2.C(w_{t+1}) \le C(w_t) - \frac{1}{2L} \lVert \nabla C(w_t) \rVert^2.

Proof. By Lemma 3 and Taylor's theorem with the integral remainder, C(v)≤C(w)+∇C(w)⋅(v−w)+L2∥v−w∥2C(v) \le C(w) + \nabla C(w) \cdot (v - w) + \frac{L}{2} \lVert v - w \rVert^2 for all w,vw, v. Put w=wtw = w_t and v=wt−∇C(wt)/Lv = w_t - \nabla C(w_t)/L. □\square

So the cost never increases, and since C≥0C \ge 0, ∑t∥∇C(wt)∥2≤2L C(w0)\sum_t \lVert \nabla C(w_t) \rVert^2 \le 2 L\, C(w_0), so the gradients tend to zero. If L=0L = 0, every preferred pair has xi=xjx_i = x_j, the cost is the constant ∣P∣log⁡2|\mathcal P| \log 2, and the code returns w=0w = 0.

Remark (no minimizer). If some uu has u⋅(xi−xj)>0u \cdot (x_i - x_j) > 0 for every preferred pair, then C(tu)→0C(t u) \to 0 as t→∞t \to \infty while C>0C > 0 everywhere. The infimum is not attained and ∥wt∥\lVert w_t \rVert grows without bound. The theorem still holds, but the iterates do not converge. A target Pˉij<1\bar P_{ij} < 1 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 CC, 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 NN be the number of documents and PP the number of preferred pairs, at most ∑qnq2/2\sum_q n_q^2 / 2. One step computes the scores in O(Nd)O(N d), the pair lambdas in O(P)O(P) and the gradient in O(Nd)O(N d), so it costs O(P+Nd)O(P + N d). Without the factorization, summing λij(xi−xj)\lambda_{ij}(x_i - x_j) over the pairs costs O(Pd)O(P d). The extra space is O(N+d)O(N + d) for the scores, the lambdas and the gradient. With a neural scorer, the factorization replaces PP back-propagations by NN.

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. Cij≥log⁡2C_{ij} \ge \log 2 when si≤sjs_i \le s_j, so C/log⁡2C / \log 2 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 ww orders all pairs, C(tw)→0C(t w) \to 0 as t→∞t \to \infty and the weights grow without bound. A weight penalty or a target Pˉij<1\bar P_{ij} < 1 fixes it.
  • Bounded pushes. ∣λij∣<σ|\lambda_{ij}| < \sigma, so one badly ordered pair cannot dominate the gradient, unlike a squared loss on the score difference.

Variants and improvements

  • LambdaRank multiplies each λij\lambda_{ij} by the change of NDCG from swapping ii and jj.
  • 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 λi\lambda_i.
  • Ties and soft targets. The target Pˉij=12(1+Sij)\bar P_{ij} = \frac{1}{2}(1 + S_{ij}) 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 log⁡(1+e−σo)\log(1 + e^{-\sigma o}) directly overflows for large −σo-\sigma o. Use the stable softplus for CijC_{ij}, and in line L4 compute 1/(1+eσo)1/(1 + e^{\sigma o}) through a stable sigmoid.
  • The sign of the update. Line L5 adds λij\lambda_{ij} 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 1/L1/L in line L7 can make the cost oscillate. The bound LL 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 ww. 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.

ranknet.pyI0RawGitHub
# 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

  1. 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)
  2. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.per_step
  • a full proof of time.total
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example