Module contents
Lesson 11 of 20Advanced 110 min

Regularization and algorithmic stability

Shift focus from the class to the algorithm. Define stability notions, relate average replacement to expected generalization gap, and prove uniform stability for Tikhonov regularization with convex Lipschitz losses.

After this lesson you can

  • Formulate Tikhonov and Ivanov regularization and justify their equivalence through duality.
  • Define uniform, average replacement and leave-one-out stability and order them by strength.
  • Prove the identity between expected generalization gap and signed average replacement stability.
  • Prove 2ρ²/(λn) stability for λ‖w‖² regularization with convex ρ-Lipschitz loss.
  • Derive the fit-stability tradeoff and λ proportional to 1/√n.
  • Measure stability of ridge, trees and k-NN empirically.

Before you start

Analyze the algorithm

Two algorithms can choose hypotheses from the same class and respond very differently when one datum is replaced. Algorithmic stability measures that output or loss change; it is not numerical stability of a calculation. Regularization can reduce the influence of one example, although it can also introduce bias.

Tikhonov regularization minimizes R^S(w)+λ∥w∥2\widehat R_S(w)+\lambda\|w\|^2; Ivanov’s formulation minimizes R^S(w)\widehat R_S(w) subject to ∥w∥≤B\|w\|\le B. If wλw_\lambda minimizes the former, it also minimizes empirical loss in the ball of radius ∥wλ∥\|w_\lambda\|: otherwise a competitor in the ball would improve the penalized objective. Conversely, convexity, existence and a Slater condition for the constraint guarantee a multiplier λ≥0\lambda\ge0 whose penalized minimum contains a constrained solution. Solutions can be nonunique, constraints inactive, or values of BB lack one-to-one correspondence. The penalty selects an inductive preference; it does not claim the minimum-norm solution is always best.

InteractiveConstraint versus penalty

Blue: ball and unconstrained minimum. Orange: penalized path and solution for B. Contours can extend beyond the frame.

1.0
Multiplier λ0.618
Solution norm1.000
Move B to project the minimum of an explicit quadratic loss onto the ball and read the corresponding multiplier.

Here R^(w)=12∥w−a∥2\widehat R(w)=\tfrac12\|w-a\|^2 with a=(2,1)a=(2,1). The constrained solution is amin⁡(1,B/∥a∥)a\min(1,B/\|a\|) and the penalized solution is a/(1+2λ)a/(1+2\lambda). For 0<B<∥a∥0<B<\|a\| they coincide with λ=(∥a∥/B−1)/2\lambda=(\|a\|/B-1)/2; if the ball contains aa, λ=0\lambda=0. This is a geometric example, not an unconditional equivalence for every nonconvex problem.

What changing one datum means

Let S=(Z1,…,Zn)S=(Z_1,\ldots,Z_n) be i.i.d., Zi′Z_i' an independent copy, and S(i)S^{(i)} the sample replacing ZiZ_i with Zi′Z_i'. An algorithm AA is uniformly stable with constant β\beta if for any neighboring samples and any evaluation point zz,

∣ℓ(A(S),z)−ℓ(A(S(i)),z)∣≤β.|\ell(A(S),z)-\ell(A(S^{(i)}),z)|\le\beta.

Hypothesis stability can directly measure distance between parameters or predictions; it translates to loss stability only under assumptions such as Lipschitz continuity. Average replacement stability can be defined as the mean of the absolute value above over sample, replacement and point; it is weaker than the uniform supremum. A signed version evaluated at original datum ZiZ_i is also used. Leave-one-out stability removes a datum and compares algorithms trained on nn and n−1n-1 examples: it is not literally the same quantity as replacement. Definitions depend on evaluation point and coupling; the variants should not all be ordered without these details.

InteractiveReplace a point and inspect the boundary

Blue line: before; dashed orange: after. Hollow circle: original point; orange circle: replacement.

0.10
0.2
0.5
Maximum change on grid0.040
Conservative bound 2/(λn)1.250
Change the replacement point position and λ; original and modified logistic boundaries overlap.

The model uses 16 points in the unit ball and a logistic classifier without intercept. The new position is projected onto that ball; the optimizer performs 250 gradient steps. The displayed maximum is sought over a finite grid and both labels; it does not certify the supremum over all samples. Bound 2/(λn)2/(\lambda n) corresponds to the exact minimizer with ρ=1\rho=1, and although it falls as λ\lambda increases, an individual measured change need not be monotone.

The replacement identity

For a deterministic algorithm and integrable loss, symmetry of ZiZ_i and Zi′Z_i' gives

ESR(A(S))=1n∑iES,Zi′ℓ(A(S),Zi′)=1n∑iES,Zi′ℓ(A(S(i)),Zi).\mathbb E_S R(A(S))=\frac1n\sum_i\mathbb E_{S,Z_i'}\ell(A(S),Z_i') =\frac1n\sum_i\mathbb E_{S,Z_i'}\ell(A(S^{(i)}),Z_i).

Subtracting empirical risk,

E[R(A(S))−R^S(A(S))]=1n∑iE[ℓ(A(S(i)),Zi)−ℓ(A(S),Zi)].\mathbb E[R(A(S))-\widehat R_S(A(S))] =\frac1n\sum_i\mathbb E[\ell(A(S^{(i)}),Z_i)-\ell(A(S),Z_i)].

This stability-generalization identity is exact for the signed replacement quantity. The mean absolute value gives an upper bound, but need not equal the gap. A randomized algorithm admits the same argument when its randomness is included and appropriately coupled across both runs. The identity alone does not guarantee small risk: a constant algorithm can generalize its own loss perfectly while being a poor predictor.

InteractiveGap and replacement by algorithm
0.00.00.20.20.40.41-NN: replacement 0.420, gap 0.3445-NN: replacement 0.130, gap 0.08515-NN: replacement 0.000, gap 0.027tree d=2: replacement 0.090, gap 0.091tree d=5: replacement 0.240, gap 0.248tree unrestricted: replacement 0.370, gap 0.339ridge α=1: replacement 0.000, gap 0.013ridge α=20: replacement 0.050, gap 0.023logistic C=1: replacement 0.020, gap −0.001logistic C=.1: replacement 0.010, gap 0.009mean signed replacementmean gap
1-NN: replacement 0.420; gap 0.344
5-NN: replacement 0.130; gap 0.085
15-NN: replacement 0.000; gap 0.027
tree d=2: replacement 0.090; gap 0.091
tree d=5: replacement 0.240; gap 0.248
tree unrestricted: replacement 0.370; gap 0.339
ridge α=1: replacement 0.000; gap 0.013
ridge α=20: replacement 0.050; gap 0.023
logistic C=1: replacement 0.020; gap −0.001
logistic C=.1: replacement 0.010; gap 0.009

Monte Carlo uncertainties are retained in stability.json; some points may overlap or fall off the diagonal due to estimation noise.

Algorithm
Replicates per algorithm100
Visible points10
Select families and compare measured averages with the diagonal; use 100 replicates for each point.

Synthetic data and seeds are generated in src/widgets/m13/l11/generate.py. Each replicate uses 80 training and 1000 independent test examples; replacement is evaluated on the removed datum. Points are averages of 0-1 loss and have Monte Carlo error, recorded alongside each value. The identity concerns expectations and does not require every finite point to lie on the diagonal. Ridge here is a ridge classifier; the following convex guarantee concerns a Lipschitz loss, not automatically its 0-1 decision.

Strong convexity implies stability

Assume ℓ(w,z)\ell(w,z) is convex and ρ\rho-Lipschitz in ww on a convex domain, and λ>0\lambda>0. Define FS(w)=R^S(w)+λ∥w∥2F_S(w)=\widehat R_S(w)+\lambda\|w\|^2 with minima ww and w′w' on neighboring samples. The quadratic term makes FSF_S 2λ2\lambda-strongly convex. By constrained optimality and strong convexity,

FS(w′)−FS(w)≥λ∥w′−w∥2,FS′(w)−FS′(w′)≥λ∥w′−w∥2.F_S(w')-F_S(w)\ge\lambda\|w'-w\|^2,\qquad F_{S'}(w)-F_{S'}(w')\ge\lambda\|w'-w\|^2.

Adding cancels all common terms; the two terms from the replaced example are bounded by 2ρ∥w′−w∥/n2\rho\|w'-w\|/n. If the solutions differ, division gives ∥w′−w∥≤ρ/(λn)\|w'-w\|\le\rho/(\lambda n); if they coincide the conclusion is immediate. Lipschitz continuity at an evaluation point yields

β≤ρ2λn≤2ρ2λn.\beta\le\frac{\rho^2}{\lambda n}\le\frac{2\rho^2}{\lambda n}.

This Tikhonov stability is uniform and contains no dimension. The factor depends on convention: penalty λ∥w∥2/2\lambda\|w\|^2/2 directly gives 2ρ2/(λn)2\rho^2/(\lambda n). We use the conservative version 2ρ2/(λn)2\rho^2/(\lambda n) in the following figures. Squared loss without bounded data and parameters is not globally Lipschitz; ρ=1\rho=1 cannot be substituted without checking bounds.

For a loss between 0 and MM, one replacement changes the gap R(A(S))−R^S(A(S))R(A(S))-\widehat R_S(A(S)) by at most 2β+M/n2\beta+M/n: population risk changes by at most β\beta, the n−1n-1 common mean terms by at most (n−1)β/n(n-1)\beta/n, and the replaced term by at most M/nM/n. Since expected gap is at most β\beta, McDiarmid gives with probability 1−δ1-\delta

R(A(S))≤R^S(A(S))+β+(2nβ+M)ln⁡(1/δ)2n.R(A(S))\le\widehat R_S(A(S))+\beta+(2n\beta+M)\sqrt{\frac{\ln(1/\delta)}{2n}}.

This derivation uses replacement stability. Constants in Bousquet and Elisseeff depend on the stability variant; Feldman and Vondrák obtain high-probability refinements. An expectation bound does not become a high-probability bound without an additional argument and boundedness or alternative assumptions.

Fit versus stability

If ∥w∗∥≤B\|w^*\|\le B, empirical optimality and the preceding identity give

ER(A(S))≤R(w∗)+λB2+2ρ2λn.\mathbb E R(A(S))\le R(w^*)+\lambda B^2+\frac{2\rho^2}{\lambda n}.

The fit penalty grows with λ\lambda and the stability term falls. Their sum is minimized at λ=2ρ2/(B2n)\lambda=\sqrt{2\rho^2/(B^2n)}, with scale 1/n1/\sqrt n. This is a theoretical tradeoff for a fixed comparator and known constants; it need not identify the best practical hyperparameter. The fit-stability tradeoff does not guarantee monotone test error on a particular sample.

InteractiveThe λ that balances fit and stability
  • logistic training
  • stability 2/(λn)
  • sum
  • logistic test
Sample size n
Grid minimum1.000
Oracle scale B=10.141
Test at the minimum0.675
Compare empirical loss, test and penalty on a grid; the oracle scale is shown separately.

The curves come from one synthetic logistic run per sample size, with inputs of norm at most 1 and an independent 3000-example test. The horizontal axis is log⁡10λ\log_{10}\lambda and height is clipped at 4 to show moderate values. Empirical loss plus stability is not the oracle right side, which contains R(w∗)+λB2R(w^*)+\lambda B^2; its grid minimum need not follow 1/n1/\sqrt n exactly.

Measuring stability

The next cell calculates replacements on bounded samples. A maximum on a finite grid is only an observed maximum, not certified uniform stability. For logistic loss, inputs in the unit ball give ρ=1\rho=1. In ridge, squared loss is Lipschitz only on a bounded domain; here ∣y∣≤1|y|\le1, ∥x∥≤1\|x\|\le1, and the penalized objective at zero is at most 1, so ∥w∥≤1/λ\|w\|\le1/\sqrt\lambda and one may use ρ=2(1+1/λ)\rho=2(1+1/\sqrt\lambda).

[ ]Replace-one for ridge and logistic regressionBrowser
import numpy as np
rng=np.random.default_rng(1311)
def sample(n):
    X=rng.normal(size=(n,2)); X/=np.maximum(1,np.linalg.norm(X,axis=1,keepdims=True))
    y=np.where(rng.random(n)<1/(1+np.exp(-X[:,0])),1.,-1.)
    return X,y
def ridge(X,y,lam): return np.linalg.solve(X.T@X/len(y)+lam*np.eye(2),X.T@y/len(y))
def logistic(X,y,lam):
    w=np.zeros(2)
    for _ in range(1000):
        z=y*(X@w); grad=-(X.T@(y/(1+np.exp(z))))/len(y)+2*lam*w; w-=.4*grad
    return w
def measure(fit,loss,lam,n=80,trials=100):
    observed=[]; signed=[]; grid,_=sample(200)
    for _ in range(trials):
        X,y=sample(n); X2,y2=X.copy(),y.copy(); xr,yr=sample(1); X2[0]=xr[0]; y2[0]=yr[0]
        a,b=fit(X,y,lam),fit(X2,y2,lam)
        observed.append(max(np.max(np.abs(loss(grid,np.ones(len(grid)),a)-loss(grid,np.ones(len(grid)),b))),np.max(np.abs(loss(grid,-np.ones(len(grid)),a)-loss(grid,-np.ones(len(grid)),b)))))
        signed.append(float(loss(X[:1],y[:1],b)[0]-loss(X[:1],y[:1],a)[0]))
    return np.mean(signed),max(observed)
for name,fit,loss in [('ridge',ridge,lambda X,y,w:(X@w-y)**2),('logística',logistic,lambda X,y,w:np.logaddexp(0,-y*(X@w)))]:
    lam=.1; signed,maximum=measure(fit,loss,lam); rho=2*(1+1/np.sqrt(lam)) if name=='ridge' else 1
    print(name,'media firmada',round(signed,4),'máximo observado',round(maximum,4),'cota',round(2*rho*rho/(lam*80),3))

Iterative logistic optimization is approximate; the grid result and exact bound are different objects. The 100 replacements do not prove a uniform bound.

[ ]Gap and replacement with scikit-learnBrowser
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression
rng=np.random.default_rng(1312)
def sample(n):
    X=rng.normal(size=(n,2)); y=np.where(X[:,0]+.5*X[:,1]+rng.normal(size=n)>.0,1,-1); return X,y
algorithms={'1-NN':lambda:KNeighborsClassifier(n_neighbors=1),'9-NN':lambda:KNeighborsClassifier(n_neighbors=9),
            'árbol 2':lambda:DecisionTreeClassifier(max_depth=2,random_state=0),'árbol libre':lambda:DecisionTreeClassifier(random_state=0),
            'logística C=.1':lambda:LogisticRegression(C=.1),'logística C=1':lambda:LogisticRegression(C=1)}
gaps=[]; changes=[]
for name,factory in algorithms.items():
    g=[]; d=[]
    for _ in range(80):
        X,y=sample(80); Xt,yt=sample(1000); xr,yr=sample(1)
        model=factory().fit(X,y); old=int(model.predict(X[:1])[0]!=y[0]); g.append(np.mean(model.predict(Xt)!=yt)-np.mean(model.predict(X)!=y))
        X2,y2=X.copy(),y.copy(); X2[0]=xr[0]; y2[0]=yr[0]; new=factory().fit(X2,y2)
        d.append(int(new.predict(X[:1])[0]!=y[0])-old)
    gaps.append(np.mean(g)); changes.append(np.mean(d)); print(name,'brecha',round(gaps[-1],3),'reemplazo',round(changes[-1],3))
print('correlación entre medias:',round(np.corrcoef(gaps,changes)[0,1],3))

The correlation among six averages depends on this simulation and does not replace the theoretical identity. 1-NN can change substantially near the replaced point; a deep tree can also change its partition, but the observed ordering of all algorithms is not universal.

In the general learning framework, Shalev-Shwartz and colleagues construct learnable examples without uniform convergence, including infinite-dimensional convex optimization. They do not contradict the previous fundamental theorem: that theorem specifically characterizes binary classification with 0-1 loss and uniform guarantees over distributions.

Exercises

Proof
Prove: Prove the expected-gap and signed-replacement identity.
0
Introduce independent Zᵢ′ and S⁽ⁱ⁾.

Step 1 of 2. Why is E ℓ(A(S), Zᵢ′) = E ℓ(A(S⁽ⁱ⁾), Zᵢ)?

Proof
Prove: Prove stability for R̂+λ||w||².
0
Compare two minima on samples differing in one observation.

Step 1 of 2. What does adding the two strong-convexity inequalities give?

Numeric
Calculate 2ρ²/(λn) with ρ=1, λ=0.01 and n=10000.
Numeric
Calculate √(2ρ²/(B²n)) with ρ=1, B=10 and n=10000.
Quiz
Which algorithm can lack uniform stability tending to zero under 0-1 loss?
CodeSigned average stability
Implement on_average_replace_one_stability(fit, loss, sampler, n, trials). sampler(m) returns a list of m independent examples; fit(S) returns a model and loss(model, z) a number. In each trial replace the first example with a fresh one and average loss(fit(S_replaced), S[0]) − loss(fit(S), S[0]).
def on_average_replace_one_stability(fit, loss, sampler, n, trials):
  pass
Shift+Enter to run

Summary

Key idea
Signed replacement stability equals the expected gap. Strong convexity and Lipschitz continuity control one datum’s influence; regularization balances approximation and stability under explicit assumptions on loss and domain.