Module contents
Lesson 9 of 20Advanced 110 min

Surrogate loss calibration and margin bounds

Study classification calibration and the ψ transform linking convex surrogate loss to 0-1 excess risk, then derive norm- and margin-based generalization bounds for SVM and boosting.

After this lesson you can

  • Explain why 0-1 ERM on half-spaces is NP-hard in the agnostic case and what surrogate losses address.
  • Define classification calibration via conditional risk C_η(α), compute ψ transforms for hinge, logistic and exponential losses, and prove ψ(R(f) - R*) ≤ R_φ(f) - R_φ*.
  • Prove the BR/√n Rademacher bound for bounded linear classes on bounded inputs.
  • Prove a margin bound using ramp loss and the contraction lemma.
  • Apply margin bounds to SVM and boosting and measure them on real data.

Before you start

Changing the loss without losing the objective

In binary classification we want to minimize 0-1 errors, but that loss is discontinuous and nonconvex. In the agnostic case, finding the half-space with the fewest mistakes is NP-hard when dimension is part of the input; Guruswami and Raghavendra prove even approximation hardness for noisy half-spaces. This does not contradict the fact that a separable set can be handled with linear programming. Convex surrogates ease optimization under suitable conditions, but optimizing another function helps only if its risk relates to the risk of interest.

Write Y∈{−1,1}Y\in\{-1,1\}, score f(X)f(X) and margin Yf(X)Yf(X). A margin loss has form ϕ(Yf(X))\phi(Yf(X)). Conditional risk for η=P(Y=1∣X=x)\eta=P(Y=1\mid X=x) and score α\alpha is

Cη(α)=ηϕ(α)+(1−η)ϕ(−α),Cη∗=inf⁡αCη(α).C_\eta(\alpha)=\eta\phi(\alpha)+(1-\eta)\phi(-\alpha),\qquad C_\eta^*=\inf_\alpha C_\eta(\alpha).

The Bayes rule predicts positive when η>1/2\eta>1/2 and negative when η<1/2\eta<1/2. Classification risk may use any tie convention at f=0f=0; the margin-loss graph counts yf=0yf=0 as error for both labels and thus dominates that risk at a tie. A loss is classification-calibrated if, away from a tie, the infimum of conditional risk over incorrect or zero signs is strictly larger than Cη∗C_\eta^*. A correct-sign minimizer alone is insufficient: there must be a positive separation from the best incorrect-sign risk.

InteractiveLoss and conditional-risk gallery
Loss
0.70
Minimizer α*1.000
Bayes sign+
Choose loss and η. Above is φ and below Cη; the readout shows a representative minimizer.

Hinge max⁡(0,1−z)\max(0,1-z) has minimizer α∗=sign⁡(2η−1)\alpha^*=\operatorname{sign}(2\eta-1) away from a tie. Logistic log⁡(1+e−z)\log(1+e^{-z}) gives α∗=log⁡(η/(1−η))\alpha^*=\log(\eta/(1-\eta)), and exponential e−ze^{-z} gives half that logit. At η=0\eta=0 or 11 their infima may require infinite scores. Squared loss (1−z)2(1-z)^2 gives α∗=2η−1\alpha^*=2\eta-1; clipped ramp loss is calibrated but nonconvex. Perceptron loss max⁡(0,−z)\max(0,-z) has a minimum at α=0\alpha=0 for every η\eta and is not calibrated.

Logistic loss recovers η\eta through the sigmoid only at the unrestricted population minimizer with a correctly specified logarithmic loss. A restricted class or misspecified model can produce useful classification scores without well-calibrated probabilities. Classification calibration and probability calibration are not synonyms.

The ψ transform

For calibrated convex losses like those above, define H(η)=Cη∗H(\eta)=C_\eta^* and ψ(θ)=ϕ(0)−H((1+θ)/2)\psi(\theta)=\phi(0)-H((1+\theta)/2) for 0≤θ≤10\le\theta\le1. In general use the lower convex envelope of the appropriate pointwise transform. The ψ transform quantifies the price of transferring surrogate excess to 0-1 excess:

ψ(R01(f)−R01∗)≤Rϕ(f)−Rϕ∗.\psi(R_{01}(f)-R_{01}^*)\le R_\phi(f)-R_\phi^*.

The infima on the right are over all measurable scores, not necessarily the restricted class used by an algorithm. To understand the proof, an incorrect-sign decision has conditional 0-1 excess ∣2η−1∣|2\eta-1| and, by convexity, surrogate excess at least ψ(∣2η−1∣)\psi(|2\eta-1|). A correct decision has zero 0-1 excess. Integrate over XX and apply Jensen to convex ψ\psi. Calibration makes ψ(θ)>0\psi(\theta)>0 for θ>0\theta>0.

For hinge, logistic with natural logarithm and exponential respectively,

ψbis(θ)=θ,ψlog(θ)=1+θ2log⁡(1+θ)+1−θ2log⁡(1−θ),ψexp(θ)=1−1−θ2.\psi_{\rm bis}(\theta)=\theta,\quad \psi_{\rm log}(\theta)=\tfrac{1+\theta}{2}\log(1+\theta)+\tfrac{1-\theta}{2}\log(1-\theta),\quad \psi_{\rm exp}(\theta)=1-\sqrt{1-\theta^2}.

Terms 0log⁡00\log0 are interpreted by continuity. The latter two are approximately θ2/2\theta^2/2 near zero; thus a surrogate excess bound uu generally induces order u\sqrt u for 0-1 excess. The hinge relationship is linear. The inequality compares population risks; lowering empirical loss alone does not guarantee lower population excess.

InteractiveThe ψ transform in action
  • ψ(θ)
  • surrogate excess
Loss
0.10
0-1 excess bound0.100
ψ(1)1.000
Select a loss and surrogate excess: the intersection inverts ψ and bounds 0-1 excess.
[ ]Conditional risk and population comparisonBrowser
import numpy as np
from scipy.optimize import minimize_scalar
from sklearn.linear_model import LogisticRegression
from scipy.special import expit
losses={'bisagra':lambda a:np.maximum(0,1-a),'logística':lambda a:np.logaddexp(0,-a),
        'exponencial':lambda a:np.exp(-a),'perceptrón':lambda a:np.maximum(0,-a)}
for eta in (.2,.5,.8):
    vals=[]
    for name,phi in losses.items():
        res=minimize_scalar(lambda a:eta*phi(a)+(1-eta)*phi(-a),bounds=(-8,8),method='bounded')
        vals.append((name,round(res.x,3)))
    print('η',eta,vals)
rng=np.random.default_rng(1309); x=rng.uniform(-2,2,2000); eta=expit(2*x); y=rng.binomial(1,eta)
model=LogisticRegression(C=1e6).fit(x[:,None],y)
grid=np.linspace(-2,2,10001); e=expit(2*grid); f=model.decision_function(grid[:,None])
r01=np.mean(np.where(f>0,1-e,e)); bayes=np.mean(np.minimum(e,1-e));
sur=np.mean(e*np.logaddexp(0,-f)+(1-e)*np.logaddexp(0,f))
opt=np.mean(-e*np.log(e)-(1-e)*np.log(1-e))
theta=r01-bayes; psi=.5*((1+theta)*np.log1p(theta)+(1-theta)*np.log1p(-theta))
print('exceso 0-1:',round(theta,6),'ψ:',round(psi,8),'exceso logístico:',round(sur-opt,8))
assert psi<=sur-opt+1e-12

Integration uses a deterministic grid for a distribution with known η(x)\eta(x); fitting uses another sample. The numerical optimizer is bounded to [−8,8][-8,8], so a solution near an edge does not show that the unrestricted minimum is finite.

Linear complexity and margin

For FB={x↦w⊤x:∥w∥2≤B}\mathcal F_B=\{x\mapsto w^\top x:\|w\|_2\le B\}, Cauchy-Schwarz resolves the supremum and Jensen controls the expectation:

R^S(FB)=BnEσ∥∑iσixi∥2≤Bn∑i∥xi∥22≤BRn,\widehat{\mathfrak R}_S(\mathcal F_B)=\frac Bn\mathbb E_\sigma\left\|\sum_i\sigma_i x_i\right\|_2 \le\frac Bn\sqrt{\sum_i\|x_i\|_2^2}\le\frac{BR}{\sqrt n},

if ∥xi∥≤R\|x_i\|\le R. This is linear Rademacher complexity; cross terms vanish when signs are averaged. The absence of explicit dimension depends on keeping BB and RR controlled, which can fail when features are added.

The margin ramp loss ℓρ(z)=min⁡(1,max⁡(0,1−z/ρ))\ell_\rho(z)=\min(1,\max(0,1-z/\rho)) dominates 0-1 loss and is 1/ρ1/\rho-Lipschitz. Contraction and the previous empirical bound imply that, for ρ>0\rho>0 fixed in advance, with probability 1−δ1-\delta and simultaneously for every ∥w∥≤B\|w\|\le B,

R01(w)≤1n∑iℓρ(yiw⊤xi)+2BRρn+3log⁡(2/δ)2n.R_{01}(w)\le\frac1n\sum_i\ell_\rho(y_iw^\top x_i)+\frac{2BR}{\rho\sqrt n}+3\sqrt{\frac{\log(2/\delta)}{2n}}.

This margin bound combines empirical cost of small margins with complexity and confidence. If ρ\rho is selected from data, use the grid ρj=2−j\rho_j=2^{-j} and allocate δj=6δ/(π2j2)\delta_j=6\delta/(\pi^2j^2): the union gives a simultaneous guarantee over all j≥1j\ge1 with the confidence term for each scale. Scaling ww changes functional margin and BB by the same factor; geometric margin yf(x)/∥w∥yf(x)/\|w\| removes that change. An unbounded intercept must be treated separately or included as a constant coordinate with controlled augmented norm.

InteractiveMore dimensions with controlled norms
  • margin
  • VC
100
Margin term0.316
VC term1.631
Compare VC and margin complexity terms as dimension grows, fixing radius and norm.

In SVM, w=∑iαiyixiw=\sum_i\alpha_i y_i x_i comes from dual coefficients and the smallest positive geometric margin determines separation in the separable case. Soft-margin models have errors and small margins; the full margin distribution matters. The bound does not say an added dimension is free if norm or radius changes.

Votes and boosting

AdaBoost produces FT(x)=∑tαtht(x)F_T(x)=\sum_t\alpha_t h_t(x) with αt>0\alpha_t>0. Its normalized margin is yFT(x)/∑tαt∈[−1,1]yF_T(x)/\sum_t\alpha_t\in[-1,1] for base classifiers ht∈{−1,1}h_t\in\{-1,1\}. It is a convex combination of bases, so the Rademacher complexity of the convex hull equals that of the bases. A ramp loss yields a uniform bound depending on the margin distribution, not directly on round count. Schapire and colleagues studied test improvement after zero training error; this need not happen on every sample.

InteractiveAdaBoost margins on real and synthetic data
  • fraction with margin ≤ x
  • chosen ρ

Wisconsin: 284 training and 285 test examples, two features; stratified split with seed 1309. One trajectory does not guarantee that test performance improves after reaching zero.

Data
Round 1
Margin ρ
Training error0.077
Test error0.077
10th percentile of margin1.000
Margin bound1.226
Replay 50 stump rounds and observe margins, test error and bound on the chosen split.

The fixed stratified Wisconsin split has 284 training and 285 test examples. It uses features 0 and 20, all thresholds between training values and both orientations; the figure computes rounds in the browser. The bound uses at most 4(n+1)4(n+1) stump traces on nn examples, Massart and a union over radii. It can exceed 1. The real trajectory does not reach zero training error in these 50 rounds and test error is not monotone.

The synthetic moons option has 40 training and 1000 test examples. In this run, from round 17 to 20 training error remains zero, test error drops from .095 to .088 and the 10th margin percentile rises from .113 to .116. The seed was selected after inspecting test trajectories to show an example: that selection prevents treating it as an independent evaluation of a general procedure. Other seeds and rounds can behave differently; this does not reproduce published figures.

[ ]AdaBoost from scratch, SVM and comparisonBrowser
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.svm import SVC
X,y=load_breast_cancer(return_X_y=True); X=X[:,[0,20]]; y=2*y-1
X,Xt,y,yt=train_test_split(X,y,test_size=.5,stratify=y,random_state=1309)
scaler=StandardScaler().fit(X); X=scaler.transform(X); Xt=scaler.transform(Xt)
stumps=[]
for j in range(X.shape[1]):
    v=np.unique(X[:,j]); cuts=np.r_[v[0]-1,(v[:-1]+v[1:])/2,v[-1]+1]
    for c in cuts:
        for s in (-1,1): stumps.append((j,c,s))
H=np.array([s*np.where(X[:,j]>=c,1,-1) for j,c,s in stumps])
Ht=np.array([s*np.where(Xt[:,j]>=c,1,-1) for j,c,s in stumps])
w=np.ones(len(y))/len(y); score=np.zeros(len(y)); test=np.zeros(len(yt)); total=0
for t in range(50):
    errors=(H!=y)@w; k=np.argmin(errors); e=errors[k]
    if e>=.5-1e-14: break
    a=.5*np.log((1-max(e,1e-12))/max(e,1e-12)); total+=a
    score+=a*H[k]; test+=a*Ht[k]; w*=np.exp(-a*y*H[k]); w/=w.sum()
    if e<=1e-12: break
margins=y*score/total; rho=.5; delta=.05*6/np.pi**2
ramp=np.clip(1-margins/rho,0,1).mean()
bound=ramp+2*np.sqrt(2*np.log(4*(len(y)+1))/len(y))/rho+3*np.sqrt(np.log(2/delta)/(2*len(y)))
print('AdaBoost propio train/test:',round(np.mean(margins<=0),4),round(np.mean(yt*test<=0),4),'cota:',round(bound,3))
ada=AdaBoostClassifier(estimator=DecisionTreeClassifier(max_depth=1),n_estimators=50,random_state=1309).fit(X,y)
svm=SVC(kernel='linear',C=1).fit(X,y); [email protected]_vectors_
print('sklearn AdaBoost train/test:',round(1-ada.score(X,y),4),round(1-ada.score(Xt,yt),4))
print('SVC train/test:',round(1-svm.score(X,y),4),round(1-svm.score(Xt,yt),4),'norma:',round(np.linalg.norm(dual),4))
assert np.all(np.abs(margins)<=1+1e-12) and np.allclose(dual,svm.coef_)

Standardization is fitted on training only. The custom stumps and scikit-learn’s can break ties differently; results are compared without requiring identical classifiers. The bound uses the stump family over both coordinates and is a statistical guarantee under i.i.d. sampling, not a clinical proof or guarantee for another population.

Exercises

Proof
Prove: Bound the complexity of the linear ball.
0
Use Cauchy-Schwarz and Jensen on independent signs.

Step 1 of 2. What is the supremum over ||w|| ≤ B?

Proof
Prove: Prove hinge loss is calibrated and calculate ψ.
0
Minimize Cη(α) piecewise for η > 1/2 and use symmetry.

Step 1 of 2. What is a minimizer for η > 1/2?

Numeric
Calculate 2BR/(ρ√n) for B=R=1, ρ=0.1 and n=10000.
Quiz
Which loss is not classification-calibrated?
CodeAdaBoost and margins
Implement adaboost_stumps(X, y, T). Return a list of quadruples (column, threshold, orientation, weight) and normalized margins. Enumerate thresholds between ordered values and constants, both orientations ±1; use α=0.5 log((1−error)/error), stop if error ≥ 0.5 or zero (clip error to 1e−12 for finite α).
def adaboost_stumps(X, y, T):
  pass
Shift+Enter to run

Summary

Key idea
Calibration transfers surrogate excess to 0-1 excess through ψ. Margin bounds control complexity through norm and radius, and boosting uses normalized votes; neither a good empirical margin nor low loss alone guarantees calibrated probabilities.

Main source: Bartlett, Jordan and McAuliffe.