Simple Algorithm
Machine Learning · Convergence · 28 min

Soft Margins & Surrogate Losses

Slack variables, the hinge loss and classification calibration.

An SVM is judged by how many points it misclassifies, but it is trained to minimize the hinge loss. When does driving down a convex surrogate also drive down the classification error? Classification calibration answers this exactly, turns it into quantitative inequalities, and explains a practical fact: SVM scores are not probabilities.

What you’ll learn

  • Write soft-margin SVMs as regularized hinge-loss minimization and compare the hinge with the squared hinge, logistic and exponential surrogates.
  • Define classification calibration and the ψ\psi-transform, compute ψ\psi for four losses, and state the Bartlett–Jordan–McAuliffe theorem.
  • Show that the hinge risk is minimized by sign⁡(2η−1)\sign(2\eta - 1), so SVM scores do not estimate probabilities, and recalibrate them with Platt scaling.
  • Analyze Pegasos, stochastic subgradient descent on the primal with step 1/(λt)1/(\lambda t).
  • Formulate the ν\nu-SVM and interpret ν\nu as a bound on margin errors and support vectors.

Surrogates for the 0–1 loss

Labels are y∈{−1,+1}y \in \{-1, +1\}, a score function ff predicts sign⁡f(x)\sign f(\mathbf x), and the margin is m=yf(x)m = yf(\mathbf x). The classification risk is R(f)=P(yf(x)≤0)R(f) = P\big(yf(\mathbf x) \le 0\big), the risk of the 0–1 loss 1{m≤0}\mathbf 1\{m \le 0\}, and R⋆R^\star is the Bayes risk. Minimizing the empirical 0–1 loss is discontinuous, non-convex and, over linear classifiers, computationally hard in the worst case. So we minimize a convex surrogate ϕ(m)\phi(m) instead, with ϕ\phi-risk Rϕ(f)=E ϕ(yf(x))R_\phi(f) = \E\,\phi(yf(\mathbf x)) and minimum Rϕ⋆R_\phi^\star over all measurable ff.

As the Descent lesson showed, the soft-margin SVM is exactly regularized empirical ϕ\phi-risk minimization with the hinge loss:

min⁡f 1n∑i=1n[1−yif(xi)]++λ2∥f∥2,λ=1nC,\min_{f}\ \frac1n\sum_{i=1}^n\big[1 - y_if(\mathbf x_i)\big]_+ + \frac\lambda2\norm{f}^2,\qquad \lambda = \frac1{nC},

with ∥f∥\norm{f} the norm of w\mathbf w, or the kernel's function norm.

Lossϕ(m)\phi(m)Used byDifferentiable at 0, ϕ′(0)\phi'(0)
hinge[1−m]+[1 - m]_+SVMyes, −1-1 (the kink is at m=1m = 1)
squared hinge[1−m]+2[1 - m]_+^2L2-loss SVMyes, −2-2
logisticln⁡(1+e−m)\ln(1 + e^{-m})logistic regressionyes, −12-\tfrac12
exponentiale−me^{-m}AdaBoostyes, −1-1
perceptron[−m]+[-m]_+the perceptronno: kink at 00
All are convex in mm. The first four, suitably scaled, upper-bound the 0–1 loss. The last column turns out to decide everything.

Classification calibration

Because Rϕ(f)=Ex[η(x)ϕ(f(x))+(1−η(x))ϕ(−f(x))]R_\phi(f) = \E_{\mathbf x}\big[\eta(\mathbf x)\phi(f(\mathbf x)) + (1 - \eta(\mathbf x))\phi(-f(\mathbf x))\big] with η(x)=P(y=1∣x)\eta(\mathbf x) = P(y = 1 \mid \mathbf x), everything reduces to one point at a time. Define the conditional ϕ\phi-risk of predicting the score α\alpha when P(y=1)=ηP(y = 1) = \eta, its minimum, and its minimum over scores with the wrong sign:

Cη(α)=η ϕ(α)+(1−η) ϕ(−α),H(η)=inf⁡αCη(α),H−(η)=inf⁡α: α(2η−1)≤0Cη(α).C_\eta(\alpha) = \eta\,\phi(\alpha) + (1 - \eta)\,\phi(-\alpha),\qquad H(\eta) = \inf_\alpha C_\eta(\alpha),\qquad H^-(\eta) = \inf_{\alpha:\ \alpha(2\eta - 1) \le 0} C_\eta(\alpha).
DerivationThe hinge loss: $psi( heta) = lvert heta vert$
  1. Cη(α)=η(1−α)+(1−η)(1+α)=1+(1−2η) α(∣α∣≤1)C_\eta(\alpha) = \eta(1 - \alpha) + (1 - \eta)(1 + \alpha) = 1 + (1 - 2\eta)\,\alpha \qquad (\lvert\alpha\rvert \le 1)

    On α∈[−1,1]\alpha \in [-1, 1] both hinges are active, so the conditional risk is linear in α\alpha; outside that interval it only grows:

  2. α⋆(η)=sign⁡(2η−1),H(η)=2min⁡(η,1−η)\alpha^\star(\eta) = \sign(2\eta - 1),\qquad H(\eta) = 2\min(\eta, 1 - \eta)

    For η>12\eta > \tfrac12 the slope is negative, so the minimum is at α=1\alpha = 1; for η<12\eta < \tfrac12, at α=−1\alpha = -1:

  3. ψ(θ)=1−2min⁡(1+θ2,1−θ2)=∣θ∣⟹R(f)−R⋆  ≤  Rhinge(f)−Rhinge⋆\psi(\theta) = 1 - 2\min\Big(\frac{1+\theta}2, \frac{1-\theta}2\Big) = \lvert\theta\rvert\quad\Longrightarrow\quad R(f) - R^\star \;\le\; R_{\text{hinge}}(f) - R_{\text{hinge}}^\star

    On the wrong side, α≤0\alpha \le 0 for η>12\eta > \tfrac12, the function 1+(1−2η)α1 + (1 - 2\eta)\alpha is smallest at α=0\alpha = 0, so H−(η)=Cη(0)=1H^-(\eta) = C_\eta(0) = 1. With η=1+θ2\eta = \tfrac{1+\theta}2:

LossMinimizer α⋆(η)\alpha^\star(\eta)H(η)H(\eta)ψ(θ)\psi(\theta)
hingesign⁡(2η−1)\sign(2\eta - 1)2min⁡(η,1−η)2\min(\eta, 1 - \eta)∣θ∣\lvert\theta\rvert
squared hinge2η−12\eta - 14η(1−η)4\eta(1 - \eta)θ2\theta^2
logistic (natural log)ln⁡η1−η\ln\frac{\eta}{1 - \eta}−ηln⁡η−(1−η)ln⁡(1−η)-\eta\ln\eta - (1 - \eta)\ln(1 - \eta)1+θ2ln⁡(1+θ)+1−θ2ln⁡(1−θ)≥θ22\tfrac{1+\theta}2\ln(1+\theta) + \tfrac{1-\theta}2\ln(1-\theta) \ge \tfrac{\theta^2}2
exponential12ln⁡η1−η\tfrac12\ln\frac{\eta}{1 - \eta}2η(1−η)2\sqrt{\eta(1 - \eta)}1−1−θ21 - \sqrt{1 - \theta^2}
perceptron [−m]+[-m]_+00 for every η\eta0000: not calibrated
For the four smooth-at-zero losses H−(η)=ϕ(0)H^-(\eta) = \phi(0), attained at α=0\alpha = 0. Since ψ\psi is convex with ψ(0)=0\psi(0) = 0, it lies below its chord, ψ(θ)≤ψ(1) θ\psi(\theta) \le \psi(1)\,\theta, so no loss does better than linear growth near 00, and the hinge attains it: a small excess hinge risk forces an equally small excess classification risk. For the losses with ψ≈θ2\psi \approx \theta^2, the guarantee degrades to a square root. The perceptron loss is minimized by the uninformative score 00, consistent with the theorem, since it is not differentiable at 00.
Predict before you look

A classifier trained with the squared hinge loss has excess ϕ\phi-risk Rϕ(f)−Rϕ⋆=0.01R_\phi(f) - R_\phi^\star = 0.01. What upper bound on its excess classification risk R(f)−R⋆R(f) - R^\star does the comparison inequality give?

Show the answer

0.1

ψ(θ)=θ2≤0.01\psi(\theta) = \theta^2 \le 0.01 gives θ≤0.1\theta \le 0.1. The same excess hinge risk would have given 0.010.01, since the hinge's ψ\psi is ∣θ∣\lvert\theta\rvert. Under a low-noise (margin) condition, the bounds for curved ψ\psi can be sharpened.

SVM scores are not probabilities

The table's second column holds the key practical fact. The logistic and exponential minimizers are invertible functions of η\eta: from f⋆=ln⁡η1−ηf^\star = \ln\frac{\eta}{1-\eta} one recovers η=1/(1+e−f⋆)\eta = 1/(1 + e^{-f^\star}). The hinge minimizer sign⁡(2η−1)\sign(2\eta - 1) keeps only the side of 12\tfrac12 on which η\eta falls. Lin (2002) made this point for SVMs: their population target is the Bayes decision itself, not the conditional probability. With lots of data and a flexible kernel, an SVM's scores therefore tend to pile up near ±1\pm1 and say little about whether η\eta is 0.6 or 0.99.

This is not a defect so much as a trade. The hinge loss is exactly flat for margins above 1, which is what makes the SVM sparse. Bartlett and Tewari (2007) proved that the two goals conflict: losses that allow the conditional probability to be estimated over its whole range lead, asymptotically, to solutions that are not sparse.

Platt scaling. When probabilities are needed, fit a two-parameter sigmoid to the scores,

P^(y=1∣f)=11+eAf+B,\hat P(y = 1 \mid f) = \frac{1}{1 + e^{Af + B}},

by maximum likelihood on scores from data the SVM was not trained on: a held-out split or cross-validation. Training-set scores are biased, because the points that shaped the boundary sit at margin exactly 1 by construction. Platt (2000) also smoothed the 0/1 targets slightly to avoid overfitting with few examples; Lin, Lin and Weng (2007) gave a numerically more robust fitting algorithm. The general theory of recalibration is in Calibration & Proper Scoring Rules.

Pegasos: solving the primal stochastically

For linear SVMs with many examples, the primal F(w)=λ2∥w∥2+1n∑i[1−yiw⊤xi]+F(\mathbf w) = \frac\lambda2\norm{\mathbf w}^2 + \frac1n\sum_i[1 - y_i\mathbf w^\top\mathbf x_i]_+ (bias folded into a constant feature) is λ\lambda-strongly convex, and stochastic subgradient descent exploits that. Pegasos (Shalev-Shwartz, Singer, Srebro & Cotter, 2011) samples one example per step, takes a subgradient step of size ηt=1/(λt)\eta_t = 1/(\lambda t), and optionally projects onto the ball ∥w∥≤1/λ\norm{\mathbf w} \le 1/\sqrt\lambda, which contains the optimum. (A cruder argument already gives 2/λ\sqrt{2/\lambda}: λ2∥w⋆∥2≤F(w⋆)≤F(0)=1\frac\lambda2\norm{\mathbf w^\star}^2 \le F(\mathbf w^\star) \le F(\mathbf 0) = 1.)

python
import numpy as np

def pegasos(X, y, lam=1e-4, T=100_000, seed=0):
    """Stochastic subgradient descent on lam/2 ||w||^2 + mean hinge loss."""
    n, d = X.shape
    w = np.zeros(d)
    rng = np.random.default_rng(seed)
    for t in range(1, T + 1):
        i = rng.integers(n)
        eta = 1.0 / (lam * t)
        active = y[i] * (w @ X[i]) < 1          # is the hinge active?
        w *= 1.0 - eta * lam                     # gradient of the regularizer
        if active:
            w += eta * y[i] * X[i]               # subgradient of the hinge
        norm = np.linalg.norm(w)
        if norm > 1.0 / np.sqrt(lam):            # optional projection
            w /= norm * np.sqrt(lam)
    return w

The step 1/(λt)1/(\lambda t) is the classical choice for λ\lambda-strongly convex objectives. With subgradient norms bounded by GG, the averaged iterate's suboptimality is of order G2log⁡T/(λT)G^2\log T/(\lambda T) in expectation, so O~(1/(λε))\tilde{\mathcal O}(1/(\lambda\varepsilon)) iterations reach accuracy ε\varepsilon, and for linear kernels the total run time does not grow with the training-set size nn.

Think first Pegasos's run time does not depend on nn. Does that mean a bigger training set is never more expensive?

For a fixed accuracy on the training objective, yes: each step touches one example, and the number of steps depends on λ\lambda and ε\varepsilon, not nn. But with more data you would choose a smaller λ\lambda (less regularization is needed), and the cost grows like 1/λ1/\lambda. Shalev-Shwartz and Srebro's view is that with more data, reaching a given test error can even get cheaper, because the optimization need not be as precise.

The ν-SVM, and beyond two classes

CC is hard to interpret: its useful range depends on nn and on the scale of the kernel. Schölkopf, Smola, Williamson and Bartlett (2000) replaced it by a parameter with a meaning. The ν\nu-SVM also optimizes the margin level ρ\rho:

min⁡w,b,ξ,ρ 12∥w∥2−νρ+1n∑iξis.t.yi(w⊤φ(xi)+b)≥ρ−ξi,ξi≥0,ρ≥0.\min_{\mathbf w, b, \boldsymbol\xi, \rho}\ \tfrac12\norm{\mathbf w}^2 - \nu\rho + \frac1n\sum_i\xi_i\quad\text{s.t.}\quad y_i\big(\mathbf w^\top\varphi(\mathbf x_i) + b\big) \ge \rho - \xi_i,\quad \xi_i \ge 0,\quad \rho \ge 0.

A margin error is a point with ξi>0\xi_i > 0, on the wrong side of its margin hyperplane.

DerivationThe ν-property
  1. αi=1n−μi≤1n,∑iαi=ν+β\alpha_i = \tfrac1n - \mu_i \le \tfrac1n,\qquad \sum_i\alpha_i = \nu + \beta

    Stationarity of the Lagrangian in ξi\xi_i and ρ\rho (with multipliers αi\alpha_i, μi\mu_i and β\beta for the three constraint families) gives

  2. #{margin errors}n≤∑iαi=ν≤#{support vectors}n\frac{\#\{\text{margin errors}\}}{n} \le \sum_i\alpha_i = \nu \le \frac{\#\{\text{support vectors}\}}{n}

    If ρ>0\rho > 0, complementary slackness gives β=0\beta = 0, so ∑iαi=ν\sum_i\alpha_i = \nu. A margin error has ξi>0\xi_i > 0, hence μi=0\mu_i = 0 and αi=1n\alpha_i = \tfrac1n. Every support vector has 0<αi≤1n0 < \alpha_i \le \tfrac1n:

  3. So ν∈(0,1]\nu \in (0, 1] is an upper bound on the fraction of margin errors and a lower bound on the fraction of support vectors. Schölkopf et al. also showed that, under mild conditions on the distribution and the kernel, both fractions converge to ν\nu with probability 1 as n→∞n \to \infty.

Consistency. Calibration of the hinge, plus the ability of a universal kernel's function class to approximate any decision function, plus a regularization λn→0\lambda_n \to 0 at a suitable rate, makes kernel SVMs universally consistent (Steinwart, 2005).

More than two classes. Reductions such as one-vs-rest inherit binary calibration. Single-machine multiclass SVMs are more delicate: Tewari and Bartlett (2005) showed that the popular Crammer–Singer and Weston–Watkins hinge losses are not calibrated in general, so they can fail to be consistent when no class has conditional probability above 12\tfrac12, while the loss of Lee, Lin and Wahba is calibrated.

Key takeaways

  • A surrogate ϕ\phi is classification-calibrated when choosing the wrong sign always costs extra conditional ϕ\phi-risk; then ψ(R(f)−R⋆)≤Rϕ(f)−Rϕ⋆\psi(R(f) - R^\star) \le R_\phi(f) - R_\phi^\star, and ϕ\phi-risk consistency implies classification consistency.
  • A convex ϕ\phi is calibrated iff ϕ′(0)\phi'(0) exists and is negative. The hinge has ψ(θ)=∣θ∣\psi(\theta) = \lvert\theta\rvert, the squared hinge θ2\theta^2, the exponential 1−1−θ21 - \sqrt{1 - \theta^2}, and the logistic about θ2/2\theta^2/2.
  • The hinge risk is minimized by sign⁡(2η−1)\sign(2\eta - 1), so SVM scores are not probabilities; Platt scaling fits 1/(1+eAf+B)1/(1 + e^{Af + B}) on held-out scores. Sparsity and probability estimation are in genuine tension.
  • Pegasos solves the primal by stochastic subgradient steps of size 1/(λt)1/(\lambda t), needing O~(1/(λε))\tilde{\mathcal O}(1/(\lambda\varepsilon)) iterations independent of nn for linear kernels.
  • The ν\nu-SVM's ν\nu bounds the fraction of margin errors from above and of support vectors from below; single-machine multiclass hinge losses are not always calibrated.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Which convex loss of the margin is not classification-calibrated?

  1. ϕ(m)=[1−m]+\phi(m) = [1 - m]_+
  2. ϕ(m)=e−m\phi(m) = e^{-m}
  3. ϕ(m)=[−m]+\phi(m) = [-m]_+
  4. ϕ(m)=ln⁡(1+e−m)\phi(m) = \ln(1 + e^{-m})
Show the answer

C. ϕ(m)=[−m]+\phi(m) = [-m]_+

A convex ϕ\phi is calibrated if and only if it is differentiable at 00 with ϕ′(0)<0\phi'(0) < 0. The perceptron loss [−m]+[-m]_+ has a kink at 00, and indeed its conditional risk η[−α]++(1−η)[α]+\eta[-\alpha]_+ + (1 - \eta)[\alpha]_+ is minimized at α=0\alpha = 0 for every η\eta, an uninformative score.

Question 2

With unlimited data and a rich enough function class, an SVM's score function approaches the minimizer of the hinge risk. What can you read off it?

  1. The conditional probability η(x)\eta(\mathbf x), through the sigmoid
  2. Only the Bayes decision, sign⁡(2η(x)−1)\sign(2\eta(\mathbf x) - 1)
  3. The log-odds ln⁡η1−η\ln\frac{\eta}{1-\eta}
  4. Nothing: the hinge minimizer does not exist
Show the answer

B. Only the Bayes decision, sign⁡(2η(x)−1)\sign(2\eta(\mathbf x) - 1)

The conditional hinge risk is minimized at α⋆=sign⁡(2η−1)\alpha^\star = \sign(2\eta - 1), which discards ∣η−12∣\lvert\eta - \tfrac12\rvert. Probabilities need an extra step such as Platt scaling on held-out scores, or a loss with an invertible minimizer, such as the logistic.

Question 3

A ν\nu-SVM is trained with ν=0.05\nu = 0.05 on 4,000 examples and finds ρ>0\rho > 0. What do you know?

  1. Exactly 200 examples are support vectors
  2. The test error is at most 5%
  3. At most 200 examples are margin errors, and at least 200 are support vectors
  4. At least 200 margin errors and at most 200 support vectors
Show the answer

C. At most 200 examples are margin errors, and at least 200 are support vectors

With ρ>0\rho > 0, ∑iαi=ν\sum_i\alpha_i = \nu and 0≤αi≤1n0 \le \alpha_i \le \tfrac1n, with equality for margin errors. Hence (margin errors)/n≤ν≤/n \le \nu \le (support vectors)/n/n: at most 0.05×4000=2000.05 \times 4000 = 200 margin errors and at least 200 support vectors.

Question 4

Why should Platt scaling be fitted on held-out scores rather than on the SVM's training-set scores?

  1. Training scores are biased: support vectors sit at margin exactly 1 or inside it by construction, so the sigmoid would be fitted to a distorted picture
  2. Because the sigmoid has too many parameters
  3. Because SVM scores on the training set are always negative
  4. It makes no difference which scores are used
Show the answer

A. Training scores are biased: support vectors sit at margin exactly 1 or inside it by construction, so the sigmoid would be fitted to a distorted picture

The fit shaped the training scores: many training points are pushed exactly to yf=1yf = 1, and the rest beyond it. Scores on fresh data are what the calibrated probabilities will be applied to, so the sigmoid must be fitted on them (a held-out split or cross-validation).

Further reading

  • P. L. Bartlett, M. I. Jordan & J. D. McAuliffe, "Convexity, classification, and risk bounds," Journal of the American Statistical Association 101(473), 138–156 (2006).
  • T. Zhang, "Statistical behavior and consistency of classification methods based on convex risk minimization," Annals of Statistics 32(1), 56–85 (2004).
  • Y. Lin, "Support vector machines and the Bayes rule in classification," Data Mining and Knowledge Discovery 6(3), 259–275 (2002).
  • J. C. Platt, "Probabilistic outputs for support vector machines and comparisons to regularized likelihood methods," in Advances in Large Margin Classifiers (MIT Press, 2000).
  • S. Shalev-Shwartz, Y. Singer, N. Srebro & A. Cotter, "Pegasos: primal estimated sub-gradient solver for SVM," Mathematical Programming 127(1), 3–30 (2011).