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
- 13Uniform convergenceExcess risk decompositionStructural risk minimizationRademacher complexity of norm-bounded linear classesOracle inequality
- 06Strong convexityLagrange dual functionDual problem and weak dualityStrong duality and Slater's condition
- 04McDiarmid's bounded differences inequality
- 03Lipschitz continuity
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 ; Ivanov’s formulation minimizes subject to . If minimizes the former, it also minimizes empirical loss in the ball of radius : otherwise a competitor in the ball would improve the penalized objective. Conversely, convexity, existence and a Slater condition for the constraint guarantee a multiplier whose penalized minimum contains a constrained solution. Solutions can be nonunique, constraints inactive, or values of lack one-to-one correspondence. The penalty selects an inductive preference; it does not claim the minimum-norm solution is always best.
Here with . The constrained solution is and the penalized solution is . For they coincide with ; if the ball contains , . This is a geometric example, not an unconditional equivalence for every nonconvex problem.
What changing one datum means
Let be i.i.d., an independent copy, and the sample replacing with . An algorithm is uniformly stable with constant if for any neighboring samples and any evaluation point ,
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 is also used. Leave-one-out stability removes a datum and compares algorithms trained on and 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.
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 corresponds to the exact minimizer with , and although it falls as increases, an individual measured change need not be monotone.
The replacement identity
For a deterministic algorithm and integrable loss, symmetry of and gives
Subtracting empirical risk,
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.
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 is convex and -Lipschitz in on a convex domain, and . Define with minima and on neighboring samples. The quadratic term makes -strongly convex. By constrained optimality and strong convexity,
Adding cancels all common terms; the two terms from the replaced example are bounded by . If the solutions differ, division gives ; if they coincide the conclusion is immediate. Lipschitz continuity at an evaluation point yields
This Tikhonov stability is uniform and contains no dimension. The factor depends on convention: penalty directly gives . We use the conservative version in the following figures. Squared loss without bounded data and parameters is not globally Lipschitz; cannot be substituted without checking bounds.
For a loss between 0 and , one replacement changes the gap by at most : population risk changes by at most , the common mean terms by at most , and the replaced term by at most . Since expected gap is at most , McDiarmid gives with probability
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 , empirical optimality and the preceding identity give
The fit penalty grows with and the stability term falls. Their sum is minimized at , with scale . 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.
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 and height is clipped at 4 to show moderate values. Empirical loss plus stability is not the oracle right side, which contains ; its grid minimum need not follow 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 . In ridge, squared loss is Lipschitz only on a bounded domain; here , , and the penalized objective at zero is at most 1, so and one may use .
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.
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
Step 1 of 2. Why is E ℓ(A(S), Zᵢ′) = E ℓ(A(S⁽ⁱ⁾), Zᵢ)?
Step 1 of 2. What does adding the two strong-convexity inequalities give?
def on_average_replace_one_stability(fit, loss, sampler, n, trials):
pass