Spectral analysis of kernel ridge regression and random features
Analyze kernel ridge regression through Gram eigenmodes, effective dimension and source-capacity rates, then examine the statistical cost of random-feature kernel approximation.
After this lesson you can
- Derive KRR from the representer theorem and write its fixed-design risk in the Gram eigenbasis.
- Express KRR bias and variance using spectral filters μ_i/(μ_i + nλ) and bound variance by effective dimension d_λ.
- State KRR rates under source and capacity conditions and the optimal λ choice.
- Bound random-feature approximation error with Hoeffding and explain why p on the order of √n log n suffices for KRR under the stated assumptions.
- Relate random features to a two-layer network with a frozen first layer.
Before you start
- 13Representer theoremMercer's theoremBias-variance decompositionReproducing kernel Hilbert space
- 11Ridge regressionNyström approximationKernel trickEffective degrees of freedom
- 02Spectral theoremSherman-Morrison-Woodbury identityCholesky decomposition
- 04Hoeffding's inequality
- 09Forward and back substitutionCholesky in finite precision: stability and jitterMonte Carlo estimatorMonte Carlo error and confidence intervals
A filter for each direction
Kernel ridge regression (KRR) lets us study a nonlinear estimator using linear algebra. With mean squared loss and it minimizes . The representer theorem gives ; one coefficient choice satisfies . Solve with Cholesky without explicit inversion. Dense factorization costs and storing Gram costs . For scikit-learn KernelRidge with the same matrix, alpha=n*lambda: its parameter does not include normalization by .
Let , and . At training points and multiplies coordinate by . Small modes are attenuated more. This decomposition defines KRR spectral risk.
With fixed design, centered noise and covariance , denote . The noise expectation of error at design points against the signal, not against new labels, is
Indeed, ; the cross term has zero expectation and . Loss on new labels would add variance of new noise. This formula is not automatically out-of-design risk.
Effective dimension counts partially fitted directions. Since , variance is . At population level use with integral operator ; it is not identical to the empirical finite-sample quantity.
Smoothness, capacity and saturation
A source and capacity condition relates target and spectrum. Use convention , , with , and eigenvalues , . For ridge, population squared bias is bounded by with : the filter has qualification one. Effective dimension has order . In an i.i.d. regime with controlled kernel and noise and remaining rate-theorem assumptions, balancing and gives
For these are minimax rates in usual classes and ranges where additional assumptions hold; for the ridge filter saturates at even for a smoother target. Constants, logarithmic terms and technical ranges depend on the theorem; balancing alone does not prove a bound for every distribution. Source conventions vary across papers: here is a power of in , not an exponent in RKHS norm. See Caponnetto and De Vito and Sutherland’s correction.
The bias power follows directly from the population filter: coordinate is multiplied by . For , its maximum over is at most a constant times ; squaring and summing yields . If , a fixed eigenmode with nonzero coefficient leaves bias of order , so a uniform bound cannot improve beyond . Separating the sum of around index explains the effective-dimension order. The sum requires .
The standard case of a target within the RKHS corresponds here to ; less regular targets need additional conditions to justify the same statistical formulas. The figure also lets you explore as algebraic balancing, not an automatic guarantee. The minimax rate concerns a distribution class with specified bounds, not every function or sample; a particular function can be easier.
Random features
A random-features model trains only the last layer of ; first-layer frequencies and phases are drawn once and remain fixed. For , take , uniform on and . Then . Ridge on approximates the kernel; it is not the same estimator for finite .
For a fixed pair each summand lies in . Hoeffding gives, with probability at least ,
This random-feature approximation error is pointwise. A uniform bound on a compact set needs Lipschitz control and a finite covering net, together with frequency tails. It does not follow by applying the bound at one point. Under precise assumptions, Rudi and Rosasco show that on the order of random features can preserve the KRR statistical rate in their reference regime. This is not a universal test-error threshold or a promise of small uniform approximation: it depends on distribution, regularization and confidence.
To obtain the constant, Hoeffding bounds deviation probability by . Equating that expression to yields the preceding square root. On a net of pairs one can replace with by the union bound; extension error for points outside the net must then be added. Gaussian frequencies have no deterministic uniform Lipschitz constant: first control the probability that any frequency is too large.
The curve can fluctuate and need not saturate exactly at . Width must be validated; median distance is only a heuristic. Nyström instead uses Gram columns at landmark centers. Both methods reduce cost, but actual cost depends on , , implementation and hardware.
To understand Gaussian width, if design points are distinct and , Gram tends to the identity and . If , Gram tends to the rank-one all-ones matrix and . Between these extremes, values and risk must be measured for the given design: changing changes capacity and bias simultaneously.
import numpy as np
from sklearn.kernel_ridge import KernelRidge
rng=np.random.default_rng(1414); n=48; x=np.linspace(-2,2,n)[:,None]; f=np.sin(2*x[:,0]); sigma=.2; lam=.01
K=np.exp(-((x-x.T)**2)/(2*.5**2)); mu,U=np.linalg.eigh(K); h=mu/(mu+n*lam); c=U.T@f
bias=np.sum(((1-h)*c)**2)/n; var=sigma**2*np.sum(h*h)/n; deff=np.sum(h)
L=np.linalg.cholesky(K+n*lam*np.eye(n))
def solve(y): return np.linalg.solve(L.T,np.linalg.solve(L,y))
errors=[]
for _ in range(200):
y=f+rng.normal(0,sigma,n); pred=K@solve(y); errors.append(np.mean((pred-f)**2))
reference=KernelRidge(alpha=n*lam,kernel='precomputed').fit(K,y)
print('sesgo²',round(bias,6),'varianza',round(var,6),'d efectiva',round(deff,4))
print('predicción teórica',round(bias+var,6),'Monte Carlo',round(np.mean(errors),6),'error estándar',round(np.std(errors,ddof=1)/np.sqrt(len(errors)),6))
print('diferencia sklearn',np.max(np.abs(reference.predict(K)-pred)))The simulation estimates expectation conditional on the design; Monte Carlo uncertainty is shown. The next experiment uses a particular sinusoid and rule: a slope observed at three sizes does not alone estimate a minimax rate. It also compares RFF and Nyström with scikit-learn implementations; times are measurements on the current environment, not portable results.
import numpy as np, time
from sklearn.kernel_approximation import RBFSampler, Nystroem
rng=np.random.default_rng(1415); test=np.linspace(-2,2,201)[:,None]; truth=np.sin(2*test[:,0]); gamma=2.; results=[]
def gram(A,B): return np.exp(-gamma*(A-B.T)**2)
for n in (32,64,128):
X=rng.uniform(-2,2,(n,1)); y=np.sin(2*X[:,0])+rng.normal(0,.2,n); lam=n**(-.5); K=gram(X,X)
exact=gram(test,X)@np.linalg.solve(K+n*lam*np.eye(n),y); exacterr=np.mean((exact-truth)**2); results.append(exacterr)
for p in sorted(set((8,16,32,min(n,int(np.ceil(np.sqrt(n)*np.log(n))))))):
start=time.perf_counter(); w=rng.normal(0,np.sqrt(2*gamma),(1,p)); b=rng.uniform(0,2*np.pi,p)
Z=np.sqrt(2/p)*np.cos(X@w+b); Zt=np.sqrt(2/p)*np.cos(test@w+b); pred=Zt@np.linalg.solve(Z.T@Z+n*lam*np.eye(p),Z.T@y); trff=time.perf_counter()-start
start=time.perf_counter(); centers=X[:p]; C=gram(X,centers); Ct=gram(test,centers); W=gram(centers,centers); d,V=np.linalg.eigh(W); whitening=(V*(1/np.sqrt(np.maximum(d,1e-10))))@V.T
N=C@whitening; Nt=Ct@whitening; npred=Nt@np.linalg.solve(N.T@N+n*lam*np.eye(p),N.T@y); tnys=time.perf_counter()-start
models=[RBFSampler(gamma=gamma,n_components=p,random_state=3),Nystroem(gamma=gamma,n_components=p,random_state=3)]
errs=[]
for model in models:
A=model.fit_transform(X); B=model.transform(test); yp=B@np.linalg.solve(A.T@A+n*lam*np.eye(p),A.T@y); errs.append(np.mean((yp-truth)**2))
print('n,p',n,p,'exacto',round(exacterr,5),'RFF/Nys propio',round(np.mean((pred-truth)**2),5),round(np.mean((npred-truth)**2),5),'sklearn',np.round(errs,5),'segundos propio',round(trff,4),round(tnys,4))
print('pendiente log-log exacta observada',round(np.polyfit(np.log([32,64,128]),np.log(results),1)[0],3))Exercises
Step 1 of 2. What happens to the cross term between signal and noise?
Step 1 of 2. What is the interval width in Hoeffding?
def krr_spectral_risk(K, f_star, sigma2, lam):
passSummary
Sources: Rahimi and Recht, Rudi and Rosasco and kernel approximation in scikit-learn.