Module contents
Lesson 14 of 20Advanced 110 min

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

A filter for each direction

Kernel ridge regression (KRR) lets us study a nonlinear estimator using linear algebra. With mean squared loss and λ>0\lambda>0 it minimizes n−1∑i(f(xi)−yi)2+λ∥f∥H2n^{-1}\sum_i(f(x_i)-y_i)^2+\lambda\|f\|_\mathcal H^2. The representer theorem gives f=∑iaik(xi,⋅)f=\sum_i a_i k(x_i,\cdot); one coefficient choice satisfies (K+nλI)a=y(K+n\lambda I)a=y. Solve with Cholesky without explicit inversion. Dense factorization costs O(n3)O(n^3) and storing Gram costs O(n2)O(n^2). For scikit-learn KernelRidge with the same matrix, alpha=n*lambda: its parameter does not include normalization by nn.

Let K=Udiag⁡(μi)U⊤K=U\operatorname{diag}(\mu_i)U^\top, y=f⋆(X)+εy=f_\star(X)+\varepsilon and H=K(K+nλI)−1H=K(K+n\lambda I)^{-1}. At training points f^=Hy\hat f=Hy and HH multiplies coordinate ii by hi=μi/(μi+nλ)h_i=\mu_i/(\mu_i+n\lambda). Small modes are attenuated more. This decomposition defines KRR spectral risk.

InteractiveThe KRR spectral filter
  • log₁₀(μᵢ/n)
  • log₁₀ λ
  • KRR fit
  • signal
  • data
−2.0
Effective dimension7.17
λ0.01000
Move λ and observe the spectrum threshold and fit on the same 40 points.

With fixed design, centered noise and covariance σ2I\sigma^2 I, denote c=U⊤f⋆(X)c=U^\top f_\star(X). The noise expectation of error at design points against the signal, not against new labels, is

1nEε∥f^−f⋆(X)∥2=1n∑i[(1−hi)2ci2+σ2hi2].\frac1n\mathbb E_\varepsilon\|\hat f-f_\star(X)\|^2=\frac1n\sum_i\left[(1-h_i)^2c_i^2+\sigma^2h_i^2\right].

Indeed, f^−f⋆=(H−I)f⋆+Hε\hat f-f_\star=(H-I)f_\star+H\varepsilon; the cross term has zero expectation and E∥Hε∥2=σ2tr⁡(H2)\mathbb E\|H\varepsilon\|^2=\sigma^2\operatorname{tr}(H^2). Loss on new labels would add variance of new noise. This formula is not automatically out-of-design risk.

Effective dimension dλ=tr⁡H=∑ihid_\lambda=\operatorname{tr}H=\sum_i h_i counts partially fitted directions. Since 0≤hi≤10\le h_i\le1, variance is σ2∑ihi2/n≤σ2dλ/n\sigma^2\sum_i h_i^2/n\le\sigma^2d_\lambda/n. At population level use tr⁡(T(T+λI)−1)\operatorname{tr}(T(T+\lambda I)^{-1}) with integral operator TT; 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 f⋆=Trgf_\star=T^r g, ∥g∥L2≤C\|g\|_{L^2}\le C, with r>0r>0, and eigenvalues τj≍j−α\tau_j\asymp j^{-\alpha}, α>1\alpha>1. For ridge, population squared bias is bounded by C′λ2sC'\lambda^{2s} with s=min⁡(r,1)s=\min(r,1): the filter has qualification one. Effective dimension has order λ−1/α\lambda^{-1/\alpha}. In an i.i.d. regime with controlled kernel and noise and remaining rate-theorem assumptions, balancing λ2s\lambda^{2s} and n−1λ−1/αn^{-1}\lambda^{-1/\alpha} gives

λ≍n−1/(2s+1/α),riesgo en exceso≲n−2s/(2s+1/α).\lambda\asymp n^{-1/(2s+1/\alpha)},\qquad \text{riesgo en exceso}\lesssim n^{-2s/(2s+1/\alpha)}.

For r≤1r\le1 these are minimax rates in usual classes and ranges where additional assumptions hold; for r>1r>1 the ridge filter saturates at s=1s=1 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 rr is a power of TT in L2L^2, 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 gjg_j is multiplied by λτjr/(τj+λ)\lambda\tau_j^r/(\tau_j+\lambda). For 0<r≤10<r\le1, its maximum over τj≥0\tau_j\ge0 is at most a constant times λr\lambda^r; squaring and summing yields λ2r∥g∥2\lambda^{2r}\|g\|^2. If r>1r>1, a fixed eigenmode with nonzero coefficient leaves bias of order λ\lambda, so a uniform bound cannot improve beyond λ2\lambda^2. Separating the sum of τj/(τj+λ)\tau_j/(\tau_j+\lambda) around index j≈λ−1/αj\approx\lambda^{-1/\alpha} explains the effective-dimension order. The sum requires α>1\alpha>1.

The standard case of a target within the RKHS corresponds here to r≥1/2r\ge1/2; less regular targets need additional conditions to justify the same statistical formulas. The figure also lets you explore r<1/2r<1/2 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.

InteractiveRate map: source and capacity
2.0
0.5
Risk exponent0.667
λ exponent0.667
The predicted rate saturates past r=1; points show another finite model, not a theorem proof.

Random features

A random-features model trains only the last layer of f(x)=∑j=1pwjzj(x)f(x)=\sum_{j=1}^p w_j z_j(x); first-layer frequencies and phases are drawn once and remain fixed. For k(x,x′)=exp⁡(−∥x−x′∥2/(2ℓ2))k(x,x')=\exp(-\|x-x'\|^2/(2\ell^2)), take ωj∼N(0,ℓ−2I)\omega_j\sim\mathcal N(0,\ell^{-2}I), bjb_j uniform on [0,2π][0,2\pi] and zj(x)=2/pcos⁡(ωj⊤x+bj)z_j(x)=\sqrt{2/p}\cos(\omega_j^\top x+b_j). Then E[z(x)⊤z(x′)]=k(x,x′)\mathbb E[z(x)^\top z(x')]=k(x,x'). Ridge on ZZ approximates the kernel; it is not the same estimator for finite pp.

For a fixed pair each summand 2cos⁡(ωj⊤x+bj)cos⁡(ωj⊤x′+bj)2\cos(\omega_j^\top x+b_j)\cos(\omega_j^\top x'+b_j) lies in [−2,2][-2,2]. Hoeffding gives, with probability at least 1−δ1-\delta,

∣z(x)⊤z(x′)−k(x,x′)∣≤8log⁡(2/δ)p.|z(x)^\top z(x')-k(x,x')|\le\sqrt{\frac{8\log(2/\delta)}p}.

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 nlog⁡n\sqrt n\log n 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 2exp⁡(−2pϵ2/16)2\exp(-2p\epsilon^2/16). Equating that expression to δ\delta yields the preceding square root. On a net of NN pairs one can replace δ\delta with δ/N\delta/N 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.

InteractiveHow many features suffice?
  • RFF test
  • exact KRR test
Examples n
Features p
√n log n39.2
RFF test at p0.0063
Mean exact test error0.0063
Compare kernel error on a grid with prediction error: each point averages three reproducible replicates.

The curve can fluctuate and need not saturate exactly at nlog⁡n\sqrt n\log n. Width ℓ\ell 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 nn, pp, implementation and hardware.

To understand Gaussian width, if design points are distinct and ℓ→0\ell\to0, Gram tends to the identity and dλ→n/(1+nλ)d_\lambda\to n/(1+n\lambda). If ℓ→∞\ell\to\infty, Gram tends to the rank-one all-ones matrix and dλ→1/(1+λ)d_\lambda\to1/(1+\lambda). Between these extremes, values and risk must be measured for the given design: changing ℓ\ell changes capacity and bias simultaneously.

[ ]Spectral risk and simulationBrowser
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 λ=n−1/2\lambda=n^{-1/2} 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.

[ ]RFF and Nyström: accuracy and costBrowser
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); [email protected](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; [email protected](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); [email protected](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

Proof
Prove: Prove spectral risk and the variance bound.
0
Use H=U diag(hᵢ) Uᵀ and covariance σ²I.

Step 1 of 2. What happens to the cross term between signal and noise?

Proof
Prove: Bound RFF error for a fixed pair.
0
Each random product lies in [−2,2] and its mean is the kernel.

Step 1 of 2. What is the interval width in Hoeffding?

Numeric
For normalized eigenvalues 1, 0.5, 0.25, 0.125 and λ=0.25, calculate Σ μ/(μ+λ).
Quiz
In a Gaussian family on a fixed design, what conclusion is safe when increasing ℓ?
CodeSpectral risk
Implement krr_spectral_risk(K, f_star, sigma2, lam) and return bias², variance and effective dimension. Use the K+nλI convention and positive lam.
def krr_spectral_risk(K, f_star, sigma2, lam):
  pass
Shift+Enter to run

Summary

Key idea
KRR filters Gram modes and its fixed-design variance is controlled by effective dimension. Rates and sufficient feature counts require source, capacity and sampling assumptions that must accompany each guarantee.

Sources: Rahimi and Recht, Rudi and Rosasco and kernel approximation in scikit-learn.