Module contents
Lesson 18 of 20Research 110 min

The kernel regime: the NTK as a lens on the generalization of wide networks

A very wide network whose parameters barely move can behave like its linearization, giving regression with the neural tangent kernel (NTK). Use the NTK to analyze data-dependent bounds, spectral learning and alignment with the target. Then compare the fixed-kernel regime with finite networks that learn features.

After this lesson you can

  • Linearize a network around initialization, define the empirical NTK, and solve the linearized gradient flow as kernel regression.
  • Derive and compute the two-layer data-dependent bound and explain how label randomization changes it.
  • Explain spectral bias as learning along eigendirections and predict learning curves from the kernel spectrum and target alignment.
  • State separation results for fixed kernels and feature-learning networks and construct a task that fixed kernels struggle to learn.
  • Measure empirical NTK drift and alignment in finite networks, then compare the network with regression using its initial and final kernels.

Before you start

Does a wide network behave like a kernel method?

The previous lesson ended with a puzzle. Overparameterized networks can memorize random labels, making bounds that depend only on their function class vacuous. Yet those same networks generalize on real labels. A complexity measure for this phenomenon must account for data and the training algorithm.

Kernel methods already have such a theory. Earlier lessons studied the Rademacher complexity of an RKHS ball, the representer theorem, kernel ridge risk in the spectral basis, and effective dimension. Jacot, Gabriel and Hongler (2018) observed that in a suitable limit, gradient descent on a network is regression with a fixed kernel, the neural tangent kernel (NTK). Kernel results can then describe a network close to that limit.

This lesson uses the NTK to study generalization. The derivation of the infinite-width limit and the required parameterization is in the neural networks module’s abc parameterizations lesson. The related Bayesian kernel in the NNGP limit describes an infinite-width network with only its final layer trained. Here, linearization is enough. It gives a bound that distinguishes real and random labels, explains why models learn smooth functions first, and connects learning curves to the spectrum. Theoretical separations and the GPU experiments then show where fixed-kernel behavior departs from feature-learning networks.

The neural tangent kernel

Linearizing around initialization

Let f(x;θ)f(\vb{x}; \theta) be a network with parameters θ∈RP\theta \in \R^P initialized at θ0\theta_0. Its first-order Taylor expansion at θ\theta gives the linearized model

flin(x;θ)=f(x;θ0)+∇θf(x;θ0)⊤(θ−θ0).f^{\mathrm{lin}}(\vb{x}; \theta) = f(\vb{x}; \theta_0) + \grad_\theta f(\vb{x}; \theta_0)\T(\theta - \theta_0).

The model is linear in parameters and can be nonlinear in inputs. Its features ϕ(x)=∇θf(x;θ0)∈RP\vb{\phi}(\vb{x}) = \grad_\theta f(\vb{x}; \theta_0) \in \R^P are fixed by the architecture and initialization. A linear model in fixed features is a kernel method with the kernel induced by those features.

The NTK measures how the prediction at x′\vb{x}' moves under a gradient step correcting the prediction at x\vb{x}. A step Δθ=−ϵ∇θf(x;θ)\Delta\theta = -\epsilon\grad_\theta f(\vb{x}; \theta) changes f(x′)f(\vb{x}') by −ϵ Θθ(x,x′)+O(ϵ2)-\epsilon\,\Theta_\theta(\vb{x}, \vb{x}') + \bigO(\epsilon^2). The similarity comes from the gradient updates.

Gradient flow of the linearized model gives kernel regression

Train with squared loss L(θ)=12∥f(X;θ)−y∥2L(\theta) = \tfrac12\norm{f(\mat{X}; \theta) - \vb{y}}^2 and gradient flow θ˙t=−η∇L(θt)\dot\theta_t = -\eta\grad L(\theta_t), the continuous-time limit of gradient descent with step η\eta. Applying the chain rule to the original network gives

 ⁣d ⁣dtf(X;θt)=Jθtθ˙t=−η JθtJθt⊤(f(X;θt)−y)=−η Θθt(f(X;θt)−y).\frac{\dd}{\dd t} f(\mat{X}; \theta_t) = \mat{J}_{\theta_t}\dot\theta_t = -\eta\,\mat{J}_{\theta_t}\mat{J}_{\theta_t}\T\big(f(\mat{X}; \theta_t) - \vb{y}\big) = -\eta\,\mat{\Theta}_{\theta_t}\big(f(\mat{X}; \theta_t) - \vb{y}\big).

In function space the network’s descent follows the NTK at time tt. For the linearized model, the Jacobian is fixed. Its dynamics form a linear ODE with constant coefficients.

Proof

(1) With rt=ft(X)−y\vb{r}_t = f_t(\mat{X}) - \vb{y}, the equation with fixed J\mat{J} becomes r˙t=−ηΘrt\dot{\vb{r}}_t = -\eta\mat{\Theta}\vb{r}_t. Its unique solution is rt=e−ηΘtr0\vb{r}_t = e^{-\eta\mat{\Theta}t}\vb{r}_0, using the matrix exponential.

(2) θ˙t=−ηJ⊤rt\dot\theta_t = -\eta\mat{J}\T\vb{r}_t, so θt−θ0=−ηJ⊤∫0te−ηΘs ⁣ds r0=J⊤Θ−1(I−e−ηΘt)(−r0)\theta_t - \theta_0 = -\eta\mat{J}\T\int_0^t e^{-\eta\mat{\Theta}s}\dd s\,\vb{r}_0 = \mat{J}\T\mat{\Theta}^{-1}(\mat{I} - e^{-\eta\mat{\Theta}t})(-\vb{r}_0) by ∫0tηΘe−ηΘs ⁣ds=I−e−ηΘt\int_0^t \eta\mat{\Theta}e^{-\eta\mat{\Theta}s}\dd s = \mat{I} - e^{-\eta\mat{\Theta}t} and the fact that Θ\mat{\Theta} commutes with its exponential. Substituting ft(x)=f0(x)+∇θf(x;θ0)⊤(θt−θ0)f_t(\vb{x}) = f_0(\vb{x}) + \grad_\theta f(\vb{x}; \theta_0)\T(\theta_t - \theta_0) and ∇θf(x;θ0)⊤J⊤=Θ(x,X)\grad_\theta f(\vb{x}; \theta_0)\T\mat{J}\T = \Theta(\vb{x}, \mat{X}) yields the formula.

(3) Θ\mat{\Theta} is positive definite, so e−ηΘt→0e^{-\eta\mat{\Theta}t} \to \mat{0}. The limit θ∞−θ0=J⊤Θ−1(y−f0(X))=J⊤(JJ⊤)−1(y−f0(X))\theta_\infty - \theta_0 = \mat{J}\T\mat{\Theta}^{-1}(\vb{y} - f_0(\mat{X})) = \mat{J}\T(\mat{J}\mat{J}\T)^{-1}(\vb{y} - f_0(\mat{X})) lies in the row space of J\mat{J} and solves the system. The same Pythagorean argument as for least squares gives the minimum-norm interpolator.

∎

If also f0≡0f_0 \equiv 0, as with an antisymmetric initialization or by subtracting f0f_0 in the experiments, the limit is Θ(x,X)Θ−1y\Theta(\vb{x}, \mat{X})\mat{\Theta}^{-1}\vb{y}. This is ridgeless regression with the NTK. The representer theorem identifies it as the interpolator of minimum norm in the RKHS of Θ\Theta, with norm y⊤Θ−1y\vb{y}\T\mat{\Theta}^{-1}\vb{y}, which the exercises prove. Part (2) also shows that at finite time the model acts as a spectral filter on the data.

The derivation is exact for the linearized model. For the original network, we need Θθt≈Θθ0\mat{\Theta}_{\theta_t} \approx \mat{\Theta}_{\theta_0} throughout training. This is the kernel regime, also called the lazy regime.

Output scale and lazy training

Chizat, Oyallon and Bach (2019) showed how output scaling can induce lazy behavior. Take any model h(x;θ)h(\vb{x}; \theta) and define the centered and scaled model

fα(x;θ)=α(h(x;θ)−h(x;θ0)),Lα(θ)=1α2⋅12∥fα(X;θ)−y∥2.f_\alpha(\vb{x}; \theta) = \alpha\big(h(\vb{x}; \theta) - h(\vb{x}; \theta_0)\big), \qquad L_\alpha(\theta) = \frac{1}{\alpha^2}\cdot\tfrac12\norm{f_\alpha(\mat{X}; \theta) - \vb{y}}^2 .

Its NTK is α2Θh\alpha^2\Theta^h, and the preceding equation gives  ⁣d ⁣dtfα=−η Θθth(fα−y)\frac{\dd}{\dd t}f_\alpha = -\eta\,\mat{\Theta}^h_{\theta_t}(f_\alpha - \vb{y}). At t=0t = 0, the dynamics in function space are independent of α\alpha. Parameter movement changes because fαf_\alpha is α\alpha times as sensitive to θ\theta, so a displacement ∥θt−θ0∥=O(1/α)\norm{\theta_t - \theta_0} = \bigO(1/\alpha) suffices. If ∇θh\grad_\theta h is β\beta-Lipschitz, the Jacobian’s relative change is at most β∥θt−θ0∥/∥∇θh(θ0)∥=O(1/α)\beta\norm{\theta_t - \theta_0}/\norm{\grad_\theta h(\theta_0)} = \bigO(1/\alpha). With large α\alpha the model stays in a neighborhood where its linearization is accurate. Chizat et al. bound the gap between the trajectories as a function of α\alpha.

For a two-layer network, h(x)=1m∑j=1majσ(wj⊤x)h(\vb{x}) = \frac1m\sum_{j=1}^m a_j\sigma(\vb{w}_j\T\vb{x}) is the mean-field parameterization. The NTK parameterization 1m∑jajσ(wj⊤x)\frac{1}{\sqrt m}\sum_j a_j\sigma(\vb{w}_j\T\vb{x}) is exactly αh\alpha h with α=m\alpha = \sqrt{m}. In this parameterization width scales the output and induces lazy training. Chizat et al. also find that deep convolutional classifiers perform worse when constrained to the lazy regime. The later widget visualizes the effect of changing α\alpha.

Generalization in the kernel regime

The two-layer NTK of Arora et al.

Arora, Du, Hu, Li and Wang (2019) study the network

fW(x)=1m∑r=1mar ReLU⁡(wr⊤x),wr∼iidN(0,κ2I),ar∼iidUnif⁡{−1,1},f_{\mat{W}}(\vb{x}) = \frac{1}{\sqrt m}\sum_{r=1}^m a_r\,\relu(\vb{w}_r\T\vb{x}), \qquad \vb{w}_r \iid \Normal(\vb{0}, \kappa^2\mat{I}), \quad a_r \iid \Unif\{-1, 1\},

with inputs of norm ∥x∥=1\norm{\vb{x}} = 1. Only the first layer W\mat{W} is trained and ara_r remains fixed. The gradient with respect to wr\vb{w}_r is 1mar1[wr⊤x≥0] x\frac{1}{\sqrt m}a_r\ind[\vb{w}_r\T\vb{x} \ge 0]\,\vb{x}. Since ar2=1a_r^2 = 1,

Θm(x,x′)=x⊤x′⋅1m∑r=1m1[wr⊤x≥0] 1[wr⊤x′≥0]→m→∞c.s.x⊤x′ Pw∼N(0,I)(w⊤x≥0, w⊤x′≥0).\Theta_m(\vb{x}, \vb{x}') = \vb{x}\T\vb{x}'\cdot\frac1m\sum_{r=1}^m \ind[\vb{w}_r\T\vb{x} \ge 0]\,\ind[\vb{w}_r\T\vb{x}' \ge 0] \xrightarrow[m\to\infty]{\text{c.s.}} \vb{x}\T\vb{x}'\,\Pr_{\vb{w}\sim\Normal(\vb{0}, \mat{I})}\big(\vb{w}\T\vb{x} \ge 0,\ \vb{w}\T\vb{x}' \ge 0\big).

The probability is independent of κ\kappa because the indicators are scale invariant. Project w\vb{w} onto the span of x\vb{x} and x′\vb{x}'. The projection is isotropic Gaussian in this plane and has uniform direction. Directions making an acute angle with both vectors form a sector of width π−ϑ\pi - \vartheta, with ϑ=arccos⁡(x⊤x′)\vartheta = \arccos(\vb{x}\T\vb{x}'). The probability is (π−ϑ)/(2π)(\pi - \vartheta)/(2\pi) and

 H∞(x,x′)=u (π−arccos⁡u)2π,u=x⊤x′ \boxed{\ H^\infty(\vb{x}, \vb{x}') = \frac{u\,(\pi - \arccos u)}{2\pi}, \qquad u = \vb{x}\T\vb{x}'\ }

which is uu times half the zero-order arc-cosine kernel of Cho and Saul, 1−ϑ/π1 - \vartheta/\pi. Its diagonal is 1/21/2, so tr⁡(H∞)=n/2\tr(\mat{H}^\infty) = n/2. Du, Zhai, Póczos and Singh (2019) proved λ0=λmin⁡(H∞)>0\lambda_0 = \lambda_{\min}(\mat{H}^\infty) > 0 if no two inputs are parallel, an assumption in Arora et al. The first cell compares the formula with a finite network’s empirical NTK.

[ ]Two-layer ReLU NTK: arc-cosine formula and Monte CarloBrowser
import numpy as np

def ntk_relu_two_layer(X1, X2):
    """NTK H∞ de la red ReLU de dos capas (solo se entrena la primera capa): u (π − arccos u)/(2π)."""
    U = np.clip(X1 @ X2.T, -1.0, 1.0)
    return U * (np.pi - np.arccos(U)) / (2 * np.pi)

def empirical_ntk_first_layer(X1, X2, W, a):
    """NTK empírico de f(x) = (1/√m) Σ_r a_r relu(w_rᵀx) respecto de W:
    (1/m) Σ_r a_r² 1{w_rᵀx ≥ 0} 1{w_rᵀx' ≥ 0} xᵀx'."""
    m = W.shape[0]
    A1 = (X1 @ W.T >= 0) * a          # n1 × m, en coma flotante
    A2 = (X2 @ W.T >= 0) * a
    return (A1 @ A2.T) / m * (X1 @ X2.T)

rng = np.random.default_rng(0)
X = rng.normal(size=(30, 3))
X /= np.linalg.norm(X, axis=1, keepdims=True)
H = ntk_relu_two_layer(X, X)
print(f"diagonal de H∞: {H[0, 0]:.4f};  autovalores extremos: {np.linalg.eigvalsh(H)[[0, -1]].round(4)}")
print("      m    máx |Θ_m − H∞|   × √m")
for m in [100, 1_000, 10_000, 100_000]:
    W = rng.normal(size=(m, 3))
    a = rng.choice([-1.0, 1.0], size=m)
    err = np.abs(empirical_ntk_first_layer(X, X, W, a) - H).max()
    print(f"{m:7d}      {err:.4f}        {err * np.sqrt(m):.2f}")

The maximum error between the NTK of a network with mm neurons and H∞\mat{H}^\infty falls from 0.10.1 at m=100m = 100 to 0.00330.0033 at m=105m = 10^5. Column error⋅m\text{error}\cdot\sqrt m stays near 1. This illustrates concentration around the limit, with fluctuations of order 1/m1/\sqrt m. The same scale helps assess when a finite network is wide enough for the approximation.

The data-dependent bound

The step η=O(λ0/n2)\eta = \bigO(\lambda_0/n^2) is the one in Theorem 4.1, whose assumptions Theorem 5.1 inherits. For classification with y∈{−1,1}y \in \{-1, 1\}, Corollary 5.2 gives the same bound for classification error P(sign⁡f(x)≠y)\Pr(\operatorname{sign} f(\vb{x}) \ne y). The bound is independent of mm once the network is wide enough to behave like its linearization.

The optimization part of the proof shows that the network stays close to its linearization and travels a distance satisfying ∥W(k)−W(0)∥F≤y⊤(H∞)−1y+\norm{\mat{W}(k) - \mat{W}(0)}_F \le \sqrt{\vb{y}\T(\mat{H}^\infty)^{-1}\vb{y}} + up to small terms (Lemma 5.3). For generalization, the Rademacher complexity of networks with ∥W−W(0)∥F≤B\norm{\mat{W} - \mat{W}(0)}_F \le B is, up to terms vanishing with mm, B/2nB/\sqrt{2n} (Lemma 5.4). The factor 2 in the generalization inequality turns B/2nB/\sqrt{2n} into 2B2/n\sqrt{2B^2/n}. The kernel argument follows the same structure, which the exercises develop:

  1. The interpolator f^=Θ(⋅,X)Θ−1y\hat f = \Theta(\cdot, \mat{X})\mat{\Theta}^{-1}\vb{y} has RKHS norm ∥f^∥H2=y⊤Θ−1y\norm{\hat f}_{\mathcal{H}}^2 = \vb{y}\T\mat{\Theta}^{-1}\vb{y}.
  2. The ball {∥f∥H≤B}\{\norm{f}_{\mathcal{H}} \le B\} has empirical Rademacher complexity ≤Btr⁡Θ/n\le B\sqrt{\tr\mat{\Theta}}/n. With a Lipschitz loss, the Rademacher bound gives LD(f)≤LS(f)+2Btr⁡Θ/n+3log⁡(2/δ)/(2n)L_{\mathcal{D}}(f) \le L_S(f) + 2B\sqrt{\tr\mat{\Theta}}/n + 3\sqrt{\log(2/\delta)/(2n)} for every ff in the ball.
  3. Choosing BB from the data requires accounting for that choice. Use a grid of radii BjB_j and a union bound with ∑jδj=δ\sum_j\delta_j = \delta, adding a term of order log⁡log⁡(⋅)/n\sqrt{\log\log(\cdot)/n}.
  4. f^\hat f interpolates and ℓ(y,y)=0\ell(y, y) = 0, so LS(f^)=0L_S(\hat f) = 0. With tr⁡H∞=n/2\tr\mat{H}^\infty = n/2 the leading term is 2y⊤(H∞)−1yn/2/n=2y⊤(H∞)−1y/n2\sqrt{\vb{y}\T(\mat{H}^\infty)^{-1}\vb{y}}\sqrt{n/2}/n = \sqrt{2\vb{y}\T(\mat{H}^\infty)^{-1}\vb{y}/n}.

Real and random labels have different spectral alignment. Diagonalize H∞=∑iλivivi⊤\mat{H}^\infty = \sum_i \lambda_i\vb{v}_i\vb{v}_i\T:

y⊤(H∞)−1y=∑i=1n(vi⊤y)2λi.\vb{y}\T(\mat{H}^\infty)^{-1}\vb{y} = \sum_{i=1}^n \frac{(\vb{v}_i\T\vb{y})^2}{\lambda_i}.

Structured labels concentrate energy in large-eigenvalue directions, the smooth functions favored by the kernel, making the sum small. Random labels spread energy evenly. If yiy_i are independent uniform signs, the arithmetic–harmonic mean inequality gives E[y⊤(H∞)−1y]=tr⁡((H∞)−1)=∑i1/λi≥n2/∑iλi=2n\E[\vb{y}\T(\mat{H}^\infty)^{-1}\vb{y}] = \tr((\mat{H}^\infty)^{-1}) = \sum_i 1/\lambda_i \ge n^2/\sum_i\lambda_i = 2n, so E[2y⊤(H∞)−1y/n]≥4\E[2\vb{y}\T(\mat{H}^\infty)^{-1}\vb{y}/n] \ge 4. In practice small eigenvalues dominate the sum and make it much larger. The hypothesis class is identical in both cases. Arora et al. show that the quantity rises with label randomization on MNIST and CIFAR-10.

InteractiveThe bound distinguishes real labels from random labels
Training data and decision boundary of the kernel predictor sign H∞(x,X)(H∞)−1y\mathrm{sign}\,\mat{H}^\infty(\vb{x}, \mat{X})(\mat{H}^\infty)^{-1}\vb{y}. Outlined points have changed labels.
Computing the kernel…
0.20
Training points nn
StatusComputing the kernel…
Two moons with noise 0.1, embedded in the sphere of R3\R^3 as (z1−0.5,z2−0.25,1)/norm(z_1 - 0.5, z_2 - 0.25, 1)/\text{norm} (the third coordinate supplies a bias). At the chosen fraction pp, each label is replaced by a random sign in training and test. Top right: 2y⊤(H∞)−1y/n\sqrt{2\vb{y}\T(\mat{H}^\infty)^{-1}\vb{y}/n} using the analytical kernel. Bottom right: test 0–1 error for regression with H∞\mat{H}^\infty, the wide-network limit. Red compares with labels from the same distribution, the quantity the theorem bounds. Teal compares with clean labels. Each point averages four draws. Left: data and prediction boundary, with flipped labels outlined. The widget computes the results in your browser.

Start with p=0.2p = 0.2 and lower it to p=0p = 0. The boundary becomes cleaner and the bound falls. As nn increases, the quantity falls for real labels and rises for random labels. The next cell reproduces the result in NumPy.

[ ]How label noise changes the boundBrowser
def moons(n, noise, rng):
    """Dos lunas con etiquetas ±1 (la mitad en cada clase), ángulo uniforme en [0, π]."""
    t = np.pi * rng.random(n)
    cls = np.arange(n) % 2
    z = np.where(cls[:, None] == 0, np.c_[np.cos(t), np.sin(t)], np.c_[1 - np.cos(t), 0.5 - np.sin(t)])
    return z + noise * rng.normal(size=(n, 2)), np.where(cls == 0, -1.0, 1.0)

def embed(z):
    """(z₁ − 0.5, z₂ − 0.25, 1) / norma: puntos de la esfera unidad de R³."""
    A = np.c_[z[:, 0] - 0.5, z[:, 1] - 0.25, np.ones(len(z))]
    return A / np.linalg.norm(A, axis=1, keepdims=True)

def data_dependent_bound(H, y):
    return np.sqrt(2 * y @ np.linalg.solve(H, y) / len(y))

def randomize(y, p, rng):
    """Cada etiqueta se sustituye, con probabilidad p, por un signo uniforme."""
    y = y.copy()
    mask = rng.random(len(y)) < p
    y[mask] = rng.choice([-1.0, 1.0], size=mask.sum())
    return y

rng = np.random.default_rng(1)
z_te, y_te = moons(1000, 0.1, rng)
X_te = embed(z_te)
print("   n     p    √(2yᵀH⁻¹y/n)   error test (D_p)   error frente a limpias")
for n, ps in [(200, [0.0, 0.1, 0.2, 0.4, 0.6, 0.8, 1.0]), (100, [0.0, 1.0]), (400, [0.0, 1.0])]:
    z, y = moons(n, 0.1, rng)
    X = embed(z)
    Hn = ntk_relu_two_layer(X, X)
    K_te = ntk_relu_two_layer(X_te, X)
    for p in ps:
        b, e1, e2 = [], [], []
        for s in range(5):
            r = np.random.default_rng(100 + s)
            yp, ytp = randomize(y, p, r), randomize(y_te, p, r)
            pred = np.sign(K_te @ np.linalg.solve(Hn, yp))
            b.append(data_dependent_bound(Hn, yp))
            e1.append(np.mean(pred != ytp))
            e2.append(np.mean(pred != y_te))
        print(f"{n:4d}  {p:4.1f}      {np.mean(b):6.2f}            {np.mean(e1):.3f}              {np.mean(e2):.3f}")
    if n == 200:
        lam = np.linalg.eigvalsh(Hn)
        print(f"      λ_min(H∞) = {lam[0]:.2e};  para signos uniformes, E[2yᵀH⁻¹y/n] = 2 tr(H⁻¹)/n = {2 * np.sum(1 / lam) / n:.1f}")

from sklearn.kernel_ridge import KernelRidge
kr = KernelRidge(alpha=1e-10, kernel='precomputed').fit(Hn, y)
print(f"KernelRidge de scikit-learn frente a la solución directa: máx. diferencia {np.abs(kr.predict(K_te) - K_te @ np.linalg.solve(Hn, y)).max():.1e}")

With n=200n = 200, the quantity rises from 1.771.77 on real labels to 8.178.17 with 10% randomized and 19.019.0 with all labels randomized. Test error rises from 0.40.4% to 50.350.3%, in the same order. With real labels it falls from 2.272.27 (n=100n = 100) to 1.771.77 and 1.141.14 (n=400n = 400). With random labels it rises from 15.715.7 to 22.822.8. Under random labels expectation 2tr⁡((H∞)−1)/n=370.92\tr((\mat{H}^\infty)^{-1})/n = 370.9 is for the squared quantity, and 370.9=19.3\sqrt{370.9} = 19.3 matches the measured 19.019.0. This is almost a hundred times the guaranteed 4 because tiny eigenvalues dominate ∑i1/λi\sum_i 1/\lambda_i (λmin⁡=5.2⋅10−4\lambda_{\min} = 5.2\cdot 10^{-4}), and random labels put energy in those directions. Even with real labels the quantity exceeds 1, so it is vacuous as a bound on a loss in [0,1][0, 1]. Its value here is the ranking and dependence on nn.

Spectral dynamics and spectral bias

Residuals decay along eigendirections

Return to part (1) of the linearized dynamics theorem with f0=0f_0 = 0. In the eigenbasis Θ=∑iλivivi⊤\mat{\Theta} = \sum_i\lambda_i\vb{v}_i\vb{v}_i\T,

y−ft(X)=∑i=1ne−ηλit (vi⊤y) vi,∥y−ft(X)∥2=∑i=1ne−2ηλit(vi⊤y)2.\vb{y} - f_t(\mat{X}) = \sum_{i=1}^n e^{-\eta\lambda_i t}\,(\vb{v}_i\T\vb{y})\,\vb{v}_i, \qquad \norm{\vb{y} - f_t(\mat{X})}^2 = \sum_{i=1}^n e^{-2\eta\lambda_i t}(\vb{v}_i\T\vb{y})^2 .

Each component of the residual decays independently at rate ηλi\eta\lambda_i with half-life ln⁡2/(ηλi)\ln 2/(\eta\lambda_i). Discrete gradient descent with step η\eta replaces the exponential by (1−ηλi)t(1 - \eta\lambda_i)^t. Arora et al., Theorem 4.1, show that wide networks follow this rule up to a small error. Random labels train more slowly because their energy extends into directions with small λi\lambda_i.

Rahaman et al. (2019) describe this effect using the Fourier spectrum of ReLU networks during training. Low frequencies are learned before high frequencies. The NTK gives a quantitative prediction. On a circle with nn evenly spaced points φj=2πj/n\varphi_j = 2\pi j/n, a kernel depending only on φ−φ′\varphi - \varphi' gives a circulant Gram matrix. The eigenvectors are the Fourier modes cos⁡kφ\cos k\varphi and sen⁡kφ\operatorname{sen} k\varphi with eigenvalue λk=∑jΘ(φj)cos⁡(kφj)\lambda_k = \sum_j \Theta(\varphi_j)\cos(k\varphi_j). For H∞\mat{H}^\infty with augmented input x=(cos⁡φ,sen⁡φ,1)/2\vb{x} = (\cos\varphi, \operatorname{sen}\varphi, 1)/\sqrt2, mimicking a network with bias, eigenvalues decrease with frequency. Fourier features help coordinate networks represent fine details that otherwise lie in the spectral tail.

Removing the constant coordinate has a stronger effect. Since arccos⁡u=π/2−arcsin⁡u\arccos u = \pi/2 - \arcsin u, the kernel is H∞(u)=u/4+uarcsin⁡(u)/(2π)H^\infty(u) = u/4 + u\arcsin(u)/(2\pi) and uarcsin⁡uu\arcsin u is even in uu. With u=cos⁡Δu = \cos\Delta, even powers of cos⁡Δ\cos\Delta contain only even frequencies, while the term u/4u/4 contains only frequency 1. Odd frequencies k≥3k \ge 3 have eigenvalue exactly zero. A bias-free two-layer network in the kernel regime cannot learn sen⁡3φ\operatorname{sen} 3\varphi on the circle regardless of training time.

InteractiveLearning along eigendirections
  • target f∗f^*
  • linearized network at t
For each frequency kk, the light bar shows target energy, the red bar shows residual energy, and the orange marks show the filter 1−e−ηλkt1 - e^{-\eta\lambda_k t}.
Target
6
t = 0.10
t = 0.10
Residual ∥y−ft(X)∥2/∥y∥2\|\vb{y} - f_t(\mat{X})\|^2 / \|\vb{y}\|^293.04 %
Fraction learned for mode k = 6: 1−e−ηλkt1 - e^{-\eta\lambda_k t}0.1 %
Half-life of mode k = 6: ln⁡2/(ηλk)\ln 2/(\eta\lambda_k)101
Equivalent ridge ρ≈1/(ηt)\rho \approx 1/(\eta t)100.00
The mode at frequency 6 has λ6=0.0686\lambda_{6} = 0.0686, compared with λ1=7.411\lambda_1 = 7.411. Its half-life is 108 times as long.
Sixty-four evenly spaced points on the circle. Kernel H∞\mat{H}^\infty takes augmented input (cos⁡φ,sen⁡φ,1)/2(\cos\varphi, \operatorname{sen}\varphi, 1)/\sqrt2. Linearized gradient flow uses η=0.1\eta = 0.1 and starts at f0=0f_0 = 0. Top: target (gray dashed) and prediction at time tt (blue), given between sample points by Θ(φ,X)Θ−1(I−e−ηΘt)y\Theta(\varphi, \mat{X})\mat{\Theta}^{-1}(\mat{I} - e^{-\eta\mat{\Theta}t})\vb{y}. Bottom left, by frequency kk: target energy (light bars), remaining residual energy (red bars), and learned fraction 1−e−ηλkt1 - e^{-\eta\lambda_k t} (orange). Bottom right: eigenvalues λk\lambda_k on a log scale. At the initial setting, t≈32t \approx 32 with target cos⁡φ+sen⁡6φ\cos\varphi + \operatorname{sen}6\varphi, the smooth component is learned and frequency 6 is partly learned. Play the animation, increase kk, and try the square wave.

Early stopping acts as a spectral filter

With f0=0f_0 = 0, part (1) gives ft(X)=(I−e−ηΘt)yf_t(\mat{X}) = (\mat{I} - e^{-\eta\mat{\Theta}t})\vb{y} on the training data. Each component vi⊤y\vb{v}_i\T\vb{y} is multiplied by gt(λi)=1−e−ηλitg_t(\lambda_i) = 1 - e^{-\eta\lambda_i t}. Kernel ridge with parameter ρ\rho and estimator Θ(Θ+ρI)−1y\mat{\Theta}(\mat{\Theta} + \rho\mat{I})^{-1}\vb{y} multiplies it by λi/(λi+ρ)\lambda_i/(\lambda_i + \rho). With ρ=1/(ηt)\rho = 1/(\eta t) and s=ηλits = \eta\lambda_i t, the two filters are 1−e−s1 - e^{-s} and s/(1+s)s/(1 + s), and

s1+s≤1−e−s≤2s1+s(s≥0).\frac{s}{1 + s} \le 1 - e^{-s} \le \frac{2s}{1 + s} \qquad (s \ge 0).

The left inequality is es≥1+se^s \ge 1 + s. The right is equivalent to es(1−s)≤1+se^s(1 - s) \le 1 + s. This is immediate for s≥1s \ge 1. For s<1s < 1, function ψ(s)=1+s−es(1−s)\psi(s) = 1 + s - e^s(1 - s) satisfies ψ(0)=0\psi(0) = 0 and ψ′(s)=1+ses>0\psi'(s) = 1 + se^s > 0. Stopping at tt is equivalent up to a factor of two per eigendirection to ridge with ρ=1/(ηt)\rho = 1/(\eta t). This is early stopping as regularization from lesson 15 in the NTK basis. Directions with λi≫1/(ηt)\lambda_i \gg 1/(\eta t) are already learned and those with λi≪1/(ηt)\lambda_i \ll 1/(\eta t) have hardly moved. The widget displays the equivalent ridge setting.

The next cell checks this prediction in a finite network. It uses gradient descent on Arora et al.’s model with m=4000m = 4000 neurons and antisymmetric initialization: every wr\vb{w}_r appears twice, with ar=+1a_r = +1 and ar=−1a_r = -1, so f0=0f_0 = 0 exactly. It trains on 64 circle points with target cos⁡φ+sen⁡3φ\cos\varphi + \operatorname{sen} 3\varphi and projects the residual into the Fourier basis.

[ ]Spectral bias: residual modes of a finite networkBrowser
n = 64
phi = 2 * np.pi * np.arange(n) / n
Xc = np.c_[np.cos(phi), np.sin(phi), np.ones(n)] / np.sqrt(2)
lam = np.real(np.fft.rfft(ntk_relu_two_layer(Xc, Xc)[0]))     # Gram circulante: λ_k = DFT de la primera fila
X2 = np.c_[np.cos(phi), np.sin(phi)]
lam_nobias = np.real(np.fft.rfft(ntk_relu_two_layer(X2, X2)[0]))
print("k          :", np.arange(8))
print("con sesgo  :", lam[:8].round(4))
print("sin sesgo  :", np.abs(lam_nobias[:8]).round(4))
print(f"sin sesgo, máx |λ_k| con k impar ≥ 3: {np.abs(lam_nobias[3::2]).max():.1e}")

y = np.cos(phi) + np.sin(3 * phi)
m, eta, steps = 4000, 0.1, 300
r = np.random.default_rng(3)
W = r.normal(size=(m // 2, 3))
W = np.r_[W, W]                                              # inicialización antisimétrica: f₀ = 0
a = np.r_[np.ones(m // 2), -np.ones(m // 2)]
W0 = W.copy()

def mode_energy(res, k):
    """Energía de la frecuencia k (coseno más seno) en Σ_j res_j²."""
    return 2 * np.abs(np.fft.rfft(res)[k]) ** 2 / n

print("\n   t    frec. 1: medida   predicha     frec. 3: medida   predicha")
for t in range(steps + 1):
    act = (Xc @ W.T >= 0)                                    # n × m
    res = (act * (Xc @ W.T)) @ a / np.sqrt(m) - y
    if t in (0, 10, 30, 100, 300):
        p1 = mode_energy(-y, 1) * (1 - eta * lam[1]) ** (2 * t)
        p3 = mode_energy(-y, 3) * (1 - eta * lam[3]) ** (2 * t)
        print(f"{t:4d}       {mode_energy(res, 1):.2e}    {p1:.2e}        {mode_energy(res, 3):.2e}    {p3:.2e}")
    W -= eta * ((act * res[:, None]).T @ Xc) * a[:, None] / np.sqrt(m)

A0 = (Xc @ W0.T >= 0).astype(float)
A1 = (Xc @ W.T >= 0).astype(float)
T0, T1 = A0 @ A0.T / m * (Xc @ Xc.T), A1 @ A1.T / m * (Xc @ Xc.T)
Hc = ntk_relu_two_layer(Xc, Xc)
print(f"\n‖W − W₀‖_F = {np.linalg.norm(W - W0):.2f} frente a √(yᵀH⁻¹y) = {np.sqrt(y @ np.linalg.solve(Hc, y)):.2f}  "
      f"(‖W₀‖_F = {np.linalg.norm(W0):.1f});  deriva del NTK ‖Θ_t − Θ_0‖_F / ‖Θ_0‖_F = {np.linalg.norm(T1 - T0) / np.linalg.norm(T0):.3f}")
y6 = np.cos(phi) + np.sin(6 * phi)
print(f"con sen 6φ en lugar de sen 3φ: √(yᵀH⁻¹y) = {np.sqrt(y6 @ np.linalg.solve(Hc, y6)):.2f}")

The eigenvalues are λ1=7.41\lambda_1 = 7.41 and λ3=0.30\lambda_3 = 0.30 with bias, and λ3=λ5=λ7=0\lambda_3 = \lambda_5 = \lambda_7 = 0 up to rounding without bias, as parity predicts. The network tracks kernel dynamics. Frequency 1 disappears within 10 steps, leaving energy ∼10−4\sim 10^{-4} from the mismatch between Θm\mat{\Theta}_m and H∞\mat{H}^\infty. Frequency 3 drops from 32 to 17.6 at t=10t = 10 and to 5.9 at t=30t = 30, compared with predictions 17.3 and 5.1. The approximation worsens when less than 1% of the initial residual remains (t=100t = 100). Differences between finite width 4000 and the limit then matter more, and the empirical NTK has changed by 2% over training. The last line illustrates Arora et al.’s lemma. The network moved by ∥W−W0∥F=11.06\norm{\mat{W} - \mat{W}_0}_F = 11.06, 10% of ∥W0∥F=110.1\norm{\mat{W}_0}_F = 110.1, close to y⊤(H∞)−1y=10.49\sqrt{\vb{y}\T(\mat{H}^\infty)^{-1}\vb{y}} = 10.49. With sen⁡6φ\operatorname{sen} 6\varphi its movement would be 21.7021.70 because λ6=0.069\lambda_6 = 0.069 is more than four times smaller than λ3\lambda_3. Harder labels can require greater movement from initialization and an earlier exit from the kernel regime. Try varying the target in the cell.

Spectral learning curves

Spectral bias describes training dynamics. Sample efficiency also depends on the spectrum. Take a kernel with Mercer decomposition K(x,x′)=∑ρηρϕρ(x)ϕρ(x′)K(\vb{x}, \vb{x}') = \sum_\rho \eta_\rho\phi_\rho(\vb{x})\phi_\rho(\vb{x}') relative to the input distribution, with eigenfunctions orthonormal in L2L^2, and expand the target as f∗(x)=∑ρvρϕρ(x)f^*(\vb{x}) = \sum_\rho v_\rho\phi_\rho(\vb{x}). Canatar, Bordelon and Pehlevan (2021) compute generalization error Eg=E∫(f^−f∗)2 ⁣dpE_g = \E\int (\hat f - f^*)^2\dd p for kernel regression with nn examples, ridge parameter λ\lambda and estimator (K+λI)−1y(\mat{K} + \lambda\mat{I})^{-1}\vb{y}, and noise variance σ2\sigma^2:

Eg=11−γ[∑ρ(κκ+nηρ)2vρ2+σ2γ],κ=λ+∑ρκ ηρκ+nηρ,γ=∑ρn ηρ2(κ+nηρ)2.E_g = \frac{1}{1 - \gamma}\left[\sum_\rho\Big(\frac{\kappa}{\kappa + n\eta_\rho}\Big)^2 v_\rho^2 + \sigma^2\gamma\right], \qquad \kappa = \lambda + \sum_\rho\frac{\kappa\,\eta_\rho}{\kappa + n\eta_\rho}, \qquad \gamma = \sum_\rho\frac{n\,\eta_\rho^2}{(\kappa + n\eta_\rho)^2}.

This resembles kernel ridge in the spectral basis, with an effective ridge κ\kappa induced by the problem even if λ=0\lambda = 0. The quantity nηρ/(nηρ+κ)n\eta_\rho/(n\eta_\rho + \kappa) is the learned fraction of mode ρ\rho. It is near 1 if ηρ≫κ/n\eta_\rho \gg \kappa/n and near 0 if ηρ≪κ/n\eta_\rho \ll \kappa/n. With nn examples, roughly the nn modes with largest eigenvalues are learned. Multiplying the equation by n/κn/\kappa, the equation for κ\kappa becomes ∑ρnηρ/(κ+nηρ)=n−nλ/κ\sum_\rho n\eta_\rho/(\kappa + n\eta_\rho) = n - n\lambda/\kappa. With λ=0\lambda = 0 the learned fractions sum to exactly nn. The derivation uses the nonrigorous replica method from statistical physics and describes typical behavior when nn and the number of relevant modes are large. The cell compares this theory with independent Gaussian features ϕρ(x)\phi_\rho(\vb{x}) of the same spectrum and with the actual data.

Canatar et al. use alignment to explain why the two-layer NTK needs fewer MNIST examples to distinguish zeros from ones than to distinguish eights from nines (Figure 1). More of the first target’s energy lies in early modes. The widget uses the explicit periodic Laplace kernel k(Δ)=cosh⁡((π−∣Δ∣)/ℓ)/cosh⁡(π/ℓ)k(\Delta) = \cosh((\pi - \abs{\Delta})/\ell)/\cosh(\pi/\ell) on the circle. Its eigenfunctions for uniform inputs are 11, 2cos⁡kφ\sqrt2\cos k\varphi and 2sen⁡kφ\sqrt2\operatorname{sen} k\varphi, with eigenvalues ck∝1/(1+ℓ2k2)c_k \propto 1/(1 + \ell^2k^2). The cell verifies this Fourier series of the hyperbolic cosine. Bandwidth ℓ\ell controls how fast the eigenvalues decay.

InteractiveLearning curves and target alignment
  • theory (current target)
  • theory (all energy at k = 1)
  • theory (all energy at k = 8)
  • simulation on the circle
Kernel spectrum at ℓ=0.30\ell = 0.30. The vertical line marks the high frequency K=8K = 8.
0.50
8
0.30
Simulation
Predicted error at n=64n = 642.20e−2
Theoretical nn for error 0.01 (current / aligned target)82 / 39
λ8/λ1\lambda_{8} / \lambda_10.1612
With nn examples, learning primarily covers modes with ck≫κ/nc_k \gg \kappa/n, around n/2n/2 frequencies. Frequency 1 is learned quickly. Frequency 8, with 50% of the energy, is learned only once nn is well above 2⋅82 \cdot 8. It controls the tail error, requiring 82 examples to get below 0.01, compared with 39 for the aligned target.
Kernel regression on uniformly sampled circle inputs using a periodic Laplace kernel, no noise and ridge λ=10−4\lambda = 10^{-4}. Target f∗=2(1−ρ)cos⁡φ+2ρcos⁡Kφf^* = \sqrt{2(1 - \rho)}\cos\varphi + \sqrt{2\rho}\cos K\varphi puts energy 1−ρ1 - \rho into frequency 1 and ρ\rho into KK. Blue is the predicted Canatar et al. learning curve. Dashed teal and red give completely aligned (ρ=0\rho = 0) and misaligned (ρ=1\rho = 1) targets. Magenta shows averages from either 10 circle simulations or six draws of Gaussian features with the same spectrum. At right, the spectrum marks frequency KK. The default splits energy equally between frequencies 1 and 8. The curve lies between the two references, and frequency 8 determines the tail. The readouts compare sample sizes to reach 0.01 with the aligned case. Change ρ\rho, KK and ℓ\ell or switch the simulation. Gaussian features track theory more closely than the tail of the circle simulation.
[ ]Learning curves: Canatar et al.’s theory and simulationBrowser
def laplace_spec(ell, K=1000):
    """Autovalores c_k (k = 0..K) del kernel periódico de Laplace normalizado (k(0) = 1)."""
    k = np.arange(K + 1)
    return 1 / (1 + (ell * k) ** 2) / ((np.pi / ell) / np.tanh(np.pi / ell))

def laplace_kernel(D, ell):
    """cosh((π − |Δ|)/ℓ) / cosh(π/ℓ), escrito de forma estable."""
    D = np.abs((D + np.pi) % (2 * np.pi) - np.pi)
    return np.exp(-D / ell) * (1 + np.exp(-2 * (np.pi - D) / ell)) / (1 + np.exp(-2 * np.pi / ell))

def modes(c, rho, K):
    """Autovalores con multiplicidad (k ≥ 1: coseno y seno) y energía del objetivo en cada modo."""
    eta = np.r_[c[0], np.repeat(c[1:], 2)]
    v2 = np.zeros_like(eta)
    v2[1] = 1 - rho
    v2[2 * K - 1] += rho
    return eta, v2

def canatar_eg(n, eta, v2, lam=1e-4, sigma2=0.0):
    """Ecuación (4) de Canatar et al.: κ por bisección en escala logarítmica."""
    lo, hi = np.log(1e-16), np.log(1e3)
    for _ in range(90):
        kap = np.exp((lo + hi) / 2)
        if kap - lam - kap * np.sum(eta / (kap + n * eta)) > 0:
            hi = np.log(kap)
        else:
            lo = np.log(kap)
    kap = np.exp((lo + hi) / 2)
    gam = np.sum(n * eta ** 2 / (kap + n * eta) ** 2)
    return (np.sum(v2 * (kap / (kap + n * eta)) ** 2) + sigma2 * gam) / (1 - gam)

D = np.linspace(-np.pi, np.pi, 7)
cf = laplace_spec(0.5, 20000)
serie = cf[0] + 2 * np.cos(np.outer(D, np.arange(1, 20001))) @ cf[1:]
print(f"kernel cerrado frente a su serie de Fourier truncada en k = 20000: máx. dif. {np.abs(laplace_kernel(D, 0.5) - serie).max():.1e}")

ell, K = 0.3, 8
c = laplace_spec(ell)
r = np.random.default_rng(0)
grid = np.linspace(0, 2 * np.pi, 256, endpoint=False)
print(" ρ     n     teoría    circunferencia   rasgos gaussianos")
for rho in [0.0, 1.0]:
    eta_, v2 = modes(c, rho, K)
    fs = lambda t: np.sqrt(2 * (1 - rho)) * np.cos(t) + np.sqrt(2 * rho) * np.cos(K * t)
    eg, vg = modes(laplace_spec(ell, 300), rho, K)
    for n in [8, 32, 128]:
        ec = []
        for s in range(20):
            x = r.uniform(0, 2 * np.pi, n)
            al = np.linalg.solve(laplace_kernel(x[:, None] - x[None], ell) + 1e-4 * np.eye(n), fs(x))
            ec.append(np.mean((laplace_kernel(grid[:, None] - x[None], ell) @ al - fs(grid)) ** 2))
        eG = []
        for s in range(10):
            Z = r.normal(size=(n, len(eg)))                  # rasgos gaussianos con el mismo espectro
            al = np.linalg.solve((Z * eg) @ Z.T + 1e-4 * np.eye(n), Z @ np.sqrt(vg))
            eG.append(np.sum((eg * (Z.T @ al) - np.sqrt(vg)) ** 2))
        print(f"{rho:3.0f}  {n:4d}   {canatar_eg(n, eta_, v2):.2e}     {np.mean(ec):.2e}         {np.mean(eG):.2e}")

For ℓ=0.3\ell = 0.3 with the aligned target (ρ=0\rho = 0), theory predicts 1.67⋅10−21.67\cdot 10^{-2} error at 32 examples and 9.5⋅10−59.5\cdot 10^{-5} at 128. For the misaligned target (ρ=1\rho = 1, with all energy in frequency 8), it predicts 0.2880.288 and 3.4⋅10−33.4\cdot 10^{-3}, between 17 and 36 times more error for the same data. Gaussian-feature simulations match (1.87⋅10−21.87\cdot 10^{-2}, 7.2⋅10−57.2\cdot 10^{-5}, 0.3100.310 and 3.08⋅10−33.08\cdot 10^{-3}). Circle simulations preserve the shape and ordering but predictably differ in the transition region, up to sixfold at ρ=1\rho = 1 and n=128n = 128 (2.18⋅10−22.18\cdot 10^{-2}). They use the same spectrum and target, but a different feature distribution. The Gaussian-feature assumption fails for cos⁡kφ\cos k\varphi and sen⁡kφ\operatorname{sen} k\varphi on one dimension. Alignment has a similar effect in both simulations.

Limits of the kernel regime

The dkd^k barrier for inner-product kernels

The limits become prominent in high dimension. Ghorbani, Mei, Misiakiewicz and Montanari (2021) study inputs uniform on the sphere in Rd\R^d with radius d\sqrt d and a rotation-invariant kernel K(x,x′)=h(x⊤x′/d)K(\vb{x}, \vb{x}') = h(\vb{x}\T\vb{x}'/d). This includes the NTK and random-feature kernel of a fully connected network at infinite width. The eigenfunctions are spherical harmonics grouped by polynomial degree. There are on the order of dkd^k harmonics of degree kk, and rotation invariance gives all of them the same eigenvalue. With nn examples kernel regression learns only degrees containing fewer than nn modes.

The kernel treats all dd degree-1 directions alike and all ∼d2/2\sim d^2/2 degree-2 directions alike, and so on. A single-index target f∗(x)=g(⟨w∗,x⟩)f^*(\vb{x}) = g(\inner{\vb{w}^*}{\vb{x}}) depends on only one direction, but the kernel treats its degree-kk component as a generic polynomial. The following cell expands the experiment’s target g(z)=(∣z∣−2/π)/1−2/πg(z) = (\abs{z} - \sqrt{2/\pi})/\sqrt{1 - 2/\pi} in Hermite polynomials.

[ ]The barrier in numbers: where the energy of |z| liesBrowser
from math import factorial
from numpy.polynomial.hermite_e import hermegauss, hermeval

zq, wq = hermegauss(200)
wq = wq / wq.sum()                                           # cuadratura para z ~ N(0, 1)
g = (np.abs(zq) - np.sqrt(2 / np.pi)) / np.sqrt(1 - 2 / np.pi)
print(f"varianza de g (cuadratura): {np.sum(wq * g ** 2):.3f}")
for k in range(7):
    ck = np.zeros(k + 1); ck[k] = 1
    print(f"grado {k}: energía {np.sum(wq * g * hermeval(zq, ck)) ** 2 / factorial(k):.4f}")
d = 20
dims = [1, d, d * (d + 1) // 2 - 1, (d + 2) * (d + 1) * d // 6 - d]   # C(d+k−1, k) − C(d+k−3, k−2)
print(f"armónicos esféricos en d = {d}: grado 0..3 → {dims}; acumulado hasta grado 2: {sum(dims[:3])}")

gg is even, so it has no degree-1 component. Degree 2 accounts for 87% of its variance, degree 4 for 7%, and higher degrees for the rest. In d=20d = 20 there are 209 degree-2 harmonics. With n=200n = 200 examples, the kernel is near the degree-2 threshold and learns little of the target. A network that identifies direction w∗=e1\vb{w}^* = \vb{e}_1 only needs to fit a one-variable function.

Separations from feature-learning networks

Two results formalize this intuition.

  • Wei, Lee, Liu and Ma (2019) construct a simple distribution in dd dimensions. A network with optimal regularization ℓ2\ell_2 learns with O(d)\bigO(d) examples, while its NTK requires Ω(d2)\Omega(d^2). Regularization takes the network out of the kernel regime and changes sample complexity.
  • Damian, Lee and Soltanolkotabi (2022) study targets f∗(x)=g(Ux)f^*(\vb{x}) = g(\mat{U}\vb{x}) with U∈Rr×d\mat{U} \in \R^{r\times d} and r≪dr \ll d, where gg is a polynomial of degree pp. A kernel needs n≳dpn \gtrsim d^p examples. Gradient descent on a two-layer network outside the kernel regime succeeds with n≈d2r+drpn \approx d^2 r + d r^p because its first layer learns a representation of the rr relevant directions.

The widget uses the same network on one such task in both regimes and varies only Chizat et al.’s output scale α\alpha.

InteractiveOutput scale: lazy and rich regimes
  • test (network)
  • training
  • test (network, final)
  • NTK drift
For each neuron wj\vb{w}_j, the horizontal axis shows the component along e1\vb{e}_1, and the vertical axis shows the norm of the orthogonal part. Hollow marks show the initial positions and orange marks show the current positions.
  • initial
  • current
α = 1
StatusPreparing data and the initial NTK…
A single-index model in dimension 20: x\vb{x} is uniform on a sphere of radius 20\sqrt{20}, y=g(x1)y = g(x_1) with g(z)=(∣z∣−2/π)/1−2/πg(z) = (\abs{z} - \sqrt{2/\pi})/\sqrt{1 - 2/\pi}, with 200 training and 1000 test points. Network h(x)=164∑jajReLU⁡(wj⊤x)h(\vb{x}) = \frac{1}{64}\sum_j a_j\relu(\vb{w}_j\T\vb{x}) and centered model f=α(hθ−hθ0)f = \alpha(h_\theta - h_{\theta_0}) trained by GD on 12nα2∑i(f(xi)−yi)2\frac{1}{2n\alpha^2}\sum_i(f(\vb{x}_i) - y_i)^2 at step size η=64\eta = 64 for 1500 browser steps. Top left: training and test error during training, against ridgeless regression with the initial NTK (gray). Below: final error and relative NTK drift for each computed α\alpha. At right: every neuron’s component in the relevant direction e1\vb{e}_1 and the norm of its orthogonal part at initialization (open marker) and now (orange). The opening setting α=1\alpha = 1 is rich. Neurons stretch along e1\vb{e}_1 and test error falls below kernel regression. Raise α\alpha to 1000.

With α=1\alpha = 1, the network learns the direction. The fraction of W\mat{W} energy along e1\vb{e}_1 rises from ≈1/d=0.05\approx 1/d = 0.05 to almost half. The kernel changes by several times its initial norm and test error falls to one tenth of kernel regression’s. With α=1000\alpha = 1000 the network still fits the training data, neurons barely move, the NTK changes by 3%, and predictions match kernel regression. The GPU lab repeats the experiment with three seeds. Test error goes from 0.0770.077 (α=1\alpha = 1) to 0.2350.235 (α=10\alpha = 10) and 0.7420.742 (α=1000\alpha = 1000), exactly the 0.7420.742 of regression with the initial kernel. Drift falls from 4.14.1 to 0.0300.030, and energy in e1\vb{e}_1 falls from 0.4770.477 to 0.0460.046.

How the empirical kernel changes

An evolving NTK can describe networks outside the fixed-kernel regime. Measure how much it changes with ∥Θt−Θ0∥F/∥Θ0∥F\norm{\mat{\Theta}_t - \mat{\Theta}_0}_F/\norm{\mat{\Theta}_0}_F and in which direction with Cristianini et al.’s kernel–target alignment,

A(K,yy⊤)=y⊤Ky∥K∥F ∥y∥2∈[0,1],A(\mat{K}, \vb{y}\vb{y}\T) = \frac{\vb{y}\T\mat{K}\vb{y}}{\norm{\mat{K}}_F\,\norm{\vb{y}}^2} \in [0, 1],

the cosine between K\mat{K} and yy⊤\vb{y}\vb{y}\T viewed as matrices. When the kernel concentrates energy along the labels, AA rises and the target becomes easier in the sense of the preceding section.

Fort, Dziugaite, Paul, Kharaghani, Roy and Ganguli (2020) measured NTK evolution in deep networks. They found a short initial phase of two or three epochs in which the NTK learns useful features and improves over initialization by roughly a factor of three. It then changes at a steadier rate. Kernel regression with the partially trained NTK matches the full network after 15% to 45% of training. Atanasov, Bordelon and Pehlevan (2022) describe silent alignment in homogeneous networks with small initialization and whitened inputs. The NTK changes its eigenspaces while small, before the loss drops much, and then mainly grows in scale. The resulting function is kernel regression with the final NTK. The effect weakens on unwhitened inputs.

The network can learn a task-specific kernel and then behave largely like regression with that kernel. Open problems include predicting the amount and direction of kernel drift in deep networks under SGD with large steps, scaling networks so that all layers continue to adapt as width grows (motivating μP and the spectral condition), and explaining which properties of real data make a learned kernel generalize. A fixed-kernel regime lacks the representation learning that would change those features.

GPU implementation: empirical NTK with torch.func

The empirical NTK of a network with PP parameters on nn points is JJ⊤\mat{J}\mat{J}\T with J∈Rn×P\mat{J} \in \R^{n\times P}. A backward pass per example takes nn passes, and storing all of J\mat{J} takes nPnP values. With n=2500n = 2500 and P=8⋅105P = 8\cdot 10^5, that is 8 GB in float32, the whole memory of an RTX 4060. torch.func addresses both. vmap(jacrev(f)) computes a block of Jacobians in a vectorized pass, so storage is limited to one block plus the Gram matrix. For larger networks the NTK tutorial in torch.func shows Jacobian-vector-product alternatives with jvp and vjp that avoid materializing J\mat{J}. For infinite-width kernels there are specialized libraries such as Neural Tangents (Novak et al.) in JAX.

The lab has two parts. The first repeats the last widget with the same mean-field network and three seeds. It checks the widget’s closed-form kernel using torch.func. The second uses NTK parameterization f(x)=v⊤ReLU⁡(Wx/d)/wf(\vb{x}) = \vb{v}\T\relu(\mat{W}\vb{x}/\sqrt d)/\sqrt w with W,v∼N(0,1)\mat{W}, \vb{v} \sim \Normal(0, 1). Training uses full-batch gradient descent (torch.optim.SGD, all examples at once, 3000 steps), with the same step size for all widths w∈{64,256,1024,4096}w \in \{64, 256, 1024, 4096\}, on two tasks. MNIST even-versus-odd uses 500 training images downsampled to 14×1414\times 14 and 2000 test images. The single-index task uses 200 training and 2000 test points. For each network, the lab measures NTK drift, alignment with labels, and test error of the network and kernel regression with its initial and final kernels. For the single-index task it also adds a width-1024 network with α=0.03\alpha = 0.03 in the rich regime. The run takes about a minute on the GPU and uses under 1.5 GB of memory in the original setup.

[ ]Empirical NTK, drift, and final kernel on a GPULocal GPU
"""Régimen de kernel en la GPU: NTK empírico con torch.func, deriva, alineamiento y kernel final.

Parte 1: escala de salida α (Chizat, Oyallon y Bach) en el modelo de índice único del interactivo.
Parte 2: anchura 64 a 4096 en parametrización NTK, sobre MNIST par/impar y sobre el modelo de índice único.
"""
import math, os
import numpy as np
import torch
from torch.func import functional_call, vmap, jacrev
from torchvision import datasets

dev = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.backends.cuda.matmul.allow_tf32 = False   # NTK y sistemas lineales en float32 completo

# ------------------------------------------------------------------ NTK empírico
def empirical_ntk(model, params, XA, XB, chunk=128):
    """Θ(XA, XB) = J(XA) J(XB)ᵀ, con el jacobiano por ejemplo vía vmap(jacrev), en bloques de `chunk` ejemplos."""
    def f1(p, x):
        return functional_call(model, p, (x.unsqueeze(0),)).squeeze(0)
    jac = vmap(jacrev(f1), (None, 0))
    def J(X):
        return torch.cat([j.reshape(len(X), -1) for j in jac(params, X).values()], 1)
    JB = torch.cat([J(XB[i:i + chunk]) for i in range(0, len(XB), chunk)])
    out = torch.cat([J(XA[i:i + chunk]) @ JB.T for i in range(0, len(XA), chunk)])
    del JB
    return out

def krr_predict(K_tr, K_te, y, rel_ridge=1e-6):
    """Regresión kernel casi sin ridge (λ = 1e-6 · traza/n, solo por estabilidad numérica)."""
    lam = rel_ridge * K_tr.diagonal().mean()
    return K_te @ torch.linalg.solve(K_tr + lam * torch.eye(len(y), device=K_tr.device), y)

def rel_drift(K, K0):
    return ((K - K0).norm() / K0.norm()).item()

def kernel_alignment(K, y):
    """A(K, yyᵀ) = yᵀKy / (‖K‖_F ‖y‖²): el coseno entre K e yyᵀ como matrices."""
    return (y @ K @ y / (K.norm() * (y @ y))).item()

# ------------------------------------------------------------------ datos
gen = np.random.default_rng(0)
D_IDX = 20
def sphere(n):
    X = gen.normal(size=(n, D_IDX))
    return X * math.sqrt(D_IDX) / np.linalg.norm(X, axis=1, keepdims=True)
g_abs = lambda z: (np.abs(z) - math.sqrt(2 / math.pi)) / math.sqrt(1 - 2 / math.pi)
def to_t(a):
    return torch.tensor(a, dtype=torch.float32, device=dev)

# ================================================================== Parte 1
print('Parte 1: escala de salida α, red de campo medio con m = 64 (el modelo del interactivo)')
class MeanField(torch.nn.Module):
    def __init__(self, m, d):
        super().__init__()
        self.W = torch.nn.Parameter(torch.randn(m, d) / math.sqrt(d))
        self.a = torch.nn.Parameter(torch.randn(m))
    def forward(self, x):
        return torch.relu(x @ self.W.T) @ self.a / self.a.numel()

ALPHAS = [1, 10 ** 0.5, 10, 10 ** 1.5, 100, 1000]
res1 = {a: [] for a in ALPHAS}
ker1 = []
for seed in range(3):
    Xtr, Xte = sphere(200), sphere(1000)
    ytr, yte = to_t(g_abs(Xtr[:, 0])), to_t(g_abs(Xte[:, 0]))
    Xtr, Xte = to_t(Xtr), to_t(Xte)
    torch.manual_seed(seed)
    base = MeanField(64, D_IDX).to(dev)
    p0 = {k: v.detach().clone() for k, v in base.named_parameters()}
    K0 = empirical_ntk(base, p0, Xtr, Xtr)
    if seed == 0:   # comprobación: la fórmula cerrada del NTK (la que usa el interactivo) frente a torch.func
        U = Xtr @ p0['W'].T
        Kc = (torch.relu(U) @ torch.relu(U).T + ((U > 0) * p0['a'] ** 2) @ (U > 0).float().T * (Xtr @ Xtr.T)) / 64 ** 2
        print(f'  NTK con torch.func frente a la fórmula cerrada: diferencia relativa {((K0 - Kc).norm() / Kc.norm()).item():.1e}')
    ker1.append(((krr_predict(K0, empirical_ntk(base, p0, Xte, Xtr), ytr) - yte) ** 2).mean().item())
    h0tr, h0te = base(Xtr).detach(), base(Xte).detach()
    for alpha in ALPHAS:
        net = MeanField(64, D_IDX).to(dev)
        net.load_state_dict(base.state_dict())
        opt = torch.optim.SGD(net.parameters(), lr=64.0)          # paso η = m
        for it in range(1500):
            opt.zero_grad()
            loss = 0.5 * ((alpha * (net(Xtr) - h0tr) - ytr) ** 2).mean() / alpha ** 2
            loss.backward()
            opt.step()
        p1 = {k: v.detach() for k, v in net.named_parameters()}
        W = p1['W']
        res1[alpha].append((((alpha * (net(Xte) - h0te) - yte) ** 2).mean().item(),
                            rel_drift(empirical_ntk(net, p1, Xtr, Xtr), K0),
                            ((W[:, 0] ** 2).sum() / (W ** 2).sum()).item()))
print(f'  regresión kernel con el NTK inicial (sin ridge): error de test {np.mean(ker1):.3f} (semillas: {", ".join(f"{e:.3f}" for e in ker1)})')
print('     α     test red   deriva NTK   energía en e1   (media de 3 semillas; al inicio la energía es ~1/d = 0.05)')
for a in ALPHAS:
    r = np.array(res1[a]).mean(0)
    print(f'  {a:7.1f}   {r[0]:.3f}      {r[1]:.3f}        {r[2]:.3f}')

# ================================================================== Parte 2
print()
print('Parte 2: parametrización NTK, f(x) = vᵀ relu(Wx/√d)/√w con W, v ~ N(0, 1) y GD de paso 1')
class NTKNet(torch.nn.Module):
    def __init__(self, w, d):
        super().__init__()
        self.W = torch.nn.Parameter(torch.randn(w, d))
        self.v = torch.nn.Parameter(torch.randn(w))
        self.d, self.w = d, w
    def forward(self, x):
        return torch.relu(x @ self.W.T / math.sqrt(self.d)) @ self.v / math.sqrt(self.w)

root = os.path.join(os.path.expanduser('~'), '.cache', 'atlas-data')       # MNIST se descarga la primera vez (unos 11 MB)
tr = datasets.MNIST(root, train=True, download=True)
te = datasets.MNIST(root, train=False, download=True)
def prep(ds, idx):
    X = ds.data[idx].float() / 255
    X = torch.nn.functional.avg_pool2d(X[:, None], 2).flatten(1)          # 14 × 14 = 196 píxeles
    X = X - X.mean(1, keepdim=True)
    X = X / X.norm(dim=1, keepdim=True) * math.sqrt(X.shape[1])           # norma √d
    y = (ds.targets[idx] % 2 == 0).float() * 2 - 1                        # par: +1, impar: −1
    return X.to(dev), y.to(dev)

tasks = {}
tasks['MNIST par/impar'] = (*prep(tr, torch.tensor(gen.choice(60000, 500, replace=False))),
                            *prep(te, torch.tensor(gen.choice(10000, 2000, replace=False))), 'clas')
Xi, Xit = sphere(200), sphere(2000)
tasks['índice único |z|'] = (to_t(Xi), to_t(g_abs(Xi[:, 0])), to_t(Xit), to_t(g_abs(Xit[:, 0])), 'reg')

WIDTHS = [64, 256, 1024, 4096]
CHECK = [10, 30, 100, 300, 1000]
for name, (Xtr, ytr, Xte, yte, kind) in tasks.items():
    d = Xtr.shape[1]
    if kind == 'clas':
        metric = lambda f: (torch.sign(f) != yte).float().mean().item()
    else:
        metric = lambda f: ((f - yte) ** 2).mean().item()
    print(f'\n  {name}: n = {len(ytr)}, test = {len(yte)}, d = {d}; ' + ('error 0-1' if kind == 'clas' else 'error cuadrático') + ' en test')
    print('  anchura    α     red     K_0     K_final   deriva   A(K_0)  A(K_final)   deriva en t = 10, 30, 100, 300, 1000 / deriva final')
    runs = [(w, 1.0, 3000) for w in WIDTHS] + ([(1024, 0.03, 6000)] if kind == 'reg' else [])
    for w, alpha, steps in runs:
        torch.manual_seed(1)
        net = NTKNet(w, d).to(dev)
        p0 = {k: v.detach().clone() for k, v in net.named_parameters()}
        f0tr, f0te = net(Xtr).detach(), net(Xte).detach()
        K0, K0te = empirical_ntk(net, p0, Xtr, Xtr), empirical_ntk(net, p0, Xte, Xtr)
        opt = torch.optim.SGD(net.parameters(), lr=1.0)
        drifts = {}
        for it in range(steps):
            if it in CHECK:
                drifts[it] = rel_drift(empirical_ntk(net, {k: v.detach() for k, v in net.named_parameters()}, Xtr, Xtr), K0)
            opt.zero_grad()
            loss = 0.5 * ((alpha * (net(Xtr) - f0tr) - ytr) ** 2).mean() / alpha ** 2
            loss.backward()
            opt.step()
        p1 = {k: v.detach() for k, v in net.named_parameters()}
        K1, K1te = empirical_ntk(net, p1, Xtr, Xtr), empirical_ntk(net, p1, Xte, Xtr)
        e_net = metric(alpha * (net(Xte) - f0te).detach())
        e_k0, e_k1 = metric(krr_predict(K0, K0te, ytr)), metric(krr_predict(K1, K1te, ytr))
        dfin = rel_drift(K1, K0)
        frac = ', '.join(f'{drifts[c] / dfin:.2f}' for c in CHECK)
        print(f'  {w:6d}  {alpha:5.2f}  {e_net:.3f}   {e_k0:.3f}   {e_k1:.3f}     {dfin:.3f}    {kernel_alignment(K0, ytr):.3f}   {kernel_alignment(K1, ytr):.3f}       {frac}')
        del K0, K0te, K1, K1te, net
        if dev.type == 'cuda':
            torch.cuda.empty_cache()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The recorded results show three patterns:

  • Drift falls with width. On MNIST it goes from 1.011.01 (w=64w = 64) to 0.420.42, 0.1260.126 and 0.0350.035 (w=4096w = 4096). On the single-index task it goes from 0.600.60 to 0.0330.033. Quadrupling width divides drift by factors between 2 and 3.6. Jacot et al.’s theory guarantees convergence to zero, while the width needed for negligible drift depends on the task.
  • The final kernel improves on initialization. On the single-index task with w=64w = 64, test error is 0.0870.087 with the final NTK versus 0.6860.686 with the initial NTK, and 0.1480.148 for the network. Alignment rises from 0.0320.032 to 0.0860.086. With w=4096w = 4096 the three errors nearly coincide (0.4780.478, 0.5030.503 and 0.4190.419), reflecting lazy training. On MNIST the improvement is smaller, 9.79.7% with the initial NTK versus 8.08.0% with the final one at w=64w = 64. The initial kernel already suits this task. Feature learning helps more when the fixed kernel is a poor fit.
  • The rich regime learns the kernel early. With w=1024w = 1024 and α=0.03\alpha = 0.03, test errors are 0.0470.047 for the network and 0.0560.056 for the final NTK, versus 0.4870.487 initially. Alignment reaches 0.1200.120, and the first 100 of 6000 steps produce 94% of final drift. In NTK parameterization with α=1\alpha = 1 the change is more gradual. On MNIST, 1000 steps, one third of the run, account for 52% to 61% of final drift. Fort et al.’s fast early phase appears in deep networks trained with SGD. The full-batch runs with one hidden layer here lack that phase.

Common mistakes

Exercises

ProofThe linearized model converges to kernel interpolation
Prove: Consider flin(x;θ)=f0(x)+ϕ(x)⊤(θ−θ0)f^{\mathrm{lin}}(\vb{x}; \theta) = f_0(\vb{x}) + \vb{\phi}(\vb{x})\T(\theta - \theta_0) with ϕ(x)=∇θf(x;θ0)\vb{\phi}(\vb{x}) = \grad_\theta f(\vb{x}; \theta_0), squared loss 12∥f(X)−y∥2\tfrac12\norm{f(\mat{X}) - \vb{y}}^2, and gradient flow at rate η\eta. Then ft(X)=y+e−ηΘt(f0(X)−y)f_t(\mat{X}) = \vb{y} + e^{-\eta\mat{\Theta}t}(f_0(\mat{X}) - \vb{y}). If Θ\mat{\Theta} is invertible and f0≡0f_0 \equiv 0, the limiting prediction at x\vb{x} is Θ(x,X)Θ−1y\Theta(\vb{x}, \mat{X})\mat{\Theta}^{-1}\vb{y}, the minimum-norm interpolator in the NTK RKHS.
0
Let J∈Rn×P\mat{J} \in \R^{n\times P} consist of rows ϕ(xi)⊤\vb{\phi}(\vb{x}_i)\T. Set Θ=JJ⊤\mat{\Theta} = \mat{J}\mat{J}\T and rt=ft(X)−y\vb{r}_t = f_t(\mat{X}) - \vb{y}.

Step 1 of 4. Which equation does rt\vb{r}_t satisfy?

ProofStructure of the Arora et al. bound
Prove: Let Θ\Theta be a fixed, sample-independent kernel with Θ(x,x)≤1\Theta(\vb{x}, \vb{x}) \le 1 and invertible sample Gram matrix Θ\mat{\Theta}. Let ℓ\ell take values in [0,1][0, 1], be 1-Lipschitz in its first argument, and satisfy ℓ(y,y)=0\ell(y, y) = 0. With probability at least 1−δ1 - \delta, the interpolator f^=Θ(⋅,X)Θ−1y\hat f = \Theta(\cdot, \mat{X})\mat{\Theta}^{-1}\vb{y} satisfies LD(f^)≤2cy⊤Θ−1y⋅tr⁡Θ/n+O(log⁡(log⁡(y⊤Θ−1y)/δ)/n)L_{\mathcal{D}}(\hat f) \le 2c\sqrt{\vb{y}\T\mat{\Theta}^{-1}\vb{y}\cdot\tr\mat{\Theta}}/n + \bigO\big(\sqrt{\log(\log(\vb{y}\T\mat{\Theta}^{-1}\vb{y})/\delta)/n}\big) for a constant cc arbitrarily close to 1.
0
Lemma (Rademacher complexity of RKHS balls): the class FB={f∈H:∥f∥H≤B}\mathcal{F}_B = \{f \in \mathcal{H}: \norm{f}_{\mathcal{H}} \le B\} has empirical Rademacher complexity R^S(FB)≤Btr⁡Θ/n\hat{\mathfrak{R}}_S(\mathcal{F}_B) \le B\sqrt{\tr\mat{\Theta}}/n.

Step 1 of 4. What is ∥f^∥H2\norm{\hat f}_{\mathcal{H}}^2?

NumericRKHS norm for aligned labels
Two points have Gram matrix Θ=(10.50.51)\mat{\Theta} = \begin{pmatrix} 1 & 0.5 \\ 0.5 & 1\end{pmatrix} and labels y=(1,1)\vb{y} = (1, 1). What is y⊤Θ−1y\vb{y}\T\mat{\Theta}^{-1}\vb{y}?
NumericLabels that disagree with the kernel
Use the same Θ\mat{\Theta} as in the preceding exercise. How many times larger is y⊤Θ−1y\vb{y}\T\mat{\Theta}^{-1}\vb{y} for y=(1,−1)\vb{y} = (1, -1) than for y=(1,1)\vb{y} = (1, 1)?
NumericHalf-life of a slow eigendirection
A residual component lies in an NTK eigendirection with λ=0.01\lambda = 0.01. You train by gradient flow with η=1\eta = 1. How much time tt does it take to halve the component?
QuizWhat holds in the lazy regime?
A network trains in the lazy regime and its NTK changes very little. Which statement holds?
QuizWhat can a kernel learn with d to the power 1.5 examples?
In the Ghorbani et al. setting with an inner-product kernel, uniform spherical inputs in large dimension dd, and n≍d1.5n \asymp d^{1.5} examples, what part of the target does kernel regression learn?
QuizEarly stopping regularizes
Train the linearized model from f0=0f_0 = 0 with η=0.1\eta = 0.1 and stop at t=100t = 100. Which description is closest?
CodeAnalytical NTK and the Arora et al. bound
Implement ntk_relu_two_layer(X1, X2) to return the matrix H∞(xi,xj′)=u(π−arccos⁡u)/(2π)H^\infty(\vb{x}_i, \vb{x}'_j) = u(\pi - \arccos u)/(2\pi) with u=xi⊤xj′u = \vb{x}_i\T\vb{x}'_j for unit rows. Clip uu to [−1,1][-1, 1] before taking arccos. Implement data_dependent_bound(H, y) to return 2y⊤H−1y/n\sqrt{2\vb{y}\T\mat{H}^{-1}\vb{y}/n} without explicitly inverting H\mat{H}. Tests compare your kernel to the empirical NTK of a 2⋅1052\cdot 10^5-neuron network and check that the bound rises with the fraction of randomized labels.
import numpy as np

def ntk_relu_two_layer(X1, X2):
  """H∞ entre las filas (de norma 1) de X1 y de X2."""
  U = X1 @ X2.T
  return U / 2          # sustituye por la fórmula arcocoseno

def data_dependent_bound(H, y):
  """√(2 yᵀ H⁻¹ y / n)."""
  return 0.0
Shift+Enter to run

Summary

Key idea
When a network barely changes its parameters, its linearization gives regression with the NTK. Kernel theory explains generalization through complexity y⊤Θ−1y\vb{y}\T\mat{\Theta}^{-1}\vb{y}, distinguishes real from random labels, and predicts learning order and sample requirements from eigendirections. Outside this regime a network can learn its kernel.
  • The empirical NTK Θθ(x,x′)=⟨∇θf(x),∇θf(x′)⟩\Theta_\theta(\vb{x}, \vb{x}') = \inner{\grad_\theta f(\vb{x})}{\grad_\theta f(\vb{x}')} governs gradient descent in function space. The linearized model obeys ft(X)=y+e−ηΘt(f0(X)−y)f_t(\mat{X}) = \vb{y} + e^{-\eta\mat{\Theta}t}(f_0(\mat{X}) - \vb{y}) and converges to the minimum-norm interpolator in the NTK RKHS.
  • Lazy training can arise from scale (Chizat et al.). With output α(h−h0)\alpha(h - h_0), parameter displacement is O(1/α)\bigO(1/\alpha). The NTK parameterization is mean-field with α=m\alpha = \sqrt m.
  • For two-layer ReLU, H∞(u)=u(π−arccos⁡u)/(2π)H^\infty(u) = u(\pi - \arccos u)/(2\pi) and the Arora et al. bound is 2y⊤(H∞)−1y/n\sqrt{2\vb{y}\T(\mat{H}^\infty)^{-1}\vb{y}/n}, twice the Rademacher complexity bound for the smallest RKHS ball containing the interpolator. On two moons it rises from 1.77 for real labels to 19.0 for random labels.
  • Each residual mode decays as e−ηλite^{-\eta\lambda_i t}. Early stopping at tt gives a similar filter to ridge with ρ=1/(ηt)\rho = 1/(\eta t), up to a factor of two. The bias-free two-layer ReLU NTK misses odd frequencies ≥3\ge 3 on the circle.
  • Kernel learning curves depend on target alignment with the spectrum (Canatar et al.). With nn examples, the learned modes have ηρ≫κ/n\eta_\rho \gg \kappa/n.
  • Inner-product kernels require ∼dk\sim d^k examples for degree kk (Ghorbani et al.). Feature-learning networks exploit low-dimensional structure with fewer examples (Wei et al.: O(d)\bigO(d) versus Ω(d2)\Omega(d^2); Damian et al.: d2r+drpd^2r + dr^p versus dpd^p).
  • In finite networks, the NTK can change and align with target labels. The final NTK may predict considerably better than the initial one (Fort et al. and Atanasov et al.).