Algorithm Search⌘K

Algorithmadvanced

LambdaRank

Also called lambda gradients for ranking.

Scales each pairwise RankNet gradient by the change in nDCG that swapping the pair would cause, to optimize the metric directly.

Time
O(T (N log N + P + N d)) totalO(N log N + 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, Robert Ragno, Quoc Viet Le, 2006

LambdaRank trains a scoring function for learning to rank by gradient steps whose direction is defined directly, not derived from a cost. It starts from the per-pair gradients of RankNet and multiplies each one by ∣ΔZij∣|\Delta Z_{ij}|, the absolute change of NDCG if documents ii and jj swapped their ranks. Pairs near the top of the list, where NDCG is sensitive, get large pushes, and pairs deep in the list get small ones or none. The learning-to-rank page shows one such step on three documents; this page gives the algorithm with a cutoff kk, the closed form of ∣ΔZij∣|\Delta Z_{ij}|, the exact sense in which the lambdas are a gradient, and why they are not the gradient of NDCG. Fitting trees to the same lambdas gives LambdaMART.

In plain words

RankNet treats every wrongly ordered pair of results the same. But users look mostly at the top of a result list, so a mistake at the top costs much more than a mistake near the bottom. LambdaRank keeps the pushes of RankNet and makes each one bigger or smaller. For each pair, it asks how much the quality score of the whole list would change if the two results traded places. A pair whose swap would change the list quality a lot gets a strong push. A pair whose swap changes little gets a weak push. The method never needs the quality score to be smooth, because it only uses these pushes.

The problem

The input is a set of queries; query qq has documents with features x1,…,xnx_1, \ldots, x_n and graded labels yi∈{0,1,…}y_i \in \{0, 1, \ldots\}. The scorer is si=f(xi)s_i = f(x_i); the code uses f(x)=w⋅xf(x) = w \cdot x. The ranking sorts by score, highest first, ties to the smaller index, and rir_i is the rank of document ii. NDCG@kk uses the gain Gi=2yi−1G_i = 2^{y_i} - 1 and the discount D(r)=1/log⁡2(r+1)D(r) = 1/\log_2(r + 1) for r≤kr \le k and 0 beyond. The goal is a high mean NDCG@kk over the queries. NDCG depends on the scores only through the ranking, so it is piecewise constant in ss and its gradient is zero wherever it exists. Gradient methods cannot use it directly.

For a pair with yi>yjy_i > y_j, the swap change has the closed form

∣ΔZij∣=∣(Gi−Gj)(D(ri)−D(rj))∣IDCG@k.|\Delta Z_{ij}| = \frac{|(G_i - G_j)(D(r_i) - D(r_j))|}{\mathrm{IDCG@}k}.

The algorithm

With ρij=1/(1+eσ(si−sj))\rho_{ij} = 1/(1 + e^{\sigma(s_i - s_j)}), the RankNet gradient of a pair in sis_i is −σρij-\sigma \rho_{ij}. LambdaRank uses

λij=−σρij∣ΔZij∣,λi=∑j:yi>yjλij−∑j:yj>yiλji,\lambda_{ij} = -\sigma \rho_{ij} |\Delta Z_{ij}|, \qquad \lambda_i = \sum_{j : y_i > y_j} \lambda_{ij} - \sum_{j : y_j > y_i} \lambda_{ji},

and moves ww against ∑iλixi\sum_i \lambda_i x_i.

  1. LAMBDARANK(queries, σ, k, η, T)
  2. 1w ← 0
  3. 2repeat T times:
  4. 3for each query: s_i ← w · x_i, sort to get the ranks r_i and IDCG@k
  5. 4for each pair with y_i > y_j: λ_ij ← -σ |ΔZ_ij| / (1 + e^{σ (s_i - s_j)})
  6. 5λ_i ← Σ_j λ_ij - Σ_j λ_ji
  7. 6w ← w - η Σ_queries Σ_i λ_i x_i
  8. 7return w

Line L3 is the only place where the ranking enters. Line L4 is the RankNet gradient times the swap change. Lines L5 and L6 are the factorization of RankNet: one sum per document, then one gradient per document.

Example

One query has four documents with scores s=(0.5,1.5,1.0,2.0)s = (0.5, 1.5, 1.0, 2.0) and labels y=(2,1,0,0)y = (2, 1, 0, 0), with σ=1\sigma = 1 and no cutoff. The ranking is 3,1,2,03, 1, 2, 0 (document 3 first), so the best document is last. NDCG is 0.52960.5296, with IDCG =3.6309= 3.6309.

pair (i,j)(i, j) si−sjs_i - s_j RankNet −σρij-\sigma \rho_{ij} ∣ΔZij∣\lvert \Delta Z_{ij} \rvert λij\lambda_{ij}
(0, 1) -1.0 -0.7311 0.1103 -0.0806
(0, 2) -0.5 -0.6225 0.0573 -0.0357
(0, 3) -1.5 -0.8176 0.4704 -0.3846
(1, 2) 0.5 -0.3775 0.0361 -0.0136
(1, 3) -0.5 -0.6225 0.1016 -0.0633

The pair (0, 3) holds the best document at rank 4 and a document of label 0 at rank 1, so its swap change is by far the largest. The lambdas are λ=(−0.5009,0.0038,0.0493,0.4479)\lambda = (-0.5009, 0.0038, 0.0493, 0.4479). Plain RankNet gives (−2.1711,−0.2689,1.0,1.44)(-2.1711, -0.2689, 1.0, 1.44) on the same scores; it pushes document 1 up, while LambdaRank pushes it slightly down, because its pairs matter little for NDCG compared with the push that document 0 needs. With the cutoff k=2k = 2 the lambdas are (−0.9296,0.1252,0.0656,0.7388)(-0.9296, 0.1252, 0.0656, 0.7388): they are larger, because IDCG@2 is smaller, and they act mainly on the two documents that are or should be in the top 2.

Correctness

LambdaRank has no cost that it provably decreases, and the proof in proofs/correctness.md states what does hold.

  • The swap change. The closed form above equals the change of NDCG@kk computed by swapping the two documents and recomputing. Pairs with both ranks beyond kk get λij=0\lambda_{ij} = 0.
  • A gradient on each region. On each open region of score vectors with one fixed ranking, the weights ∣ΔZij∣|\Delta Z_{ij}| are constant, and the lambdas are the exact gradient of the weighted RankNet cost CZ(s)=∑∣ΔZij∣log⁡(1+e−σ(si−sj))C_Z(s) = \sum |\Delta Z_{ij}| \log(1 + e^{-\sigma(s_i - s_j)}), a convex function of ss. This is the observation of Burges (2010), Section 4.3. Across region boundaries the weights jump.
  • Not the gradient of NDCG. NDCG is constant on each region, so the lambdas are not its gradient. That steps along the lambdas raise NDCG is an experimental finding, which Burges (2010), Section 4.1, calls empirical.

The tests check each λij\lambda_{ij} against a finite-difference RankNet gradient times the NDCG change of the swap computed by sorting, on 200 random queries. The rise of NDCG during training on a planted set is measured, not proved.

Proof: The closed form of the swap change of NDCG, and the lambdas as a local gradientfull

One query has nn documents with labels yi∈{0,1,…}y_i \in \{0, 1, \ldots\} and scores sis_i. The ranking sorts by score, highest first, with ties to the smaller index; ri∈{1,…,n}r_i \in \{1, \ldots, n\} is the rank of document ii. The gain is Gi=2yi−1G_i = 2^{y_i} - 1, and for a cutoff kk the discount is D(r)=1/log⁡2(r+1)D(r) = 1/\log_2(r + 1) if r≤kr \le k and D(r)=0D(r) = 0 otherwise. Then DCG@k=∑iGiD(ri)\mathrm{DCG@}k = \sum_i G_i D(r_i), IDCG@k\mathrm{IDCG@}k is the DCG@kk of the order by label, and NDCG@k=DCG@k/IDCG@k\mathrm{NDCG@}k = \mathrm{DCG@}k / \mathrm{IDCG@}k when IDCG@k>0\mathrm{IDCG@}k > 0. This is the NDCG with the gain 2g−12^g - 1.

For a pair with yi>yjy_i > y_j, ∣ΔZij∣|\Delta Z_{ij}| is the absolute change of NDCG@kk when documents ii and jj swap ranks and every other document keeps its rank.

Lemma 1 (closed form).

∣ΔZij∣=∣(Gi−Gj)(D(rj)−D(ri))∣IDCG@k.|\Delta Z_{ij}| = \frac{\left| (G_i - G_j) \left( D(r_j) - D(r_i) \right) \right|}{\mathrm{IDCG@}k}.

Proof. The swap leaves the ideal DCG and the terms of all other documents unchanged. Before the swap the two terms are GiD(ri)+GjD(rj)G_i D(r_i) + G_j D(r_j), after it GiD(rj)+GjD(ri)G_i D(r_j) + G_j D(r_i). The difference is (Gi−Gj)(D(rj)−D(ri))(G_i - G_j)(D(r_j) - D(r_i)). Divide by IDCG@k\mathrm{IDCG@}k. □\square

Two consequences follow. If both ranks are beyond kk, D(ri)=D(rj)=0D(r_i) = D(r_j) = 0 and the lambda of the pair is 0, so pairs deep in the list do not move. If Gi=GjG_i = G_j, the pair is not formed at all, since only pairs with yi>yjy_i > y_j enter.

Definition (the lambdas). With ρij=1/(1+eσ(si−sj))\rho_{ij} = 1/(1 + e^{\sigma (s_i - s_j)}), the RankNet gradient of the pair cost log⁡(1+e−σ(si−sj))\log(1 + e^{-\sigma(s_i - s_j)}) in sis_i is −σρij-\sigma \rho_{ij} (see the RankNet proof). LambdaRank sets

λij=−σρij∣ΔZij∣,λi=∑j:yi>yjλij−∑j:yj>yiλji.\lambda_{ij} = -\sigma \rho_{ij} |\Delta Z_{ij}|, \qquad \lambda_i = \sum_{j : y_i > y_j} \lambda_{ij} - \sum_{j : y_j > y_i} \lambda_{ji}.

This is Equation (6) of Burges (2010), Section 4.1, written with the sign of a cost to minimize. Lines L3 to L5 of the code compute the ranks, then λij\lambda_{ij} by Lemma 1, then λi\lambda_i. Each λij\lambda_{ij} enters λi\lambda_i and λj\lambda_j with opposite signs, so the lambdas of a query sum to zero.

Lemma 2 (the lambdas are a gradient where the ranking is fixed). Let UU be the open set of score vectors with no ties and the same ranking as a given s0s^0. On UU the weights ∣ΔZij∣|\Delta Z_{ij}| are constant, and the vector (λ1,…,λn)(\lambda_1, \ldots, \lambda_n) is the gradient of

CZ(s)=∑(i,j):yi>yj∣ΔZij∣log⁡(1+e−σ(si−sj)).C_Z(s) = \sum_{(i, j) : y_i > y_j} |\Delta Z_{ij}| \log\left(1 + e^{-\sigma (s_i - s_j)}\right).

Proof. On UU every rank rir_i is constant, so by Lemma 1 every weight is constant. CZC_Z is then a weighted RankNet cost with fixed weights, and the computation of Lemma 1 of the RankNet proof, term by term, gives ∂CZ/∂si=λi\partial C_Z / \partial s_i = \lambda_i. □\square

So on each region of fixed ranking, a LambdaRank step is a gradient step on a convex function of the scores, which is the observation of Burges (2010), Section 4.3. At the boundary of the regions, where two scores tie, the weights jump, and no single function has the lambdas as its gradient everywhere.

What the lambdas are not. NDCG@kk is constant on each region UU, so its gradient in ss is zero wherever it exists. The lambdas are therefore not the gradient of NDCG. The claim that steps along the lambdas raise NDCG is supported by experiments, which Burges (2010) calls empirical. Wang et al. (2018) later placed LambdaRank in a framework of well-defined losses and described it as the minimization of a coarse upper bound on an NDCG-based cost; that analysis is not repeated here.

The tests in impl/python/test_lambdarank.py check, on 200 random queries with several σ\sigma and kk, that each λij\lambda_{ij} equals a finite-difference RankNet gradient times the NDCG change of the swap computed by sorting the swapped list. They also check Lemma 1 against the direct swap, Lemma 2 against finite differences of CZC_Z, the zero lambdas below the cutoff, the zero sum, and the worked example of the page. The rise of NDCG during training is measured on one planted set and is not a theorem.

Complexity

One step sorts each query, O(nqlog⁡nq)O(n_q \log n_q), and computes IDCG. Each pair then costs O(1)O(1) by the closed form, so the lambdas cost O(P)O(P) for PP pairs, and line L6 costs O(Nd)O(N d) for NN documents. The total per step is O(Nlog⁡N+P+Nd)O(N \log N + P + N d). Recomputing NDCG for each swap would cost O(nq)O(n_q) per pair, O(Pn)O(P n) in total, which the closed form avoids. With a cutoff kk, only pairs with at least one rank at most kk have nonzero lambdas, which leaves O(knq)O(k n_q) pairs per query. The extra space is O(N+d)O(N + d).

Properties

  • Zero sum. The lambdas of a query sum to zero, as in RankNet.
  • Local to the top. With a cutoff kk, documents whose pairs all lie below rank kk get no push.
  • Scale. Each ∣ΔZij∣≤1|\Delta Z_{ij}| \le 1, so every ∣λij∣<σ|\lambda_{ij}| < \sigma.
  • Any metric with a swap change. The same recipe works with the swap change of ERR, MRR or MAP in place of NDCG.
  • No cost function in general. The lambdas are a gradient only inside each region of fixed ranking. Line searches and convergence tests that need a cost value use CZC_Z of the current region, which changes when the ranking changes.

Variants and improvements

  • LambdaMART fits gradient-boosted regression trees to the lambdas, with a Newton step in each leaf, and is the most used form.
  • LambdaLoss. Wang et al. (2018) give a family of well-defined losses that contains LambdaRank as one case, and propose new losses inside the family.
  • Other metrics. Replace ∣ΔZij∣|\Delta Z_{ij}| by the swap change of the metric that matters, for example ERR when a user is likely to stop at the first very good result.
  • Neural scorers. The original setting: line L6 becomes back-propagation of λi\lambda_i through the network.

When to use it

Use LambdaRank when the target metric weights the top of the list, such as NDCG@10, and the scorer is trained by gradients, for example a neural network. With hand-made features and tree models, use LambdaMART. If the metric weights all pairs equally, as AUC does, RankNet or the Ranking SVM is simpler and the weights add nothing. The advantage of LambdaRank over RankNet on NDCG is a measured result.

Pitfalls

  • The ranks come from the current scores. Line L3 must sort by the current ss, not by the labels or by stale scores. With the ideal ranks, every pair of the closed form is computed at the wrong positions.
  • Ties in the scores. At the start, all scores are 0. Line L3 needs a fixed tie rule, such as the smaller index first, or the ranks and the lambdas change from run to run.
  • Queries with no relevant document. IDCG@kk is 0 when every label in the top kk of the ideal order is 0. Line L4 must skip such queries rather than divide by zero.
  • Treating the lambdas as a cost. Monitoring ∑λi2\sum \lambda_i^2 or a RankNet cost does not track NDCG. Monitor NDCG@kk on validation queries.
  • The sign. Line L4 gives the gradient of a cost to minimize, so line L6 subtracts it. Adding it moves every pair the wrong way. Texts that write the lambdas as the direction to move up use the opposite sign, so check the convention before mixing code.

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.

lambdarank.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lambdarank/. The authors are listed in prov/6YEMD5.jsonl.

"""LambdaRank lambdas for a linear scoring function s = w . x.

For a pair (i, j) of one query with y[i] > y[j], RankNet has the gradient

    dC_ij/ds_i = -sigma / (1 + exp(sigma (s_i - s_j))).

LambdaRank multiplies it by |delta NDCG_ij|, the change of NDCG@k when the
documents i and j swap their positions in the current ranking, and sums
the results per document:

    lambda_i = sum over j with y_i > y_j of lambda_ij
             - sum over j with y_j > y_i of lambda_ji.

The lambdas are defined directly. They are not the gradient of NDCG, which
is flat almost everywhere. The update is w <- w - eta sum_i lambda_i x_i.
NDCG uses the gain 2^g - 1 and the discount 1 / log2(rank + 1), and the
ranking sorts by score descending, then by index ascending.
"""

import math


def dot(a, b):
    return sum(p * q for p, q in zip(a, b))


def sigmoid(z):
    if z >= 0:
        return 1.0 / (1.0 + math.exp(-z))
    e = math.exp(z)
    return e / (1.0 + e)


def softplus(z):
    if z > 0:
        return z + math.log1p(math.exp(-z))
    return math.log1p(math.exp(z))


def scores(w, xs):
    return [dot(w, x) for x in xs]


def ranking(s):
    """Indices by score descending, then index ascending."""
    return sorted(range(len(s)), key=lambda i: (-s[i], i))


def gain(g):
    return 2 ** g - 1


def discount(r):
    """The discount of rank r (r starts at 1)."""
    return 1.0 / math.log2(r + 1)


def ideal_dcg(y, k):
    return sum(gain(g) * discount(r + 1) for r, g in enumerate(sorted(y, reverse=True)[:k]))


def ndcg_of_order(order, y, k=None):
    """NDCG@k of a given order of the documents; None if no positive label."""
    k = len(y) if k is None else k
    ideal = ideal_dcg(y, k)
    if ideal == 0:
        return None
    return sum(gain(y[d]) * discount(r + 1) for r, d in enumerate(order[:k])) / ideal


def ndcg(s, y, k=None):
    return ndcg_of_order(ranking(s), y, k)


def delta_ndcg(s, y, k=None):
    """|delta NDCG_ij| for every pair, by the closed form.

    With r_i the rank of i in the current ranking, the swap changes DCG@k
    by (gain(y_i) - gain(y_j)) (D(r_j) - D(r_i)), where D(r) is the
    discount of rank r if r <= k and 0 otherwise.
    """
    n = len(y)
    k = n if k is None else k
    ideal = ideal_dcg(y, k)
    rank = [0] * n
    for r, d in enumerate(ranking(s)):                                   # @line L3
        rank[d] = r + 1
    disc = [discount(rank[i]) if rank[i] <= k else 0.0 for i in range(n)]
    out = {}
    for i in range(n):
        for j in range(n):
            if y[i] > y[j]:
                out[(i, j)] = 0.0 if ideal == 0 else abs((gain(y[i]) - gain(y[j])) * (disc[j] - disc[i])) / ideal
    return out


def ranknet_pair_gradient(s, i, j, sigma=1.0):
    """dC_ij/ds_i of the RankNet cost log(1 + exp(-sigma (s_i - s_j)))."""
    return -sigma * sigmoid(-sigma * (s[i] - s[j]))


def pair_lambdas(s, y, sigma=1.0, k=None):
    """lambda_ij for every pair with y_i > y_j."""
    dz = delta_ndcg(s, y, k)
    return {(i, j): ranknet_pair_gradient(s, i, j, sigma) * v for (i, j), v in dz.items()}   # @line L4


def lambdas(s, y, sigma=1.0, k=None):
    """The per-document lambdas (Burges 2010, Section 4.1)."""
    lam = [0.0] * len(s)
    for (i, j), v in pair_lambdas(s, y, sigma, k).items():
        lam[i] += v                                                      # @line L5
        lam[j] -= v
    return lam


def frozen_cost(s, y, weights, sigma=1.0):
    """sum of |delta Z_ij| log(1 + exp(-sigma (s_i - s_j))) with fixed weights.

    For scores near s with the same ranking, the gradient of this function
    in s is the lambda vector (Burges 2010, Section 4.3).
    """
    return sum(v * softplus(-sigma * (s[i] - s[j])) for (i, j), v in weights.items())


def direction(w, queries, sigma=1.0, k=None):
    """sum over queries and documents of lambda_i x_i."""
    g = [0.0] * len(w)
    for xs, y in queries:
        lam = lambdas(scores(w, xs), y, sigma, k)
        for li, x in zip(lam, xs):
            for c in range(len(w)):
                g[c] += li * x[c]
    return g


def train(queries, d, eta=0.1, sigma=1.0, k=None, steps=100):
    """Full-batch steps w <- w - eta * direction, from w = 0.

    Returns w and the mean NDCG@k after each step. Nothing guarantees that
    the mean NDCG grows; it is measured.
    """
    w = [0.0] * d                                                        # @line L1
    history = [mean_ndcg(w, queries, k)]
    for _ in range(steps):                                               # @line L2
        g = direction(w, queries, sigma, k)
        w = [a - eta * b for a, b in zip(w, g)]                          # @line L6
        history.append(mean_ndcg(w, queries, k))
    return w, history                                                    # @line L7


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_lambdarank.py 141 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lambdarank/. The authors are listed in prov/6YEMD5.jsonl.

import math
import random

from lambdarank import (
    delta_ndcg,
    frozen_cost,
    lambdas,
    ndcg,
    ndcg_of_order,
    pair_lambdas,
    ranking,
    softplus,
    train,
)


def planted(seed, n_queries=8, n_docs=6, 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 swapped_ndcg_change(s, y, i, j, k=None):
    """|NDCG after swapping the positions of i and j - NDCG now|, computed directly."""
    order = ranking(s)
    a, b = order.index(i), order.index(j)
    new = list(order)
    new[a], new[b] = new[b], new[a]
    return abs(ndcg_of_order(new, y, k) - ndcg_of_order(order, y, k))


def ranknet_pair_gradient_numeric(s, i, j, sigma, h=1e-6):
    def c(v):
        return softplus(-sigma * (v[i] - v[j]))

    a = list(s)
    b = list(s)
    a[i] += h
    b[i] -= h
    return (c(a) - c(b)) / (2 * h)


def test_page_example():
    # Four documents with labels 2, 1, 0, 0 and scores 0.5, 1.5, 1.0, 2.0.
    s = [0.5, 1.5, 1.0, 2.0]
    y = [2, 1, 0, 0]
    assert ranking(s) == [3, 1, 2, 0]
    assert abs(ndcg(s, y) - 0.5296) < 1e-4
    lam = lambdas(s, y)
    assert [round(v, 4) for v in lam] == [-0.5009, 0.0038, 0.0493, 0.4479]
    lam2 = lambdas(s, y, k=2)
    assert [round(v, 4) for v in lam2] == [-0.9296, 0.1252, 0.0656, 0.7388]


def test_lambda_is_ranknet_gradient_times_swap_change():
    rng = random.Random(1)
    for trial in range(200):
        n = rng.randint(2, 7)
        y = [rng.randint(0, 3) for _ in range(n)]
        s = [rng.uniform(-2, 2) for _ in range(n)]
        sigma = rng.choice([0.5, 1.0, 2.0])
        k = rng.choice([None, 1, 2, 3, 5])
        if ndcg(s, y, k) is None:
            continue
        lam = pair_lambdas(s, y, sigma, k)
        for (i, j), v in lam.items():
            direct = ranknet_pair_gradient_numeric(s, i, j, sigma) * swapped_ndcg_change(s, y, i, j, k)
            assert abs(v - direct) < 1e-6


def test_closed_form_delta_equals_direct_swap():
    rng = random.Random(2)
    for _ in range(200):
        n = rng.randint(2, 7)
        y = [rng.randint(0, 3) for _ in range(n)]
        s = [rng.uniform(-2, 2) for _ in range(n)]
        k = rng.choice([None, 1, 2, 4])
        if ndcg(s, y, k) is None:
            continue
        for (i, j), v in delta_ndcg(s, y, k).items():
            assert abs(v - swapped_ndcg_change(s, y, i, j, k)) < 1e-12


def test_lambdas_are_gradient_of_frozen_cost():
    rng = random.Random(3)
    h = 1e-6
    for _ in range(50):
        n = rng.randint(2, 6)
        y = [rng.randint(0, 2) for _ in range(n)]
        s = [rng.uniform(-2, 2) for _ in range(n)]
        if ndcg(s, y) is None:
            continue
        weights = delta_ndcg(s, y)
        lam = lambdas(s, y)
        for c in range(n):
            a = list(s)
            b = list(s)
            a[c] += h
            b[c] -= h
            num = (frozen_cost(a, y, weights) - frozen_cost(b, y, weights)) / (2 * h)
            assert abs(num - lam[c]) < 1e-6


def test_pairs_below_cutoff_get_zero():
    s = [4.0, 3.0, 2.0, 1.0]
    y = [0, 0, 1, 2]
    lam = pair_lambdas(s, y, k=2)
    assert lam[(3, 2)] == 0.0
    assert lam[(3, 0)] != 0.0


def test_lambdas_sum_to_zero():
    rng = random.Random(4)
    for _ in range(50):
        y = [rng.randint(0, 3) for _ in range(5)]
        s = [rng.uniform(-1, 1) for _ in range(5)]
        assert abs(sum(lambdas(s, y))) < 1e-12


def test_training_on_planted_set():
    # Measured on this planted set, not a theorem.
    queries = planted(seed=5)
    w, history = train(queries, 3, eta=0.5, steps=60)
    assert history[-1] > history[0]
    assert max(history) > 0.9


def test_no_relevant_document():
    assert ndcg([1.0, 2.0], [0, 0]) is None
    assert lambdas([1.0, 2.0], [0, 0]) == [0.0, 0.0]
    assert math.isclose(ndcg([2.0, 1.0], [1, 0]), 1.0)

History

Burges, Ragno and Le (2006) observed that one does not need a smooth cost to train a ranker by gradient descent: it is enough to specify the gradient of each document's score, and they chose the RankNet gradient times the NDCG change of a swap. Burges (2010) reviewed the method together with RankNet and LambdaMART, stated when the lambdas are the gradient of a cost, and called the optimization of NDCG empirical. Wang et al. (2018) later embedded LambdaRank in a framework of well-defined losses.

References

  1. Christopher J. C. Burges, Robert Ragno and Quoc Viet Le, Learning to rank with nonsmooth cost functions, Advances in Neural Information Processing Systems 19 (NIPS 2006), MIT Press, 2007, pp. 193-200 (defining the gradients of a nonsmooth ranking cost directly, with NDCG as the main case)
  2. Christopher J. C. Burges, From RankNet to LambdaRank to LambdaMART: an overview, Microsoft Research Technical Report MSR-TR-2010-82, 2010, Section 4.1 and Equation (6) (the lambdas scaled by the NDCG change of a swap, called empirically optimizing NDCG) and Section 4.3 (when the lambdas are a gradient)
  3. Xuanhui Wang, Cheng Li, Nadav Golbandi, Michael Bendersky and Marc Najork, The LambdaLoss framework for ranking metric optimization, Proceedings of the 27th ACM CIKM, 2018, pp. 1313-1322 (a loss framework in which LambdaRank is a special case)

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
  • a scene preset for the example