Algorithm Search⌘K

Algorithmcore

Ranking SVM

Also called RankSVM.

Learns a linear scoring function by solving an SVM on pairwise preferences between documents of the same query.

Time
O(T P d) totalO(P d) per_step
Space
O(P d) extra
Where
P = the number of preferred pairs; T = the number of steps; d = the number of features
Properties
deterministicnot exactofflineiterative
Origin
Ralf Herbrich, Thore Graepel, Klaus Obermayer, Thorsten Joachims, 2000

Ranking SVM learns a linear scoring function f(x)=w⋅xf(x) = w \cdot x for learning to rank. For each query and each two of its documents with different labels, it asks that the better document score at least 1 more than the worse one, and it pays the hinge loss when it does not. With the norm penalty of a support vector machine, this is an SVM on the difference vectors xi−xjx_i - x_j. The learning-to-rank page states the problem and lists the methods; this page gives the objective, a solver with a proved rate, and what a low objective guarantees about the order of the training pairs. RankNet uses the same pairs with the logistic loss in place of the hinge loss.

In plain words

For each search request we know which results are better than which. Take two results of the same request, a better one and a worse one. We want a scoring rule that gives the better one a clearly higher score. Each such pair is a small test, and the rule loses points on every pair that it gets wrong or gets right by too little. We also keep the rule simple, so that it does not chase noise. The method finds the rule that balances these two costs. It never compares results of two different requests, because their scores do not need to match. When the cost is small enough, every training pair comes out in the right order.

The problem

The input is a set of queries. Query qq has documents with feature vectors xq,1,…,xq,nq∈Rdx_{q,1}, \ldots, x_{q,n_q} \in \mathbb R^d and integer labels yq,iy_{q,i}. The preferred pairs are the PP pairs (i,j)(i, j) of one query with yq,i>yq,jy_{q,i} > y_{q,j}, and z=xq,i−xq,jz = x_{q,i} - x_{q,j} is the pair vector. The output is w∈Rdw \in \mathbb R^d, and a new query is ranked by sorting its documents by w⋅xw \cdot x, ties to the smaller id. For λ>0\lambda > 0, the objective is

J(w)=λ2∥w∥2+1P∑k=1Pmax⁡(0,1−w⋅zk).J(w) = \frac{\lambda}{2} \lVert w \rVert^2 + \frac{1}{P} \sum_{k=1}^{P} \max(0, 1 - w \cdot z_k).

Joachims (2002) writes the same problem with slack variables ξk≥1−w⋅zk\xi_k \ge 1 - w \cdot z_k, ξk≥0\xi_k \ge 0 and the constant CC in place of 1/(λP)1/(\lambda P). Pairs from different queries never form a pair, so the scores of different queries need not be on one scale.

The algorithm

The code solves the objective with the projected subgradient method of Pegasos, run on the full set of pairs.

  1. RANKING-SVM(queries, λ, T)
  2. 1Z ← the vectors x_i - x_j for all pairs of one query with y_i > y_j
  3. 2w ← 0, R ← sqrt(2 / λ), best ← w
  4. 3for t ← 1 to T:
  5. 4g ← λ w - (1 / P) Σ { z ∈ Z : w · z < 1 } z
  6. 5w ← w - g / (λ t)
  7. 6if ‖w‖ > R: w ← w R / ‖w‖
  8. 7if J(w) < J(best): best ← w
  9. 8return best

Line L4 is a subgradient of JJ at ww: the pairs with margin below 1 push ww toward their direction, and the penalty pulls it toward 0. Line L5 takes the step 1/(λt)1/(\lambda t), which suits a λ\lambda-strongly convex objective. Line L6 projects back onto the ball of radius 2/λ\sqrt{2/\lambda}, which holds the minimizer because λ2∥w∗∥2≤J(w∗)≤J(0)=1\frac{\lambda}{2}\lVert w^* \rVert^2 \le J(w^*) \le J(0) = 1. The subgradient method is not a descent method, so line L7 keeps the best iterate.

Example

One query has three documents A, B and C with the features (2,0)(2, 0), (1,1)(1, 1), (0,1)(0, 1) and the labels 2, 1, 0. The pairs are A over B, A over C and B over C, with z1=(1,−1)z_1 = (1, -1), z2=(2,−1)z_2 = (2, -1), z3=(1,0)z_3 = (1, 0), so P=3P = 3. Take λ=0.1\lambda = 0.1, so R=20≈4.472R = \sqrt{20} \approx 4.472.

tt pairs with w⋅z<1w \cdot z < 1 gg projected ww after the step J(w)J(w) best JJ
1 all three (−1.3333,0.6667)(-1.3333, 0.6667) yes (4,−2)(4, -2) 1.0000 1.0000
2 none (0.4,−0.2)(0.4, -0.2) no (2,−1)(2, -1) 0.2500 0.2500
3 none (0.2,−0.1)(0.2, -0.1) no (1.3333,−0.6667)(1.3333, -0.6667) 0.1111 0.1111
4 none (0.1333,−0.0667)(0.1333, -0.0667) no (1,−0.5)(1, -0.5) 0.0625 0.0625
5 none (0.1,−0.05)(0.1, -0.05) no (0.8,−0.4)(0.8, -0.4) 0.1067 0.0625
6 z3z_3 (−0.2533,−0.04)(-0.2533, -0.04) no (1.2222,−0.3333)(1.2222, -0.3333) 0.0802 0.0625

At step 5 the penalty has pulled ww so far that w⋅z3=0.8<1w \cdot z_3 = 0.8 < 1 and JJ rises, which is why line L7 keeps the best iterate. The minimizer is w∗=(1,0)w^* = (1, 0) with J∗=0.05J^* = 0.05: it gives the margins 1, 2 and 1, so every hinge term is 0. The dual point that puts the weight 0.30.3 on z3z_3 and 0 on the other pairs has the dual value 0.050.05, which proves that 0.050.05 is optimal (see the proof file). After 100 steps the best JJ is within 2.3⋅10−52.3 \cdot 10^{-5} of J∗J^*, and after 1000 steps within 2.0⋅10−72.0 \cdot 10^{-7}. The learned ww ranks A, B, C, the order of the labels.

Correctness

The proof in proofs/correctness.md shows four things.

  • Rate. With G=λR+max⁡k∥zk∥G = \lambda R + \max_k \lVert z_k \rVert, the best of the first TT iterates has J−J∗≤G2(1+ln⁡T)/(2λT)J - J^* \le G^2(1 + \ln T)/(2 \lambda T). The proof combines the strong convexity inequality of the subgradient with the step 1/(λt)1/(\lambda t), and the terms in the distance to w∗w^* telescope.
  • A dual lower bound. For α∈[0,1]P\alpha \in [0, 1]^P, D(α)=1P∑kαk−12λP2∥∑kαkzk∥2≤J(w)D(\alpha) = \frac{1}{P}\sum_k \alpha_k - \frac{1}{2\lambda P^2} \lVert \sum_k \alpha_k z_k \rVert^2 \le J(w) for every ww. Exact coordinate ascent on DD gives the reference values that the tests use.
  • Pairs. The number of training pairs that ww misorders is at most P J(w)P\, J(w), so J(w)<1/PJ(w) < 1/P means that every training pair is in the right order. This is the bound of Joachims (2002) that the slack sum bounds the number of discordant pairs, which is the Kendall tau distance to the label order over pairs with different labels.
  • Separable data. If some uu has u⋅zk≥1u \cdot z_k \ge 1 for all kk and λ2∥u∥2<1/P\frac{\lambda}{2}\lVert u \rVert^2 < 1/P, the best iterate orders every training pair correctly after finitely many steps.

All four are statements about the training pairs. How well the learned ww ranks new queries is measured, not proved.

Proof: The projected subgradient method for the Ranking SVM converges at rate log T over T, and a small objective orders every pairfull

The training set gives PP pairs. For each query and each two of its documents with yi>yjy_i > y_j, the pair vector is z=xi−xjz = x_i - x_j. Pairs never mix two queries. For λ>0\lambda > 0 the objective is

J(w)=λ2∥w∥2+1P∑k=1Pmax⁡(0,1−w⋅zk).J(w) = \frac{\lambda}{2} \lVert w \rVert^2 + \frac{1}{P} \sum_{k=1}^{P} \max(0, 1 - w \cdot z_k).

JJ is λ\lambda-strongly convex, as the sum of λ2∥w∥2\frac{\lambda}{2}\lVert w \rVert^2 and a convex function, so it has one minimizer w∗w^*. Let J∗=J(w∗)J^* = J(w^*).

Lemma 1 (a ball that holds w∗w^*). ∥w∗∥≤R=2/λ\lVert w^* \rVert \le R = \sqrt{2/\lambda}.

Proof. λ2∥w∗∥2≤J(w∗)≤J(0)=1\frac{\lambda}{2} \lVert w^* \rVert^2 \le J(w^*) \le J(0) = 1. □\square

Lemma 2 (subgradient). The vector g(w)=λw−1P∑k:w⋅zk<1zkg(w) = \lambda w - \frac{1}{P} \sum_{k : w \cdot z_k < 1} z_k of line L4 satisfies, for all uu,

J(u)≥J(w)+g(w)⋅(u−w)+λ2∥u−w∥2.J(u) \ge J(w) + g(w) \cdot (u - w) + \frac{\lambda}{2} \lVert u - w \rVert^2.

If ∥w∥≤R\lVert w \rVert \le R, then ∥g(w)∥≤G=λR+max⁡k∥zk∥\lVert g(w) \rVert \le G = \lambda R + \max_k \lVert z_k \rVert.

Proof. For the hinge term hk(w)=max⁡(0,1−w⋅zk)h_k(w) = \max(0, 1 - w \cdot z_k), the vector −zk-z_k is a subgradient where w⋅zk<1w \cdot z_k < 1 and 00 is a subgradient elsewhere, so hk(u)≥hk(w)+(that vector)⋅(u−w)h_k(u) \ge h_k(w) + (\text{that vector}) \cdot (u - w). For the quadratic term, λ2∥u∥2=λ2∥w∥2+λw⋅(u−w)+λ2∥u−w∥2\frac{\lambda}{2}\lVert u \rVert^2 = \frac{\lambda}{2}\lVert w \rVert^2 + \lambda w \cdot (u - w) + \frac{\lambda}{2}\lVert u - w \rVert^2. Add the two. The norm bound is the triangle inequality, since the average of at most PP vectors zkz_k divided by PP has norm at most max⁡k∥zk∥\max_k \lVert z_k \rVert. □\square

Theorem (rate). Let w1=0w_1 = 0 and wt+1=Π(wt−ηtg(wt))w_{t+1} = \Pi(w_t - \eta_t g(w_t)) with ηt=1/(λt)\eta_t = 1/(\lambda t), where Π\Pi is the projection onto the ball of radius RR (lines L2 to L6). Then

min⁡1≤t≤TJ(wt)−J∗≤G2(1+ln⁡T)2λT.\min_{1 \le t \le T} J(w_t) - J^* \le \frac{G^2 (1 + \ln T)}{2 \lambda T}.

Proof. Write dt=∥wt−w∗∥2d_t = \lVert w_t - w^* \rVert^2 and gt=g(wt)g_t = g(w_t). The projection onto a convex set that holds w∗w^* (Lemma 1) does not increase the distance to w∗w^*, so dt+1≤dt−2ηtgt⋅(wt−w∗)+ηt2∥gt∥2d_{t+1} \le d_t - 2 \eta_t g_t \cdot (w_t - w^*) + \eta_t^2 \lVert g_t \rVert^2. Hence

gt⋅(wt−w∗)≤dt−dt+12ηt+ηtG22.g_t \cdot (w_t - w^*) \le \frac{d_t - d_{t+1}}{2 \eta_t} + \frac{\eta_t G^2}{2}.

Lemma 2 with u=w∗u = w^* and w=wtw = w_t gives J(wt)−J∗≤gt⋅(wt−w∗)−λ2dtJ(w_t) - J^* \le g_t \cdot (w_t - w^*) - \frac{\lambda}{2} d_t. With 1/ηt=λt1/\eta_t = \lambda t,

J(wt)−J∗≤λ(t−1)2dt−λt2dt+1+G22λt.J(w_t) - J^* \le \frac{\lambda (t - 1)}{2} d_t - \frac{\lambda t}{2} d_{t+1} + \frac{G^2}{2 \lambda t}.

Summing over t=1,…,Tt = 1, \ldots, T, the first two terms telescope to 0⋅d1−λT2dT+1≤00 \cdot d_1 - \frac{\lambda T}{2} d_{T+1} \le 0, and ∑t≤T1/t≤1+ln⁡T\sum_{t \le T} 1/t \le 1 + \ln T. So ∑t=1T(J(wt)−J∗)≤G22λ(1+ln⁡T)\sum_{t=1}^{T} (J(w_t) - J^*) \le \frac{G^2}{2\lambda}(1 + \ln T), and the minimum is at most the mean. □\square

The code keeps the best iterate seen (line L7), which includes w1,…,wTw_1, \ldots, w_T, so its value JbestJ_{\text{best}} meets the bound. The best values never increase from one step to the next by construction.

Lemma 3 (weak duality). For α∈[0,1]P\alpha \in [0, 1]^P let

D(α)=1P∑kαk−12λP2∥∑kαkzk∥2.D(\alpha) = \frac{1}{P} \sum_k \alpha_k - \frac{1}{2 \lambda P^2} \Big\lVert \sum_k \alpha_k z_k \Big\rVert^2.

Then D(α)≤J(w)D(\alpha) \le J(w) for every ww. The coordinate step αk←clip⁡[0,1](αk+(λP−zk⋅v)/∥zk∥2)\alpha_k \leftarrow \operatorname{clip}_{[0,1]}\left(\alpha_k + (\lambda P - z_k \cdot v)/\lVert z_k \rVert^2\right), with v=∑lαlzlv = \sum_l \alpha_l z_l, maximizes DD over αk\alpha_k with the others fixed.

Proof. For αk∈[0,1]\alpha_k \in [0, 1], max⁡(0,1−w⋅zk)≥αk(1−w⋅zk)\max(0, 1 - w \cdot z_k) \ge \alpha_k (1 - w \cdot z_k). So J(w)≥λ2∥w∥2+1P∑kαk−1Pw⋅vJ(w) \ge \frac{\lambda}{2}\lVert w \rVert^2 + \frac{1}{P} \sum_k \alpha_k - \frac{1}{P} w \cdot v. The right side is a convex quadratic in ww, minimized at w=v/(λP)w = v / (\lambda P) with the value D(α)D(\alpha). For the coordinate step, DD along αk+δ\alpha_k + \delta is the concave parabola D(α)+δP−12λP2(2δ zk⋅v+δ2∥zk∥2)D(\alpha) + \frac{\delta}{P} - \frac{1}{2\lambda P^2}(2 \delta\, z_k \cdot v + \delta^2 \lVert z_k \rVert^2), whose maximum over δ\delta is at δ=(λP−zk⋅v)/∥zk∥2\delta = (\lambda P - z_k \cdot v)/\lVert z_k \rVert^2; clipping to the interval keeps the maximum of a concave function over an interval. □\square

So Jbest−J∗≤Jbest−D(α)J_{\text{best}} - J^* \le J_{\text{best}} - D(\alpha) for any α\alpha, which the tests use to check the theorem without knowing J∗J^*.

Lemma 4 (a small objective orders every pair). If J(w)<1/PJ(w) < 1/P, then w⋅xi>w⋅xjw \cdot x_i > w \cdot x_j for every pair with yi>yjy_i > y_j. Also, the number of pairs that ww misorders is at most P J(w)P\, J(w).

Proof. A pair with w⋅zk≤0w \cdot z_k \le 0 has hinge loss at least 1, so it adds at least 1/P1/P to J(w)J(w). So J(w)≥(number of misordered pairs)/PJ(w) \ge (\text{number of misordered pairs}) / P, which gives both claims. □\square

The number of misordered pairs of one query is the Kendall tau distance between the order by ww and the order by label, counted over the pairs with different labels. Lemma 4 is the bound of Joachims (2002) that the hinge sum is an upper bound on it.

Corollary (separable data). If some uu has u⋅zk≥1u \cdot z_k \ge 1 for all kk and λ2∥u∥2<1/P\frac{\lambda}{2} \lVert u \rVert^2 < 1/P, then J∗<1/PJ^* < 1/P, and by the theorem the best iterate reaches Jbest<1/PJ_{\text{best}} < 1/P after finitely many steps, after which it orders every pair correctly.

Proof. J∗≤J(u)=λ2∥u∥2J^* \le J(u) = \frac{\lambda}{2} \lVert u \rVert^2. The bound of the theorem tends to 0, so it falls below 1/P−J∗1/P - J^* for some TT. Apply Lemma 4. □\square

What is not proved. All statements are about the training pairs. The quality of the ranking on new queries is a matter of measurement, and the margin theory of SVMs bounds it only under assumptions on how the queries are drawn.

The tests in impl/python/test_ranking_svm.py check the inequality of Lemma 2 on random points, the theorem against the dual lower bound of Lemma 3 for two values of λ\lambda and three values of TT, weak duality, Lemma 4 on random points around a separating vector, the corollary on a planted separable instance, and the worked example of the page.

Complexity

A query with nn documents gives at most n(n−1)/2n(n - 1)/2 pairs, so P≤∑qnq2/2P \le \sum_q n_q^2 / 2. Line L1 costs O(Pd)O(P d) time and stores O(Pd)O(P d) numbers. Each step computes w⋅zw \cdot z for all pairs, adds the active ones and evaluates JJ, so it costs O(Pd)O(P d) time; TT steps cost O(TPd)O(T P d). The space beyond the input is O(Pd)O(P d) for the pair vectors, or O(d)O(d) if the pairs are formed on the fly from the documents. The rate bound shows that T=O(G2/(λε)log⁡(1/ε))T = O(G^2 / (\lambda \varepsilon) \log(1/\varepsilon)) steps reach accuracy ε\varepsilon. A stochastic version, as in Pegasos, samples one pair per step and costs O(d)O(d) per step.

Properties

  • Convex. The objective is λ\lambda-strongly convex and has one minimizer. Any solver that reaches it gives the same ww.
  • Linear in the features. The model is w⋅xw \cdot x. The kernel trick applies to the dual, with the kernel of a pair ⟨xi−xj,xk−xl⟩\langle x_i - x_j, x_k - x_l \rangle expanded into four kernel values.
  • Only order within a query matters. Adding the same vector to all documents of a query does not change any pair vector.
  • Few active pairs. At the optimum, the pairs with margin above 1 have dual weight 0 and do not affect ww. In the example only z3z_3 has a positive dual weight.
  • Equal weight per pair. A misordered pair at ranks 1 and 2 costs the same as one at ranks 50 and 51. The objective does not know about the top of the list.

Variants and improvements

  • Cutting planes. Joachims (2006) trains linear SVMs, including a ranking formulation, with a cutting-plane method whose work grows linearly with the data.
  • Dual coordinate ascent. The method of the proof file, one dual weight at a time, converges fast on small problems and gives a duality gap as a stopping test.
  • Stochastic subgradient. Sample one pair per step. This is Pegasos with pairs as the examples, and it scales to very large PP.
  • Bipartite labels. With labels in {0,1}\{0, 1\}, the fraction of pairs in the right order is the area under the ROC curve, so the method maximizes a convex bound on AUC.
  • Query and position weights. Weight each pair by its query or by a cost that grows near the top. LambdaRank weights by the change of NDCG; the propensity SVM-Rank of Joachims, Swaminathan and Schnabel (2017) weights by the inverse examination propensity (see unbiased learning to rank).
  • Other losses on the same pairs. The logistic loss gives RankNet, and the exponential loss gives RankBoost.

When to use it

Use Ranking SVM when the features are good, the model can be linear, and you want a convex problem with a unique answer and a clean stopping test. It is a strong first baseline, and its pair data come directly from click logs in the way Joachims (2002) proposed. If the metric cares much more about the top positions than about the rest, LambdaMART usually ranks better on feature-based benchmarks, which is a measured result. If the model must be nonlinear, use trees or a neural scorer.

Pitfalls

  • Pairs across queries. Line L1 must form pairs only inside one query. Pairs across queries ask for one score scale for all queries, which the problem does not need and the data rarely support.
  • The best iterate. The subgradient method can raise JJ, as at step 5 of the example. Returning the last ww of line L5 in place of the best of line L7 loses the guarantee of the theorem.
  • The radius. Line L6 needs a radius that holds the minimizer. With the objective above, 2/λ\sqrt{2/\lambda} is safe. A different scale of the loss, for example C∑ξC \sum \xi without the 1/P1/P, needs a different radius.
  • Pair counts. A query with many documents gives many more pairs than a short one and dominates the sum. Divide each query's pairs by their number if every query should count the same.
  • Ties in the labels. Documents with the same label form no pair. Do not add pairs with a target of zero difference; the hinge loss would push them apart.

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.

ranking_svm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ranking-svm/. The authors are listed in prov/VTCXN6.jsonl.

"""Ranking SVM: a linear scorer from pairwise preferences.

For every query and every pair of its documents with y_i > y_j, let
z = x_i - x_j. With P such pairs, the objective is

    J(w) = (lambda / 2) ||w||^2 + (1 / P) sum over pairs of max(0, 1 - w . z).

The solver is the projected subgradient method with the step 1 / (lambda t)
and the projection onto the ball of radius sqrt(2 / lambda), which holds
the minimizer because J(w*) <= J(0) = 1. It returns the best iterate. A
dual coordinate ascent gives a lower bound D(alpha) <= J(w*) for tests.
"""

import math


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


def norm(a):
    return math.sqrt(dot(a, a))


def pairs(queries):
    """The difference vectors x_i - x_j for y_i > y_j inside each query."""
    out = []
    for xs, y in queries:
        for i in range(len(xs)):
            for j in range(len(xs)):
                if y[i] > y[j]:
                    out.append([a - b for a, b in zip(xs[i], xs[j])])
    return out


def objective(w, zs, lam):
    return lam / 2 * dot(w, w) + sum(max(0.0, 1.0 - dot(w, z)) for z in zs) / len(zs)


def subgradient(w, zs, lam):
    """lambda w - (1 / P) sum of z over the pairs with w . z < 1."""
    g = [lam * a for a in w]
    for z in zs:
        if dot(w, z) < 1.0:
            for c in range(len(w)):
                g[c] -= z[c] / len(zs)
    return g


def radius(lam):
    return math.sqrt(2.0 / lam)


def train(queries, lam, steps):
    """Projected subgradient method. Returns the best w and the best J after each step."""
    zs = pairs(queries)                                          # @line L1
    d = len(zs[0])
    w = [0.0] * d                                                # @line L2
    best, best_j = list(w), objective(w, zs, lam)
    r = radius(lam)
    history = [best_j]
    for t in range(1, steps + 1):                                # @line L3
        g = subgradient(w, zs, lam)                              # @line L4
        w = [a - b / (lam * t) for a, b in zip(w, g)]            # @line L5
        n = norm(w)
        if n > r:                                                # @line L6
            w = [a * r / n for a in w]
        j = objective(w, zs, lam)
        if j < best_j:                                           # @line L7
            best, best_j = list(w), j
        history.append(best_j)
    return best, history                                         # @line L8


def bound(zs, lam, steps):
    """G^2 (1 + ln T) / (2 lambda T), with G = lambda R + max ||z||."""
    g = lam * radius(lam) + max(norm(z) for z in zs)
    return g * g * (1.0 + math.log(steps)) / (2.0 * lam * steps)


def dual(alpha, zs, lam):
    p = len(zs)
    v = [0.0] * len(zs[0])
    for a, z in zip(alpha, zs):
        for c in range(len(v)):
            v[c] += a * z[c]
    return sum(alpha) / p - dot(v, v) / (2.0 * lam * p * p)


def dual_coordinate_ascent(zs, lam, sweeps):
    """Exact maximization of D over one alpha_k at a time, alpha_k in [0, 1].

    Returns alpha and w = (1 / (lambda P)) sum alpha_k z_k.
    """
    p = len(zs)
    alpha = [0.0] * p
    v = [0.0] * len(zs[0])
    for _ in range(sweeps):
        for k, z in enumerate(zs):
            zz = dot(z, z)
            if zz == 0:
                continue
            new = min(1.0, max(0.0, alpha[k] + (lam * p - dot(z, v)) / zz))
            delta = new - alpha[k]
            if delta != 0.0:
                alpha[k] = new
                for c in range(len(v)):
                    v[c] += delta * z[c]
    return alpha, [a / (lam * p) for a in v]


def ranking(s):
    return sorted(range(len(s)), key=lambda i: (-s[i], i))


def misordered_pairs(w, queries):
    """The number of pairs with y_i > y_j and w . x_i <= w . x_j."""
    return sum(1 for z in pairs(queries) if dot(w, z) <= 0)
test_ranking_svm.py 135 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ranking-svm/. The authors are listed in prov/VTCXN6.jsonl.

import random

from ranking_svm import (
    bound,
    dot,
    dual,
    dual_coordinate_ascent,
    misordered_pairs,
    objective,
    pairs,
    ranking,
    subgradient,
    train,
)


def noisy(seed, n_queries=5, 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 = [[round(rng.uniform(-1, 1), 3) for _ in range(d)] for _ in range(n_docs)]
        t = [dot(w_true, x) + rng.gauss(0, 0.3) 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 separable(seed, n_queries=5, n_docs=5, d=3):
    """Labels from a hidden w_true with a gap of at least 0.2 between levels."""
    rng = random.Random(seed)
    w_true = [rng.uniform(-1, 1) for _ in range(d)]
    queries = []
    for _ in range(n_queries):
        xs, y = [], []
        while len(xs) < n_docs:
            x = [round(rng.uniform(-1, 1), 3) for _ in range(d)]
            t = dot(w_true, x)
            label = 2 if t > 0.4 else (1 if -0.2 < t < 0.2 else (0 if t < -0.6 else None))
            if label is not None:
                xs.append(x)
                y.append(label)
        queries.append((xs, y))
    return w_true, queries


def test_page_example():
    # One query, three documents with labels 2, 1, 0.
    queries = [([[2.0, 0.0], [1.0, 1.0], [0.0, 1.0]], [2, 1, 0])]
    zs = pairs(queries)
    assert zs == [[1.0, -1.0], [2.0, -1.0], [1.0, 0.0]]
    lam = 0.1
    assert objective([0.0, 0.0], zs, lam) == 1.0
    assert abs(objective([1.0, 0.0], zs, lam) - 0.05) < 1e-12
    alpha, wd = dual_coordinate_ascent(zs, lam, 100)
    assert abs(dual(alpha, zs, lam) - 0.05) < 1e-12
    w, history = train(queries, lam, 2000)
    assert history[-1] - 0.05 < 1e-6
    assert ranking([dot(w, x) for x in queries[0][0]]) == [0, 1, 2]


def test_best_objective_never_increases_and_falls():
    queries = noisy(seed=1)
    w, history = train(queries, 0.1, 500)
    assert all(b <= a for a, b in zip(history, history[1:]))
    assert history[-1] < history[0] == 1.0


def test_rate_bound_against_dual_lower_bound():
    for seed in (2, 3):
        queries = noisy(seed)
        zs = pairs(queries)
        for lam in (0.1, 0.3):
            alpha, wd = dual_coordinate_ascent(zs, lam, 300)
            lower = dual(alpha, zs, lam)
            # Weak duality: D(alpha) <= J(w) for every alpha in the box and every w.
            assert lower <= objective(wd, zs, lam) + 1e-12
            for steps in (50, 200, 800):
                _, history = train(queries, lam, steps)
                assert history[-1] >= lower - 1e-12
                assert history[-1] - lower <= bound(zs, lam, steps)


def test_subgradient_inequality():
    # J(u) >= J(w) + g . (u - w) + (lambda / 2) ||u - w||^2 for the returned g.
    rng = random.Random(4)
    zs = pairs(noisy(seed=5))
    lam = 0.2
    for _ in range(200):
        w = [rng.uniform(-2, 2) for _ in range(3)]
        u = [rng.uniform(-2, 2) for _ in range(3)]
        g = subgradient(w, zs, lam)
        diff = [a - b for a, b in zip(u, w)]
        rhs = objective(w, zs, lam) + dot(g, diff) + lam / 2 * dot(diff, diff)
        assert objective(u, zs, lam) >= rhs - 1e-12


def test_separable_instance_is_ranked_correctly():
    w_true, queries = separable(seed=1)
    zs = pairs(queries)
    margin = min(dot(w_true, z) for z in zs)
    assert margin > 0
    # Pick lambda so that the scaled w_true has J = 1 / (4P) < 1 / P.
    lam = margin * margin / (2.0 * len(zs) * dot(w_true, w_true))
    w, history = train(queries, lam, 500)
    # J(w) < 1 / P implies that every pair has w . z > 0 (proofs/correctness.md).
    assert history[-1] < 1.0 / len(zs)
    assert misordered_pairs(w, queries) == 0
    assert misordered_pairs(w_true, queries) == 0


def test_low_objective_lemma():
    # A misordered pair costs at least 1 / P, so J(w) < 1 / P forces zero errors.
    rng = random.Random(6)
    w_true, queries = separable(seed=1)
    zs = pairs(queries)
    scale = 1.0 / min(dot(w_true, z) for z in zs)
    low = 0
    for _ in range(500):
        w = [scale * a + rng.gauss(0, 1.5) for a in w_true]
        if objective(w, zs, 0.001) < 1.0 / len(zs):
            low += 1
            assert misordered_pairs(w, queries) == 0
        if misordered_pairs(w, queries) > 0:
            assert objective(w, zs, 0.001) >= 1.0 / len(zs)
    assert low > 0


def test_pairs_stay_inside_queries():
    queries = [([[1.0], [0.0]], [1, 0]), ([[5.0], [9.0]], [0, 0])]
    assert pairs(queries) == [[1.0]]

History

Herbrich, Graepel and Obermayer (2000) treated ordinal regression as a large margin problem on pairs of objects, with the margin taken on the difference of their feature vectors. Joachims (2002) used the same pairwise SVM for web search and showed how click logs give the pairs: a clicked result is preferred to an unclicked result ranked above it. He also observed that the slack sum bounds the number of discordant pairs, which ties the objective to the Kendall tau measure. Faster solvers followed, among them the cutting-plane method of Joachims (2006) and the stochastic subgradient method of Shalev-Shwartz, Singer and Srebro (2007). The pairwise view also led to RankNet and RankBoost, and later to the propensity-weighted version for biased clicks.

References

  1. Ralf Herbrich, Thore Graepel and Klaus Obermayer, Large margin rank boundaries for ordinal regression, in Advances in Large Margin Classifiers, MIT Press, 2000, Chapter 7, pp. 115-132 (the reduction of ordinal regression to a large margin problem on pairs of objects)
  2. Thorsten Joachims, Optimizing search engines using clickthrough data, Proceedings of the 8th ACM SIGKDD Conference on Knowledge Discovery and Data Mining, 2002, pp. 133-142 (preferences from clicks, the Ranking SVM on pair differences, and the bound of the number of discordant pairs by the slack sum)
  3. Shai Shalev-Shwartz, Yoram Singer and Nathan Srebro, Pegasos, primal estimated sub-gradient solver for SVM, Proceedings of the 24th International Conference on Machine Learning (ICML 2007), pp. 807-814 (the step 1/(lambda t), the projection onto a ball, and the log T over T rate for strongly convex objectives)
  4. Thorsten Joachims, Training linear SVMs in linear time, Proceedings of the 12th ACM SIGKDD Conference on Knowledge Discovery and Data Mining, 2006, pp. 217-226 (cutting-plane training of linear SVMs, with a formulation for ordinal regression)

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