Module contents
Lesson 16 of 20Advanced 110 min

Double descent and the interpolation regime

Reproduce double descent with random features, derive ridgeless risk in the proportional regime, explain the interpolation peak, assess optimal regularization, and study deep model-, epoch- and sample-wise variants.

After this lesson you can

  • Reproduce double descent with random features and the minimum-norm interpolator.
  • Calculate Gaussian-design least-squares variance and explain the peak through the smallest singular value of X.
  • State the Hastie, Montanari, Rosset and Tibshirani asymptotic risk as p/n approaches γ and use it to predict curves.
  • Demonstrate experimentally that optimal ridge regularization removes the peak.
  • Describe model-, epoch- and sample-wise deep double descent and effective model complexity.
  • Critique the parameter-count axis using effective parameters.

Before you start

Motivation: models larger than their data

The classical U-curve summarizes prior lessons on capacity: with few parameters a model cannot represent the signal (high bias), with too many it learns sample noise (high variance), and test error is smallest between them. VC and Rademacher bounds say something similar: the generalization gap grows with class capacity.

Modern practice has contradicted this for years. ResNet18 has about 11 million parameters and trains on 50,000 CIFAR-10 examples; language models have billions. Such models can memorize random labels, so their class can interpolate anything, yet they generalize, often better when larger. Belkin, Hsu, Ma and Mandal (2019) proposed reconciling the pictures: increasing capacity beyond training-data interpolation makes test error fall again after a peak. The U-curve is only the first half of a curve with two descents.

This lesson makes the phenomenon calculable. Reproduce it in the browser with random features; see that the peak is a conditioning problem (the design matrix’s smallest singular value collapses when parameter and data counts coincide); derive exact risk for the Gaussian linear model and its asymptotic limit; prove optimal regularization removes the peak; and study deep versions before questioning the horizontal axis itself: what does “number of parameters” mean?

The Belkin et al. experiment

Start with the random-features model: draw pp vectors w1,…,wp\vb{w}_1, \dots, \vb{w}_p once, fix them and fit only the output layer,

f(x)=∑j=1paj ϕ(wj⊤x+bj),Φij=ϕ(wj⊤xi+bj),Φ∈Rn×p.f(\vb{x}) = \sum_{j=1}^p a_j\,\phi(\vb{w}_j\T\vb{x} + b_j), \qquad \Phi_{ij} = \phi(\vb{w}_j\T\vb{x}_i + b_j), \qquad \Phi \in \R^{n\times p}.

This is a two-layer network with frozen first layer; least-squares fitting is linear regression on feature matrix Φ\Phi. While p<np < n, system Φa=y\Phi\vb{a} = \vb{y} is overdetermined and its least-squares solution is unique (if Φ\Phi has rank pp). When p≥np \ge n and Φ\Phi has rank nn, infinitely many solutions interpolate, and Belkin et al. choose the minimum-norm one,

a^=Φ+y=arg min⁡{∥a∥2:Φa=y},\hat{\vb{a}} = \Phi\pinv\vb{y} = \argmin\{\norm{\vb{a}}_2 : \Phi\vb{a} = \vb{y}\},

the minimum-norm interpolator, also the ridge limit as λ→0\lambda \to 0 and the point reached by gradient descent initialized at zero (the previous lesson’s implicit regularization). With p→∞p \to \infty, ΦΦ⊤/p\Phi\Phi\T/p converges to the kernel and fit approaches the minimum-norm RKHS interpolator.

Their main experiment used Fourier features ϕ(x;v)=e−1⟨v,x⟩\phi(\vb{x}; \vb{v}) = e^{\sqrt{-1}\inner{\vb{v}}{\vb{x}}} with v∼N(0,Id)\vb{v} \sim \Normal(\vb{0}, \mat{I}_d) on an MNIST subset of n=104n = 10^4 images and 10 classes, with NN from 0 to 6⋅1046\cdot 10^4 features (paper figure 2). Test error first traces the classical U, peaks at N=nN = n and falls afterward; coefficient ∥a^∥\norm{\hat{\vb{a}}} norm peaks at the same point and falls to the right. The same shape appears in a fully connected one-hidden-layer network on n=4⋅103n = 4\cdot 10^3 MNIST images, peaking where parameter count (d+1)H+(H+1)K(d + 1)H + (H + 1)K reaches n⋅Kn\cdot K (figure 4), in random forests and in L2L_2-boosting.

Being a phenomenon rather than a theorem matters: the second descent need not always go below the first minimum, nor must a peak always exist. You will see both shortly.

InteractiveDouble descent live
Fitting 496 models…
Seed 0 with p=40p = 40: prediction versus f∗f^* on test (hollow circles: off scale)
40 (p/n = 1.00)
0.20
Fit
λ = 1e−2
Features
Statuscomputing…
Regression with pp random features on n=40n = 40 points in R8\R^8, calculated in your browser. The target is f∗(x)=z+0.5sin⁡(2z)f^*(\vb{x}) = z + 0.5\sin(2z) with z=β⊤xz = \vb{\beta}\T\vb{x}, labels have noise N(0,σ2)\Normal(0, \sigma^2) and each curve point averages 16 seeds (new data, noise and features). Left, on a log scale: test and training error versus f∗f^* and bias²-variance decomposition. Right: one seed’s predictions against truth. The figure starts at p=n=40p = n = 40: training error has just reached zero (shown at the axis floor from there), the prediction cloud explodes and variance blows up. Lower to p≈20p \approx 20, the classical U minimum, then raise to 4n4n: the cloud returns to the diagonal. Increase noise to see the peak grow; switch to ridge and find λ\lambda that removes it, or request optimal λ\lambda for each pp.

The experiment from scratch

The next cell is the figure’s model in NumPy (different seeds, so figures differ somewhat). Minimum-norm fit comes from singular-value decomposition Φ=USV⊤\Phi = \mat{U}\mat{S}\mat{V}\T: a^=VS−1U⊤y\hat{\vb{a}} = \mat{V}\mat{S}\inv\mat{U}\T\vb{y}, discarding numerically zero singular values, and ridge replaces 1/si1/s_i with si/(si2+λ)s_i/(s_i^2 + \lambda) (ridge shrinkage in the SVD basis). Bias and variance average over S=16S = 16 seeds: variance is sample variance of predictions across seeds, and bias² is the corrected squared distance between mean prediction and f∗f^* (explained below).

[ ]Double descent with Fourier featuresBrowser
import numpy as np

n, d, n_test, S = 40, 8, 200, 16
beta = np.random.default_rng(7).normal(size=d)
beta /= np.linalg.norm(beta)


def f_star(X):
    z = X @ beta
    return z + 0.5 * np.sin(2 * z)


X_test = np.random.default_rng(12345).normal(size=(n_test, d))
f_test = f_star(X_test)


def features(X, W, b, kind):
    Z = X @ W
    p = W.shape[1]
    return np.cos(Z + b) * np.sqrt(2 / p) if kind == 'fourier' else np.maximum(Z, 0) / np.sqrt(p)


def ridge_svd(F, y, lam=0.0):
    """Ridge por SVD; con lam = 0 es el interpolador de mínima norma F⁺y."""
    U, s, Vt = np.linalg.svd(F, full_matrices=False)
    keep = s > 1e-10 * s[0]
    U, s, Vt = U[:, keep], s[keep], Vt[keep]
    k = 1 / s if lam == 0 else s / (s**2 + lam)
    return Vt.T @ (k * (U.T @ y))


def draw(seed, p, sigma, kind):
    r = np.random.default_rng(1000 + seed)
    X = r.normal(size=(n, d))
    y = f_star(X) + sigma * r.normal(size=n)
    W = r.normal(size=(d, p)) / np.sqrt(d)
    b = r.uniform(0, 2 * np.pi, p)
    return features(X, W, b, kind), y, features(X_test, W, b, kind)


def experiment(kind, sigma, p_list, lam=0.0):
    rows = []
    for p in p_list:
        preds, train = [], []
        for s in range(S):
            F, y, Ft = draw(s, p, sigma, kind)
            w = ridge_svd(F, y, lam)
            preds.append(Ft @ w)
            train.append(np.mean((F @ w - y) ** 2))
        P = np.array(preds)
        var = P.var(axis=0, ddof=1).mean()
        bias2 = np.mean((P.mean(axis=0) - f_test) ** 2) - var / S  # quita el Var/S de promediar S semillas
        rows.append((p, np.mean(train), np.mean((P - f_test) ** 2), bias2, var))
    return rows


p_list = [2, 5, 10, 15, 20, 25, 30, 35, 38, 40, 42, 45, 50, 60, 80, 120, 160]
res = experiment('fourier', 0.2, p_list)
print('   p   train     test    sesgo²  varianza')
for p, tr, te, b2, v in res:
    print(f'{p:4d}  {tr:.4f}  {te:9.3f}  {b2:7.3f}  {v:9.3f}')
best = min((r for r in res if r[0] < n), key=lambda r: r[2])
print(f'mínimo clásico: p = {best[0]}, test {best[2]:.3f};  p = 4n: test {res[-1][2]:.3f}')

Read the table top to bottom. Through p=20p = 20 it is the classical U: training error falls, bias² drops from 1.241.24 to 0.120.12 and variance rises slowly; the classical minimum is 0.8110.811 at p=20p = 20. Between p=25p = 25 and p=38p = 38 training error approaches zero and variance shoots up. At p=n=40p = n = 40 training is exactly zero and mean test error exceeds 10410^4. Beyond that everything falls: 1.811.81 at p=50p = 50, 0.6090.609 at p=80p = 80 and 0.3730.373 at p=4n=160p = 4n = 160, less than half the classical minimum. Bias² barely changes in the overparameterized regime (around 0.10.1); variance is what falls.

The mean at p=np = n is enormous because the worst-conditioned seed dominates it: the next section shows that in the Gaussian linear model expected error at p=np = n is literally infinite. This is not an artifact to hide; it is the phenomenon.

The second cell switches to ReLU features and varies noise.

[ ]ReLU and the role of noiseBrowser
for sigma in [0.0, 0.2, 0.5]:
    r = experiment('relu', sigma, [20, 40, 160])
    print(f'ReLU, σ = {sigma}: ' + ',  '.join(f'p = {p}: {te:.3g}' for p, _, te, _, _ in r))

Three observations. First, without label noise (σ=0\sigma = 0) a peak remains (359359 at p=40p = 40): target f∗f^* is not a finite linear combination of random ReLUs, and the part the model cannot represent acts as noise. Second, peak grows with noise: 359359, 447447 and 646646. Third, at σ=0.5\sigma = 0.5 the second descent does not compensate: error at p=160p = 160 (1.141.14) is worse than the classical minimum (1.081.08 at p=20p = 20). A second descent does not guarantee the larger model wins.

Why there is a peak: the smallest singular value collapses

Elementary linear algebra explains the peak, most clearly in the simplest model: linear regression with isotropic Gaussian covariates. Take xi∼iidN(0,Ip)\vb{x}_i \iid \Normal(\vb{0}, \mat{I}_p) (the multivariate Gaussian with identity covariance), yi=xi⊤w+εiy_i = \vb{x}_i\T\vb{w} + \eps_i with independent mean-zero εi\eps_i of variance σ2\sigma^2, and ∥w∥2=r\norm{\vb{w}}_2 = r. Since E[xx⊤]=I\E[\vb{x}\vb{x}\T] = \mat{I}, excess risk of any estimator is

R(w^)=Ex[(x⊤w^−x⊤w)2]=∥w^−w∥22.R(\hat{\vb{w}}) = \E_{\vb{x}}\big[(\vb{x}\T\hat{\vb{w}} - \vb{x}\T\vb{w})^2\big] = \norm{\hat{\vb{w}} - \vb{w}}_2^2 .

Write the SVD X=∑i=1msiuivi⊤\mat{X} = \sum_{i=1}^m s_i\vb{u}_i\vb{v}_i\T with m=min⁡(n,p)m = \min(n, p) and all si>0s_i > 0 (almost surely). The least-squares estimator, or minimum-norm estimator when p>np > n, is in both cases w^=X+y\hat{\vb{w}} = \mat{X}\pinv\vb{y} (the pseudoinverse), and since X+X=Π\mat{X}\pinv\mat{X} = \mat{\Pi} projects orthogonally onto the row space,

w^−w=−(I−Π)w+X+ε,X+ε=∑i=1mui⊤εsi vi.\hat{\vb{w}} - \vb{w} = -(\mat{I} - \mat{\Pi})\vb{w} + \mat{X}\pinv\vb{\eps}, \qquad \mat{X}\pinv\vb{\eps} = \sum_{i=1}^m \frac{\vb{u}_i\T\vb{\eps}}{s_i}\,\vb{v}_i .

The two terms are orthogonal (the second lies in row space, the first in its complement), so

E[∥w^−w∥2∣X]=∥(I−Π)w∥2⏟sesgo+σ2∑i=1m1si2⏟varianza.\E\big[\norm{\hat{\vb{w}} - \vb{w}}^2 \given \mat{X}\big] = \underbrace{\norm{(\mat{I} - \mat{\Pi})\vb{w}}^2}_{\text{sesgo}} + \underbrace{\sigma^2\sum_{i=1}^m \frac{1}{s_i^2}}_{\text{varianza}} .

If p≤np \le n, Π=I\mat{\Pi} = \mat{I} and bias is zero; if p>np > n, the estimator cannot see the component of w\vb{w} orthogonal to the nn rows, which becomes bias. Variance explains the peak: it is σ2\sigma^2 times the sum of inverse squared singular values, and one small sis_i suffices to blow it up. This is pure ill conditioning: noise is divided by smin⁡s_{\min}.

The exact value

With Gaussian design everything is calculable at finite nn.

Proof

Part 1 is the final proof exercise: E[ ⋅∣X]=σ2tr⁡((X⊤X)−1)\E[\,\cdot \given \mat{X}] = \sigma^2\tr((\mat{X}\T\mat{X})\inv) and X⊤X\mat{X}\T\mat{X} follows Wishart distribution Wp(I,n)\mathcal{W}_p(\mat{I}, n), whose inverse has mean I/(n−p−1)\mat{I}/(n - p - 1) when n>p+1n > p + 1.

Part 2. Bias: for every orthogonal matrix Q∈Rp×p\mat{Q} \in \R^{p\times p}, XQ\mat{X}\mat{Q} has the same distribution as X\mat{X} (each isotropic Gaussian row is rotation invariant), and its projector is Q⊤ΠQ\mat{Q}\T\mat{\Pi}\mat{Q}. Thus EΠ=Q⊤(EΠ)Q\E\mat{\Pi} = \mat{Q}\T(\E\mat{\Pi})\mat{Q} for every Q\mat{Q}, forcing EΠ=c I\E\mat{\Pi} = c\,\mat{I}; taking traces gives cp=Etr⁡Π=Erank⁡X=ncp = \E\tr\mat{\Pi} = \E\rank\mat{X} = n. Therefore E∥(I−Π)w∥2=w⊤(I−EΠ)w=r2(1−n/p)\E\norm{(\mat{I} - \mat{\Pi})\vb{w}}^2 = \vb{w}\T(\mat{I} - \E\mat{\Pi})\vb{w} = r^2(1 - n/p). Variance: ∑i1/si2=tr⁡((XX⊤)−1)\sum_i 1/s_i^2 = \tr((\mat{X}\mat{X}\T)\inv), and XX⊤=∑j=1pcjcj⊤\mat{X}\mat{X}\T = \sum_{j=1}^p \vb{c}_j\vb{c}_j\T, with cj∼iidN(0,In)\vb{c}_j \iid \Normal(\vb{0}, \mat{I}_n) columns of X\mat{X}, is Wishart Wn(I,p)\mathcal{W}_n(\mat{I}, p); its inverse has mean In/(p−n−1)\mat{I}_n/(p - n - 1) if p>n+1p > n + 1, yielding σ2n/(p−n−1)\sigma^2 n/(p - n - 1).

Part 3: the inverse of Wishart Wm(I,k)\mathcal{W}_m(\mat{I}, k) has finite mean only if k>m+1k > m + 1; at p=n−1p = n - 1, p=np = n and p=n+1p = n + 1 this condition fails (with m=min⁡(n,p)m = \min(n, p) and k=max⁡(n,p)k = \max(n, p)) and Etr⁡(⋅)−1=∞\E\tr(\cdot)\inv = \infty.

∎

Both formulas diverge as p→np \to n, one from each side, at rate 1/∣p−n∣1/\abs{p - n}. For fixed pp and n→∞n \to \infty, part 1 yields σ2p/n\sigma^2 p/n, the usual parametric rate; the peak is an effect of comparable pp and nn.

The spectrum edge

Why does the smallest singular value approach zero exactly at p=np = n? For matrices with iid mean-zero, variance-one entries and finite fourth moment, with p/n→γ∈(0,1)p/n \to \gamma \in (0, 1), Bai and Yin’s theorem (1993) says smin⁡(X)/n→1−γs_{\min}(\mat{X})/\sqrt{n} \to 1 - \sqrt{\gamma} almost surely and smax⁡(X)/n→1+γs_{\max}(\mat{X})/\sqrt{n} \to 1 + \sqrt{\gamma} (the extreme singular values). Transposing, for γ>1\gamma > 1 the edges are γ∓1\sqrt{\gamma} \mp 1, so in both regimes

smin⁡(X)n→∣1−γ∣,κ(X)=smax⁡smin⁡→1+γ∣1−γ∣.\frac{s_{\min}(\mat{X})}{\sqrt{n}} \to \abs{1 - \sqrt{\gamma}}, \qquad \kappa(\mat{X}) = \frac{s_{\max}}{s_{\min}} \to \frac{1 + \sqrt{\gamma}}{\abs{1 - \sqrt{\gamma}}} .

The lower edge touches zero exactly at γ=1\gamma = 1. For square Gaussian matrices, Edelman (1988) showed smin⁡s_{\min} is order n−1/2n^{-1/2} versus order n\sqrt{n} for the others: a single 1/smin⁡21/s_{\min}^2 term, of order nn, dominates the variance sum.

InteractiveThe collapsing singular value
  • γ/(1 − γ)
  • 1/(γ − 1)
  • sampled matrices
0.500 (p = 100, n = 200)
Statuscomputing…
A matrix X∈R200×p\mat{X} \in \R^{200\times p} with entries N(0,1)\Normal(0, 1) and p=γnp = \gamma n. Left: histogram of its min⁡(n,p)\min(n, p) singular values divided by n\sqrt{n}, with Marchenko-Pastur density transformed to singular values, supported on [∣1−γ∣,1+γ][\abs{1 - \sqrt{\gamma}}, 1 + \sqrt{\gamma}]. Right: ∑i1/si2\sum_i 1/s_i^2, estimator variance with σ=1\sigma = 1, versus γ\gamma: asymptotic curves γ/(1−γ)\gamma/(1 - \gamma) and 1/(γ−1)1/(\gamma - 1) and each sampled matrix’s value. Move γ\gamma toward 1 from both sides: the histogram’s left edge touches zero, condition number shoots up and the readout ‘fraction of sum contributed by smin⁡s_{\min}’ approaches 100%. Request new matrices near γ=1\gamma = 1 to see how unstable the sum is there.

The cell checks both with n=50n = 50: smallest singular value against edge ∣1−γ∣\abs{1 - \sqrt{\gamma}} and sum ∑1/si2\sum 1/s_i^2 against the exact formula.

[ ]Singular values and least-squares varianceBrowser
rng = np.random.default_rng(0)
n0 = 50
print('   p   s_min/√n  borde |1-√γ|   Σ1/s² (media)   fórmula exacta')
for p in [25, 40, 45, 49, 50, 51, 55, 60, 100]:
    smins, sums = [], []
    for _ in range(100):
        s = np.linalg.svd(rng.normal(size=(n0, p)), compute_uv=False)
        smins.append(s.min() / np.sqrt(n0))
        sums.append(np.sum(1 / s**2))
    g = p / n0
    formula = p / (n0 - p - 1) if p <= n0 - 2 else (n0 / (p - n0 - 1) if p >= n0 + 2 else np.inf)
    print(f'{p:4d}  {np.mean(smins):8.4f}  {abs(1 - np.sqrt(g)):10.4f}   {np.mean(sums):12.3f}   {formula:8.3f}')

Away from p=np = n, the mean of 100 matrices matches the exact formula to two or three digits (1.0241.024 versus 1.0421.042 at p=25p = 25; 1.0241.024 versus 1.0201.020 at p=100p = 100). Measured smallest singular value is somewhat above the asymptotic edge (at n=50n = 50 edge fluctuations are order n−2/3n^{-2/3} and non-negligible). At p=49p = 49, 5050 and 5151 expectation is infinite, and what you see is a 100-sample mean of a variable without a mean: at p=50p = 50 it is order 2.6⋅1032.6\cdot 10^3; another seed would give something very different.

Proportional regime: asymptotic minimum-norm risk

Exact formulas rely on Gaussian design. Hastie, Montanari, Rosset and Tibshirani (2022) obtained universal behavior in the proportional regime n,p→∞n, p \to \infty with p/n→γp/n \to \gamma, where the spectrum of X⊤X/n\mat{X}\T\mat{X}/n matters.

The continuous part has mass min⁡(1,1/γ)\min(1, 1/\gamma); the atom at zero captures the p−np - n zero eigenvalues when p>np > n. This is the Marchenko-Pastur law from probability; the previous figure’s density is that of t\sqrt{t} under normalized fγf_\gamma. One integral is key: for γ<1\gamma < 1,

∫t−1 fγ(t) ⁣dt=11−γ.\int t^{-1}\,f_\gamma(t)\dd t = \frac{1}{1 - \gamma} .

This is asymptotic minimum-norm risk, also called ridgeless. Variance follows from the prior integral: for γ<1\gamma < 1, σ2tr⁡((X⊤X)−1)=σ2pn⋅1p∑iti−1→σ2γ/(1−γ)\sigma^2\tr((\mat{X}\T\mat{X})\inv) = \sigma^2\frac{p}{n}\cdot\frac{1}{p}\sum_i t_i^{-1} \to \sigma^2\gamma/(1 - \gamma), where tit_i are eigenvalues of X⊤X/n\mat{X}\T\mat{X}/n. For γ>1\gamma > 1 apply the same to XX⊤/p\mat{X}\mat{X}\T/p, whose ratio is 1/γ1/\gamma: σ2np⋅11−1/γ=σ2/(γ−1)\sigma^2\frac{n}{p}\cdot\frac{1}{1 - 1/\gamma} = \sigma^2/(\gamma - 1). A rigor detail: t↦1/tt \mapsto 1/t is unbounded, so weak convergence of the spectral distribution is insufficient; the smallest eigenvalue must also stay away from zero, exactly what Bai and Yin provide when γ≠1\gamma \neq 1. Bias r2(1−1/γ)r^2(1 - 1/\gamma) is the limit of r2(1−n/p)r^2(1 - n/p). Compare with the exact theorem: for Gaussian design, σ2p/(n−p−1)\sigma^2 p/(n - p - 1) and σ2n/(p−n−1)\sigma^2 n/(p - n - 1) are the finite-nn versions of the two variances.

What the formula says

Write SNR=r2/σ2\text{SNR} = r^2/\sigma^2 and note that the zero estimator w^=0\hat{\vb{w}} = \vb{0} has risk r2r^2. Hastie et al. derive these consequences:

  1. On (0,1)(0, 1) risk grows with γ\gamma and beats zero if and only if γ<SNR/(SNR+1)\gamma < \text{SNR}/(\text{SNR} + 1).
  2. On (1,∞)(1, \infty), if SNR≤1\text{SNR} \le 1, risk falls but always remains worse than zero, approaching it from above.
  3. On (1,∞)(1, \infty), if SNR>1\text{SNR} > 1, risk beats zero if and only if γ>SNR/(SNR−1)\gamma > \text{SNR}/(\text{SNR} - 1), has a local minimum at
γ∗=SNRSNR−1\gamma^* = \frac{\sqrt{\text{SNR}}}{\sqrt{\text{SNR}} - 1}

and approaches zero-estimator risk from below as γ→∞\gamma \to \infty.

Differentiating point 3 takes one line:  ⁣d ⁣dγ[r2(1−1/γ)+σ2/(γ−1)]=r2/γ2−σ2/(γ−1)2\frac{\dd}{\dd\gamma}\big[r^2(1 - 1/\gamma) + \sigma^2/(\gamma - 1)\big] = r^2/\gamma^2 - \sigma^2/(\gamma - 1)^2 vanishes when (γ−1)/γ=σ/r(\gamma - 1)/\gamma = \sigma/r.

Enthusiasm for double descent often misses an observation. In this model the global minimum is at γ→0\gamma \to 0, where risk tends to zero: with fixed w\vb{w}, far more data than parameters is always best. The second descent gives only a local minimum. A global minimum in the overparameterized regime needs additional structure. Hastie et al. add it using a misspecified model (section 5): pp observed features capture only fraction κ\kappa of signal, with the rest acting as extra training noise r2(1−κ)r^2(1 - \kappa) and irreducible test bias r2(1−κ)r^2(1 - \kappa) (Theorem 4). If κ\kappa grows with γ\gamma, for example 1−κ(γ)=(1+γ)−a1 - \kappa(\gamma) = (1 + \gamma)^{-a} (their equation 22), each new feature brings signal, and for small aa and SNR>1\text{SNR} > 1 the global minimum moves to γ>1\gamma > 1. Mei and Montanari (2019) reached the same conclusion for random-feature regression on the sphere without ad hoc misspecification: above a critical signal-to-noise ratio, extremely overparameterized interpolators obtain lowest test error.

InteractiveAsymptotic theory versus finite simulation
  • asymptotic (γ < 1)
  • asymptotic (γ > 1)
  • exact with n = 25
  • simulation with n = 25
  • null risk
5.00
Simulation size nn
Model
1.00
Null risk r2r^2 (predict 0)1.00
Local minimum at γ>1\gamma > 1: γ∗=SNR/(SNR−1)\gamma^* = \sqrt{\text{SNR}}/(\sqrt{\text{SNR}} - 1)1.809, risk 0.694
Global grid minimum γ∈[0.05,20]\gamma \in [0.05, 20]γ = 0.05, risk 0.011
Bien especificado: el mínimo global está siempre en γ→0\gamma \to 0 (más datos por parámetro), con riesgo →0\to 0. El segundo descenso solo da un mínimo local.
Minimum-norm test risk versus γ=p/n\gamma = p/n on a log scale, with r2=1r^2 = 1. Gray: Hastie et al. asymptotic formula; blue: exact Gaussian-design formula at selected nn; magenta joins browser simulations (40 repeats per point at 12 γ\gamma values). Curves cross at 3. The horizontal dashed line is zero-estimator risk r2r^2. Compare n=10n = 10 with n=50n = 50: from which nn does asymptotics describe reality well, and where do they differ? Move SNR above and below 1 to check the three consequences. Then select the misspecified model at SNR 5 and move aa: with a=3a = 3 the global minimum is at γ<1\gamma < 1; lowering aa moves it to γ>1\gamma > 1, and with very small aa no γ\gamma beats zero-estimator risk.

The cell compares n=50n = 50, r2=1r^2 = 1 and σ2=0.25\sigma^2 = 0.25, i.e. SNR=4\text{SNR} = 4.

[ ]Asymptotic theory versus simulationBrowser
def hastie(g, r2, s2):
    return s2 * g / (1 - g) if g < 1 else r2 * (1 - 1 / g) + s2 / (g - 1)


def exact(nn, p, r2, s2):
    return s2 * p / (nn - p - 1) if p < nn else r2 * (1 - nn / p) + s2 * nn / (p - nn - 1)


def simulate(nn, p, r2, s2, reps, rng):
    w = np.zeros(p)
    w[0] = np.sqrt(r2)
    err = []
    for _ in range(reps):
        X = rng.normal(size=(nn, p))
        y = X @ w + np.sqrt(s2) * rng.normal(size=nn)
        wh = np.linalg.solve(X.T @ X, X.T @ y) if p < nn else X.T @ np.linalg.solve(X @ X.T, y)
        err.append(np.sum((wh - w) ** 2))
    return np.mean(err), np.std(err) / np.sqrt(reps)


rng = np.random.default_rng(1)
r2, s2, nn = 1.0, 0.25, 50
print(' gamma   simulación (±ee)   exacta n=50   asintótica')
for g in [0.2, 0.5, 0.8, 1.5, 2, 4, 8]:
    p = int(round(g * nn))
    m, se = simulate(nn, p, r2, s2, 300, rng)
    print(f'{g:5.1f}   {m:7.3f} ± {se:.3f}      {exact(nn, p, r2, s2):7.3f}     {hastie(g, r2, s2):7.3f}')
snr = r2 / s2
gs = np.sqrt(snr) / (np.sqrt(snr) - 1)
print(f'SNR = {snr:.0f}: mínimo local γ* = {gs:.2f}, riesgo {hastie(gs, r2, s2):.3f}; riesgo nulo {r2}')

Simulation and exact formula agree in every row within about one standard error, and asymptotics are already close at n=50n = 50 except near the peak: at γ=0.8\gamma = 0.8 exact gives 1.1111.111 and asymptotic 1.0001.000, because σ2p/(n−p−1)\sigma^2 p/(n - p - 1) with p=40p = 40 and n=50n = 50 still feels −1-1 in the denominator. With SNR=4\text{SNR} = 4 the local minimum is γ∗=2\gamma^* = 2 with risk 0.750.75, below zero-estimator risk 11; but risk at γ=0.2\gamma = 0.2 (0.0620.062) is much lower: as stated, the global minimum is on the left.

Bias and variance in the two descents

In the classical bias-variance decomposition, the peak is variance, as the linear model makes clear: for γ<1\gamma < 1 bias is zero and the whole curve is growing variance; for γ>1\gamma > 1 bias r2(1−1/γ)r^2(1 - 1/\gamma) grows and variance σ2/(γ−1)\sigma^2/(\gamma - 1) falls. The second descent is variance falling faster than bias rises. An immediate consequence: without noise there is no peak. With σ=0\sigma = 0 risk is 0 for γ<1\gamma < 1 and r2(1−1/γ)r^2(1 - 1/\gamma) for γ>1\gamma > 1, a monotone curve. Initial random features had a peak at σ=0\sigma = 0 because the unrepresentable part of f∗f^* acts as noise.

Simulation bias measurement has a trap. With SS seeds, mean prediction fˉ\bar{f} averages SS predictors, and

E[(fˉ(x)−f∗(x))2]=sesgo2(x)+Var⁡(f^(x))S.\E\big[(\bar{f}(\vb{x}) - f^*(\vb{x}))^2\big] = \text{sesgo}^2(\vb{x}) + \frac{\Var(\hat{f}(\vb{x}))}{S} .

Near the threshold variance is so large that Var⁡/S\Var/S dominates and naively calculated “bias” has a spurious peak. The cell and figure therefore subtract sample variance divided by SS. Even corrected, estimated bias is very noisy at p=np = n (subtracting two enormous numbers); elsewhere the table shows bias² falling from 1.241.24 to around 0.10.1 and staying there.

A finer decomposition

Random-feature models have three randomness sources: features (“initialization,” PP), input data (XX) and label noise (ε\eps). Total variance mixes them and total-variance decomposition depends on conditioning order. Adlam and Pennington (2020) propose a symmetric ANOVA-style decomposition: with D=(X,ε)D = (X, \eps),

VP=ExVar⁡(E[y^∣P]),VD=ExVar⁡(E[y^∣D]),VPD=ExVar⁡(y^)−VP−VD,V_P = \E_{\vb{x}}\Var\big(\E[\hat{y} \given P]\big), \quad V_D = \E_{\vb{x}}\Var\big(\E[\hat{y} \given D]\big), \quad V_{PD} = \E_{\vb{x}}\Var(\hat{y}) - V_P - V_D ,

where VPDV_{PD} is variance explained only jointly by features and data. In asymptotic random-feature regression they calculate terms and find bias decreases monotonically with width; variance terms are nonmonotone and can diverge at the threshold even without label noise; divergence comes from sampling-initialization interaction; and it therefore disappears when averaging samples (bagging) or features (ensembles). Label noise exacerbates but does not cause the peak.

The cell estimates these three terms with a two-factor design: 8 feature draws crossed with 8 data draws, 64 fits per pp, and unbiased two-factor ANOVA estimators with one observation per cell.

[ ]Fine variance decompositionBrowser
def fine_grained(p, kind='fourier', sigma=0.2, K=8):
    """Y[i, j] = predicción en test con las características i y los datos (X, ε) j."""
    feats = []
    for i in range(K):
        r = np.random.default_rng(50 + i)
        feats.append((r.normal(size=(d, p)) / np.sqrt(d), r.uniform(0, 2 * np.pi, p)))
    data = []
    for j in range(K):
        r = np.random.default_rng(900 + j)
        X = r.normal(size=(n, d))
        data.append((X, f_star(X) + sigma * r.normal(size=n)))
    Y = np.empty((K, K, n_test))
    for i, (W, b) in enumerate(feats):
        Ft = features(X_test, W, b, kind)
        for j, (X, y) in enumerate(data):
            Y[i, j] = Ft @ ridge_svd(features(X, W, b, kind), y)
    mu = Y.mean(axis=(0, 1))
    rows, cols = Y.mean(axis=1), Y.mean(axis=0)
    resid = Y - rows[:, None] - cols[None, :] + mu
    V_PD = (resid**2).sum(axis=(0, 1)).mean() / (K - 1) ** 2    # interacción características × datos
    V_P = rows.var(axis=0, ddof=1).mean() - V_PD / K            # varianza de E[ŷ | características]
    V_D = cols.var(axis=0, ddof=1).mean() - V_PD / K            # varianza de E[ŷ | datos]
    bias2 = np.mean((mu - f_test) ** 2) - (V_P + V_D) / K - V_PD / K**2
    return bias2, V_P, V_D, V_PD


print('   p   sesgo²    V_P      V_D     V_PD (interacción)')
for p in [20, 36, 44, 160]:
    b2, vp, vd, vpd = fine_grained(p)
    print(f'{p:4d}  {b2:7.3f}  {vp:7.3f}  {vd:7.3f}  {vpd:10.3f}')

Results match Adlam and Pennington. On either side of the peak (p=36p = 36 and p=44p = 44), interaction VPDV_{PD} is 2.512.51 and 3.953.95, while VPV_P and VDV_D stay below 0.230.23: nearly all peak variance is interaction. Away from the threshold interaction is comparable to other terms (0.110.11 at p=160p = 160). We omit p=40p = 40: tails there are so heavy that 64 fits estimate nothing reliably (unbiased estimators can even give negative variance). Practical implication: averaging predictions over many feature draws, which in the limit leaves only variance VDV_D and removes VPV_P and VPDV_{PD}, attacks the peak at its source; model averaging reduces variance where it is greatest.

Optimal regularization: the peak disappears

If the peak is variance from small singular values, the classical remedy is ridge: w^λ=(X⊤X+λI)−1X⊤y\hat{\vb{w}}_\lambda = (\mat{X}\T\mat{X} + \lambda\mat{I})\inv\mat{X}\T\vb{y} replaces 1/si1/s_i with si/(si2+λ)s_i/(s_i^2 + \lambda), bounded by 1/(2λ)1/(2\sqrt{\lambda}). Nakkiran, Venkat, Kakade and Ma (2020) turn this into a theorem.

Let μ1,…,μp\mu_1, \dots, \mu_p be eigenvalues of X⊤X\mat{X}\T\mat{X} (including zeros if p>np > n) and X⊤X=Vdiag⁡(μi)V⊤\mat{X}\T\mat{X} = \mat{V}\diag(\mu_i)\mat{V}\T. Error is w^λ−w=−λ(X⊤X+λI)−1w+(X⊤X+λI)−1X⊤ε\hat{\vb{w}}_\lambda - \vb{w} = -\lambda(\mat{X}\T\mat{X} + \lambda\mat{I})\inv\vb{w} + (\mat{X}\T\mat{X} + \lambda\mat{I})\inv\mat{X}\T\vb{\eps}, and with isotropic Gaussian X\mat{X} matrix V\mat{V} is uniform over rotations and independent of μi\mu_i, giving E(vi⊤w)2=r2/p\E(\vb{v}_i\T\vb{w})^2 = r^2/p. Averaging (paper Lemma 1),

R(λ)=E∑i=1pλ2r2/p+σ2μi(μi+λ)2.R(\lambda) = \E\sum_{i=1}^p \frac{\lambda^2 r^2/p + \sigma^2\mu_i}{(\mu_i + \lambda)^2} .

Each term is a function of λ\lambda with derivative 2μi(λr2/p−σ2)/(μi+λ)32\mu_i(\lambda r^2/p - \sigma^2)/(\mu_i + \lambda)^3: all are minimized at the same point,

λ∗=p σ2r2,R(λ∗)=E∑i=1pσ2μi+λ∗,\lambda^* = \frac{p\,\sigma^2}{r^2}, \qquad R(\lambda^*) = \E\sum_{i=1}^p \frac{\sigma^2}{\mu_i + \lambda^*},

which does not depend on nn (Lemma 2). It is the Bayesian estimator with prior w∼N(0,(r2/p)I)\vb{w} \sim \Normal(\vb{0}, (r^2/p)\mat{I}), hence optimal for all eigenvalues at once.

Proof

Couple samples: Xn+1\mat{X}_{n+1} is Xn\mat{X}_n with an extra row x\vb{x}. Then Xn+1⊤Xn+1=Xn⊤Xn+xx⊤\mat{X}_{n+1}\T\mat{X}_{n+1} = \mat{X}_n\T\mat{X}_n + \vb{x}\vb{x}\T, and since xx⊤\vb{x}\vb{x}\T is positive semidefinite, Weyl’s theorem (or Courant-Fischer) gives μi(n+1)≥μi(n)\mu_i^{(n+1)} \ge \mu_i^{(n)} for each ii with sorted eigenvalues. Each term σ2/(μi+λ∗)\sigma^2/(\mu_i + \lambda^*) decreases in μi\mu_i and λ∗\lambda^* does not change with nn, so the sum and its expectation cannot increase.

∎

The proof shows why the unregularized estimator lacks this property: at λ=0\lambda = 0 terms are σ2/μi\sigma^2/\mu_i over nonzero eigenvalues, and going from n=p−1n = p - 1 to n=pn = p introduces a new positive but tiny eigenvalue, adding a huge term. More data can worsen the model: sample-wise nonmonotonicity is the same phenomenon. An interpolator’s learning curve, error versus nn, need not be monotone, and a validation-curve maximum need not mark the end of improvement when the model can interpolate.

InteractiveWhen more data hurt
  • minimum norm (λ → 0), exact
  • ridge, chosen λ (Marchenko-Pastur)
  • ridge, optimal λ* (Marchenko-Pastur)
  • n = p
80
100
0.25
λ = 1.000
Minimum norm (exact)1.253
Ridge with chosen λ\lambda0.900
Ridge with λ∗=pσ2/r2\lambda^* = p\sigma^2/r^20.476 (λ* = 25.0)
More data, worse model: with n=49n = 49 the interpolator had risk 0.755; with n=80n = 80, 1.253.
Isotropic linear model with fixed pp and r2=1r^2 = 1: risk versus sample count nn. Red: minimum-norm interpolator (exact formula); blue: ridge at your chosen λ\lambda; dashed aqua: ridge at λ∗=pσ2/r2\lambda^* = p\sigma^2/r^2. Both ridge curves replace eigenvalues of X⊤X\mat{X}\T\mat{X} with the Marchenko-Pastur law, a high-dimensional approximation. Move nn through pp: minimum norm has a hump at n≈pn \approx p, and the notice says how many fewer samples produced a better model. Set σ2=0\sigma^2 = 0: the hump disappears. Increase λ\lambda: it flattens, and at λ∗\lambda^* the curve is monotone. Change pp and watch the hump move.

The cell calculates R(λ)R(\lambda) by averaging the lemma’s formula over actual Gaussian matrices, with p=50p = 50, r2=1r^2 = 1 and σ2=0.25\sigma^2 = 0.25, and checks the lemma against an actual ridge fit.

[ ]Optimal ridge and monotonicity in nBrowser
def ridge_risk_mc(nn, p, r2, s2, lam, reps, rng):
    """E‖ŵ_λ − w‖² con la fórmula espectral del lema 1, promediada sobre matrices X gaussianas."""
    out = []
    for _ in range(reps):
        mu = np.linalg.svd(rng.normal(size=(nn, p)), compute_uv=False) ** 2
        mu = np.concatenate([mu, np.zeros(max(p - nn, 0))])        # los p autovalores de XᵀX
        out.append(np.sum((lam**2 * r2 / p + s2 * mu) / (mu + lam) ** 2))
    return np.mean(out)


rng = np.random.default_rng(3)
p, r2, s2 = 50, 1.0, 0.25
lam_star = p * s2 / r2
print(f'λ* = pσ²/r² = {lam_star}')
print('   n   mínima norma (exacta)   ridge λ = 1   ridge λ*')
for nn in [10, 25, 40, 48, 52, 60, 75, 100, 150]:
    if nn > p + 1:
        mn_ = s2 * p / (nn - p - 1)
    elif nn < p - 1:
        mn_ = r2 * (1 - nn / p) + s2 * nn / (p - nn - 1)
    else:
        mn_ = np.inf
    print(f'{nn:4d}   {mn_:12.3f}          {ridge_risk_mc(nn, p, r2, s2, 1.0, 40, rng):9.3f}   {ridge_risk_mc(nn, p, r2, s2, lam_star, 40, rng):8.3f}')

# comprobación directa: ridge de verdad con X, w y ruido nuevos en cada repetición (n = 40)
errs = []
for _ in range(300):
    X = rng.normal(size=(40, p))
    w = rng.normal(size=p)
    w *= np.sqrt(r2) / np.linalg.norm(w)
    wh = np.linalg.solve(X.T @ X + lam_star * np.eye(p), X.T @ (X @ w + np.sqrt(s2) * rng.normal(size=40)))
    errs.append(np.sum((wh - w) ** 2))
print(f'n = 40, ridge λ* simulado: {np.mean(errs):.3f} ± {np.std(errs) / np.sqrt(300):.3f}')

The minimum-norm column rises from 0.7600.760 at n=25n = 25 to 12.012.0 at n=48n = 48 and 12.512.5 at n=52n = 52: doubling data multiplied error by 16. With λ=1\lambda = 1 (little regularization for this problem) the hump remains, flattened: 0.7230.723, 0.7730.773, 0.8460.846. With λ∗=12.5\lambda^* = 12.5 the column falls continuously from 0.8470.847 at n=10n = 10 to 0.1070.107 at n=150n = 150. Direct fit with n=40n = 40 gives 0.479±0.0060.479 \pm 0.006, agreeing with the lemma’s 0.4770.477.

In the random-features model

The theorem does not apply literally to random features, but its idea does, and in practice λ\lambda is chosen using validation rather than test data. The cell holds out 20 extra validation examples, selects λ\lambda among 15 values with them and measures test error.

[ ]Ridge with λ chosen by validationBrowser
lams = np.logspace(-6, 1, 15)


def ridge_validated(kind, sigma, p_list, n_val=20):
    out = []
    for p in p_list:
        errs = []
        for s in range(S):
            r = np.random.default_rng(1000 + s)
            X = r.normal(size=(n + n_val, d))
            y = f_star(X) + sigma * r.normal(size=n + n_val)
            W = r.normal(size=(d, p)) / np.sqrt(d)
            b = r.uniform(0, 2 * np.pi, p)
            F = features(X, W, b, kind)
            Ftr, Fva, ytr, yva = F[:n], F[n:], y[:n], y[n:]
            U, sv, Vt = np.linalg.svd(Ftr, full_matrices=False)
            uy = U.T @ ytr
            ws = [Vt.T @ (sv / (sv**2 + lam) * uy) for lam in lams]
            best = min(ws, key=lambda w: np.mean((Fva @ w - yva) ** 2))
            errs.append(np.mean((features(X_test, W, b, kind) @ best - f_test) ** 2))
        out.append((p, np.mean(errs)))
    return out


pv = [10, 20, 30, 38, 40, 42, 50, 80, 160]
mn = {p: te for p, _, te, _, _ in experiment('fourier', 0.2, pv)}
for p, e in ridge_validated('fourier', 0.2, pv):
    print(f'p = {p:3d}   mínima norma {mn[p]:9.3f}   ridge validado {e:.3f}')

With validated λ\lambda, error falls monotonically across the grid: 0.5670.567 at p=20p = 20, 0.4240.424 at p=40p = 40 (where minimum norm exceeded 10410^4) and 0.2590.259 at p=160p = 160. At each pp validated ridge also improves on minimum norm, including p=4np = 4n (0.2590.259 versus 0.3730.373): interpolation is not optimal here even though the interpolator generalizes reasonably. Validated ridge uses 20 more labeled examples; the fair comparison is with minimum norm’s classical minimum, which it also comfortably beats.

The 2020 paper extends the result in two directions. Model size: with isotropic covariates in a high-dimensional ambient space and a model using an dd-size projection, optimally tuned ridge λ\lambda has risk monotone in dd (Theorem 3). Empirically, random ReLU features on Fashion-MNIST and five-layer CNNs on CIFAR-100 in the next section show double descent unregularized or weakly regularized, while optimally regularized models are “largely monotone,” with optimal λ\lambda changing with size. It also marks limits: a non-Gaussian, heteroscedastic-noise counterexample makes optimal ridge nonmonotone in nn, and for nonisotropic Gaussian covariates monotonicity with standard ridge remains a conjecture.

Deep double descent

Nakkiran, Kaplun, Bansal, Yang, Barak and Sutskever (2019) showed the phenomenon in real deep networks in three variants.

Model-wise. Families of ResNet18 with four stage widths [k,2k,4k,8k][k, 2k, 4k, 8k] (k=64k = 64 is standard ResNet18) and five-layer CNNs: four Conv-BatchNorm-ReLU-MaxPool blocks of widths [k,2k,4k,8k][k, 2k, 4k, 8k] with max pooling [1,2,2,8][1, 2, 2, 8] and a final linear layer (at k=64k = 64 it has 1 558 0261\,558\,026 parameters). In paper figure 1, ResNet18 on CIFAR-10 with 15% noisy labels, trained with Adam at rate 10−410^{-4} for 4000 epochs, has test error versus kk rising near zero training error then falling again. “Label noise pp” means each example retains its label with probability 1−p1 - p and otherwise gets a uniformly sampled wrong label, drawn once. Noise emphasizes the peak; more data moves the threshold right (the model needs more capacity to interpolate); and peaks occur without added noise, for example CNN on CIFAR-100.

Epoch-wise. With a fixed large model, test error versus training time falls, rises and falls again (figures 9 and 10, ResNet18 on CIFAR-10 with 20% noise). Small models that never interpolate improve monotonically; medium ones that barely interpolate at the end trace a U where early stopping helps; large ones pass the threshold mid-training and leave it. With 10% noise, final error can be lower than the first minimum.

Sample-wise. In IWSLT’14 German-English translation with Transformers, multiplying training data by 4.5 (4000 to 18,000 sentences) worsens the model over a size range (figure 3): more data shift the threshold right and a formerly comfortably overparameterized model enters the critical regime. For CNNs on CIFAR-10 there is a width range where quadrupling data does not improve error (figure 11a).

To unify them they define a complexity measure depending on the full procedure, not architecture alone.

The informal generalized double-descent hypothesis (Hypothesis 1) says: if EMC≪n\text{EMC} \ll n, any change increasing effective complexity reduces test error; if EMC≫n\text{EMC} \gg n, likewise; if EMC≈n\text{EMC} \approx n, it may increase or decrease it. The three variants move through the same critical regime differently: enlarging the model or training longer increases EMC; adding data increases nn. Deep double descent comprises these three phenomena in networks trained with SGD or Adam, explained by EMC relative to nn. The appendix adds a fourth axis: for ResNet18 on CIFAR-10 (20% noise, SGD) and weight decay from 0 to 0.1, error versus regularization traces the same shape because greater decay means lower EMC.

Two qualifications from the paper prevent misunderstanding. First, its appendix E.2.3 title is literal: optimally chosen early stopping has no double descent, and with it more samples always help in their translation experiments. Second, epoch-wise double descent is not simply “late overfitting” fixed by stopping early: stopping at the first minimum can leave a model worse than the final trained model.

Lab: deep double descent on your GPU

The lab reproduces a reduced protocol: five-layer CNN with variable width kk, CIFAR-10 subset with 20% noisy labels, no augmentation, Adam at rate 10−410^{-4} and batches of 128 as in the paper, but fewer data and epochs to fit an 8 GB GPU. It records training error against noisy labels and test error against clean labels at logarithmically spaced epochs, test error at the epoch selected by early stopping on noisy validation, and repeats selected widths with decoupled weight decay (AdamW). Data come from the pinned Hugging Face CIFAR-10 copy (uoft-cs/cifar10), downloaded once and cached.

The full configuration (n=10 000n = 10\,000, 16 widths, 1000 epochs) is for you to run; ORYON_VERIFY_SHORT=1 runs a short end-to-end flow check. Due to duration the cell is excluded from automatic checks.

[ ]Deep double descent with a five-layer CNNLocal GPU
"""Double descent profundo: protocolo reducido de Nakkiran et al. (2019) para una GPU de 8 GB.

CNN de cinco capas [k, 2k, 4k, 8k] (Conv-BN-ReLU-MaxPool con pools [1, 2, 2, 8] y una lineal final),
subconjunto de CIFAR-10 con un 20 % de etiquetas ruidosas (una etiqueta incorrecta uniforme, sorteada una vez),
sin aumento de datos, Adam con lr = 1e-4 y lotes de 128. Se registran, para cada anchura k y a lo largo de las
épocas, el error de entrenamiento (respecto a las etiquetas ruidosas) y el error de test (respecto a las limpias).
Variantes: parada temprana con un conjunto de validación ruidoso y decaimiento de pesos.

ORYON_VERIFY_SHORT=1 ejecuta una versión corta (menos datos, anchuras y épocas) que comprueba el flujo.
"""
import json
import math
import os
import time
from pathlib import Path

import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
import io as _io
import pyarrow.parquet as pq
from huggingface_hub import hf_hub_download
from PIL import Image

SHORT = os.environ.get('ORYON_VERIFY_SHORT') == '1'
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.backends.cudnn.benchmark = True

if SHORT:
    N_TRAIN, N_VAL, N_TEST = 4000, 1000, 5000
    WIDTHS = [2, 3, 4, 5, 6, 8, 10, 12, 16, 24, 32]
    EPOCHS = 150
    WD_WIDTHS = [4, 6, 8, 12]
else:
    N_TRAIN, N_VAL, N_TEST = 10000, 2000, 10000
    WIDTHS = [1, 2, 3, 4, 5, 6, 8, 10, 12, 16, 20, 24, 32, 40, 48, 64]
    EPOCHS = 1000
    WD_WIDTHS = [4, 6, 8, 10, 12, 16, 24, 32, 64]
NOISE, LR, BATCH, WD = 0.2, 1e-4, 128, 1.0   # WD: decaimiento desacoplado de AdamW
LOG_EPOCHS = sorted({int(round(x)) for x in np.geomspace(1, EPOCHS, 40)})
OUT = Path(os.environ.get('ORYON_DD_OUTPUT', 'deep-double-descent.json'))

# ---------------------------------------------------------------- datos
def load_cifar(split, rows):
    """CIFAR-10 desde la caché de Hugging Face (uoft-cs/cifar10): solo se decodifican las filas pedidas."""
    path = hf_hub_download('uoft-cs/cifar10', f'plain_text/{split}-00000-of-00001.parquet', repo_type='dataset',
                           revision='0b2714987fa478483af9968de7c934580d0bb9a2')  # versión fijada
    t = pq.read_table(path)
    imgs = t.column('img').take(rows).to_pylist()
    X = np.stack([np.array(Image.open(_io.BytesIO(d['bytes'])).convert('RGB')) for d in imgs])
    return torch.tensor(X).permute(0, 3, 1, 2).float() / 255, torch.tensor(t.column('label').take(rows).to_numpy())


gen = np.random.default_rng(0)
idx = gen.permutation(50000)[: N_TRAIN + N_VAL]
X, y_clean = load_cifar('train', idx)
mean, std = X[:N_TRAIN].mean((0, 2, 3), keepdim=True), X[:N_TRAIN].std((0, 2, 3), keepdim=True)
X = (X - mean) / std
# ruido de etiquetas: con probabilidad NOISE, una etiqueta incorrecta uniforme (fija para todo el entrenamiento)
flip = torch.tensor(gen.random(len(idx)) < NOISE)
shift = torch.tensor(gen.integers(1, 10, len(idx)))
y_noisy = torch.where(flip, (y_clean + shift) % 10, y_clean)
Xtr, ytr = X[:N_TRAIN].to(device), y_noisy[:N_TRAIN].to(device)
Xva, yva = X[N_TRAIN:].to(device), y_noisy[N_TRAIN:].to(device)
tidx = gen.permutation(10000)[:N_TEST]
Xte_raw, yte = load_cifar('test', tidx)
Xte, yte = ((Xte_raw - mean) / std).to(device), yte.to(device)
print(f'n = {N_TRAIN}, etiquetas cambiadas: {flip[:N_TRAIN].float().mean():.3f}, test limpio: {N_TEST}')


# ---------------------------------------------------------------- modelo
def make_cnn(k: int) -> nn.Module:
    layers, c_in = [], 3
    for c_out, pool in zip([k, 2 * k, 4 * k, 8 * k], [1, 2, 2, 8]):
        layers += [nn.Conv2d(c_in, c_out, 3, padding=1), nn.BatchNorm2d(c_out), nn.ReLU()]
        if pool > 1:
            layers.append(nn.MaxPool2d(pool))
        c_in = c_out
    return nn.Sequential(*layers, nn.Flatten(), nn.Linear(8 * k, 10))


print('parámetros con k = 64:', sum(p.numel() for p in make_cnn(64).parameters()))


@torch.no_grad()
def error(model, Xs, ys):
    model.eval()
    wrong = 0
    for i in range(0, len(Xs), 1000):
        with torch.autocast('cuda', dtype=torch.bfloat16, enabled=device.type == 'cuda'):
            wrong += (model(Xs[i:i + 1000]).argmax(1) != ys[i:i + 1000]).sum().item()
    model.train()
    return wrong / len(Xs)


def train(k: int, wd: float = 0.0, seed: int = 0):
    torch.manual_seed(seed)
    model = make_cnn(k).to(device).to(memory_format=torch.channels_last)
    opt = torch.optim.AdamW(model.parameters(), lr=LR, weight_decay=wd) if wd > 0 else torch.optim.Adam(model.parameters(), lr=LR)
    g = torch.Generator(device=device).manual_seed(seed)
    hist = []
    for ep in range(1, EPOCHS + 1):
        perm = torch.randperm(N_TRAIN, device=device, generator=g)
        for i in range(0, N_TRAIN, BATCH):
            b = perm[i:i + BATCH]
            with torch.autocast('cuda', dtype=torch.bfloat16, enabled=device.type == 'cuda'):
                loss = F.cross_entropy(model(Xtr[b]), ytr[b])
            opt.zero_grad(set_to_none=True)
            loss.backward()
            opt.step()
        if ep in LOG_EPOCHS:
            hist.append({'epoch': ep, 'train': error(model, Xtr, ytr), 'val': error(model, Xva, yva), 'test': error(model, Xte, yte)})
    del model, opt
    if device.type == 'cuda':
        torch.cuda.empty_cache()
    return hist


results = {'config': {'n_train': N_TRAIN, 'n_val': N_VAL, 'n_test': N_TEST, 'noise': NOISE, 'lr': LR,
                      'batch': BATCH, 'epochs': EPOCHS, 'wd': WD, 'short': SHORT}, 'runs': []}
t0 = time.time()
for k in WIDTHS:
    h = train(k)
    params = sum(p.numel() for p in make_cnn(k).parameters())
    best = min(h, key=lambda r: r['val'])
    results['runs'].append({'k': k, 'wd': 0.0, 'params': params, 'history': h})
    print(f"k={k:3d} params={params:8d}  final: train {h[-1]['train']:.3f} test {h[-1]['test']:.3f}"
          f"  | parada temprana (época {best['epoch']}): test {best['test']:.3f}  [{time.time() - t0:.0f} s]")
for k in WD_WIDTHS:
    h = train(k, wd=WD)
    results['runs'].append({'k': k, 'wd': WD, 'params': None, 'history': h})
    print(f"k={k:3d} wd={WD}  final: train {h[-1]['train']:.3f} test {h[-1]['test']:.3f}  [{time.time() - t0:.0f} s]")
OUT.write_text(json.dumps(results), encoding='utf-8')
print('guardado en', OUT)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Before launching, check architecture: at k=64k = 64 the code prints 1 558 0261\,558\,026 parameters, exactly the paper’s figure. The interactive shows the short verification run (n=4000n = 4000, 150 epochs, one seed, 5000 clean test images). It is small and should be read as such.

InteractiveThe lab’s short run
  • test (final)
  • training, noisy labels (final)
  • test with early stopping
  • test
  • training
8 · 25.418 params.
Final test error58.5 %
Final training error8.1 %
Early stopping: epoch and test error47, 56.0 %
With AdamW: final test error54.1 %
Short verification run: n=4000n = 4000, 150 epochs and one seed, with a test set of 5000 images (standard error of about 0.7 points). The first width that interpolates is k=12k = 12.
Actual output from the preceding cell with ORYON_VERIFY_SHORT=1: five-layer CNN on 4000 CIFAR-10 images with 20% noisy labels, Adam at rate 10−410^{-4}, 150 epochs and one seed. Left versus width kk: final training error against noisy labels, test error against clean labels, and test error at the early-stopping epoch. Right: selected width’s epoch dynamics. Explore widths 8 to 12 where training error reaches zero: test error falls, rises and does not fall again within 150 epochs. Compare with k=32k = 32. Enable AdamW repeats and see where weight decay helps most.

The results, with numbers. Model-wise, final test error falls from 66.7 %66.7\,\% at k=2k = 2 to 58.6 %58.6\,\% at k=5k = 5, is nearly flat between k=5k = 5 and k=12k = 12 (58.658.6, 59.659.6, 58.558.5, 57.357.3 and 57.7 %57.7\,\%) while training error falls from 35 %35\,\% to 0.4 %0.4\,\%, then clearly falls again beyond the threshold: 53.7 %53.7\,\% at k=16k = 16, 52.2 %52.2\,\% at k=24k = 24 and 48.5 %48.5\,\% at k=32k = 32. There is no sharp peak: one-point increases at k=6k = 6 and k=12k = 12 are within one-seed standard error (about 0.7 points). The hypothesis pattern does appear: while EMC is below nn, extra capacity barely helps because it is spent memorizing roughly 790 changed labels; once comfortably above, it helps again. Epoch-wise, critical widths show a U: at k=8k = 8 test is minimal at epoch 61 (55.8 %55.8\,\%) and worsens to 58.5 %58.5\,\% at the end, when training error reaches 8 %8\,\%; wide models barely move after interpolation (k=32k = 32 ends at 48.5 %48.5\,\%, minimum 47.7 %47.7\,\%). Thus early stopping with noisy validation gains 2.5 points at k=8k = 8 (56.056.0 versus 58.5 %58.5\,\%) and almost nothing at k=24k = 24 and k=32k = 32. Weight decay (AdamW with decoupled coefficient 1.0, repeated at four widths) helps where the problem lies: 58.358.3 versus 62.3 %62.3\,\% at k=4k = 4, 57.057.0 versus 59.6 %59.6\,\% at k=6k = 6, 54.154.1 versus 58.5 %58.5\,\% at k=8k = 8 and 55.755.7 versus 57.7 %57.7\,\% at k=12k = 12.

Why does the paper’s peak not appear? The short run cuts precisely what produces it. In Nakkiran et al. each model trains 4000 epochs, so all reach their final state and critical models barely end up interpolating noise; with 150 epochs threshold widths are still midway (k=6k = 6 has final training error 23 %23\,\%), and threshold movement with training time is epoch-wise double descent. One seed and 4000 images add noise. The full lab configuration trains 1000 epochs on n=10 000n = 10\,000 with 16 widths; according to the paper, training to completion with 20% noise gives a test-error maximum near the interpolating width (figure 12 shows this ridge for five-layer CNNs on CIFAR-10 with 20% noise over the model-size and sample-count plane). Run it and repeat with another seed before interpreting one-point differences.

How many parameters does a model have?

Everything above places parameter count on the horizontal axis. Curth, Jeffares and van der Schaar (2023) argue that axis creates the apparent mystery. Reanalyzing Belkin et al., they show that in all three nonparametric cases (trees, boosting and Fourier-feature regression) the axis combines two distinct mechanisms applied sequentially:

  • For trees, first increase maximum leaf count PleafP^{\text{leaf}} of one tree; once it cannot grow further, increase ensemble tree count PensP^{\text{ens}}. Separately, error is U-shaped (or L-shaped) in PleafP^{\text{leaf}} and L-shaped in PensP^{\text{ens}}; double descent appears only when curves are joined.
  • For boosting, first boosting rounds and then ensemble size, with the same conclusion.
  • In random-feature regression the second mechanism is hidden. Their Proposition 1: with p>np > n, the minimum-norm interpolator is equivalent to building a basis of nn vectors from right singular vectors of Φ\Phi without using labels, then fitting ordinary least squares in that basis. Beyond p=np = n the model still fits nn coefficients; increasing pp improves the basis without supervision. They separate axes with principal-component regression: number PPCP^{\text{PC}} of components used gives a classical U, and number PexP^{\text{ex}} of remaining features gives a decreasing curve.

To measure complexity without parameter counting, they use that all these methods are smoothers: prediction is f^(x0)=s^(x0)⊤y\hat{f}(\vb{x}_0) = \hat{\vb{s}}(\vb{x}_0)\T\vb{y}, with weights s^(x0)∈Rn\hat{\vb{s}}(\vb{x}_0) \in \R^n on training labels (for ridge, s^(x0)⊤=ϕ(x0)⊤(Φ⊤Φ+λI)−1Φ⊤\hat{\vb{s}}(\vb{x}_0)\T = \vb{\phi}(\vb{x}_0)\T(\Phi\T\Phi + \lambda\mat{I})\inv\Phi\T). If noise is homoscedastic, Var⁡f^(x0)=σ2∥s^(x0)∥2\Var\hat{f}(\vb{x}_0) = \sigma^2\norm{\hat{\vb{s}}(\vb{x}_0)}^2, leading to their effective parameter count on an input set I0I_0:

p^s^0=n∣I0∣∑j∈I0∥s^(xj0)∥2.\hat{p}^0_{\hat{\vb{s}}} = \frac{n}{\abs{I_0}}\sum_{j \in I_0}\norm{\hat{\vb{s}}(\vb{x}_j^0)}^2 .

On training inputs this is the classical variance degrees-of-freedom measure ∑ihi2\sum_i h_i^2 in terms of smoother eigenvalues hih_i, exactly pp for least squares with p<np < n and related to ridge effective dimension ∑iμi/(μi+λ)\sum_i \mu_i/(\mu_i + \lambda). But with p≥np \ge n and λ=0\lambda = 0 it stays nn forever, since each training point predicts its own label. The key is measuring on new inputs: p^test\hat{p}^{\text{test}}. They find effective test complexity never increases beyond the threshold, although raw parameter count does. The second descent is decreasing complexity, and plotting error against p^test\hat{p}^{\text{test}} recovers classical shapes.

In the isotropic linear model one calculation shows this: s^(x0)⊤=x0⊤X+\hat{\vb{s}}(\vb{x}_0)\T = \vb{x}_0\T\mat{X}\pinv and Ex0∥s^(x0)∥2=tr⁡(X+X+⊤)=∑i1/si2\E_{\vb{x}_0}\norm{\hat{\vb{s}}(\vb{x}_0)}^2 = \tr(\mat{X}\pinv\mat{X}\pinv{}\T) = \sum_i 1/s_i^2. That is, p^test=n∑i1/si2\hat{p}^{\text{test}} = n\sum_i 1/s_i^2, and estimator variance is exactly σ2p^test/n\sigma^2\hat{p}^{\text{test}}/n. The variance peak is an effective-parameter peak, and its subsequent decline causes the second descent.

InteractiveHow many parameters does the model really use?
100
λ = 1e−2
Statuscomputing…
The first figure’s experiment (Fourier, σ=0.2\sigma = 0.2), viewed as a smoother. Left: Curth et al. effective parameters measured on training and test versus raw pp on log-log axes. Right: test error versus p^test\hat{p}^{\text{test}}, separating p≤np \le n branch (orange) from p≥np \ge n branch (purple, traversed leftward as pp grows). Move pp above 40: raw count rises, training p^\hat{p} stays fixed at nn and test p^\hat{p} falls. On the right, p≤np \le n draws the classical U and p≥np \ge n rises with p^test\hat{p}^{\text{test}}: on the right of both, greater effective complexity means greater error. Enable ridge and raise λ\lambda: the effective-complexity peak and error peak flatten together.
[ ]Effective training and test parametersBrowser
def effective_params(kind, sigma, p_list, lam=0.0):
    rows = []
    for p in p_list:
        pt, ptr, te = [], [], []
        for s in range(S):
            F, y, Ft = draw(s, p, sigma, kind)
            U, sv, Vt = np.linalg.svd(F, full_matrices=False)
            keep = sv > 1e-10 * sv[0]
            U, sv, Vt = U[:, keep], sv[keep], Vt[keep]
            k = 1 / sv if lam == 0 else sv / (sv**2 + lam)
            Smat = (Ft @ Vt.T) * k @ U.T      # fila j: pesos ŝ(x_j) del suavizador en el punto de test j
            h = sv * k                         # autovalores del suavizador en entrenamiento
            pt.append(n * np.mean(np.sum(Smat**2, axis=1)))
            ptr.append(np.sum(h**2))
            te.append(np.mean((Smat @ y - f_test) ** 2))
        rows.append((p, np.mean(ptr), np.mean(pt), np.mean(te)))
    return rows


print('   p   p̂ train    p̂ test      test')
for p, a, b_, c in effective_params('fourier', 0.2, [5, 10, 20, 30, 36, 40, 44, 50, 80, 160]):
    print(f'{p:4d}  {a:7.1f}  {b_:10.1f}  {c:9.3f}')

p^train\hat{p}^{\text{train}} is 5,10,20,…5, 10, 20, \dots through 4040 and remains 4040. p^test\hat{p}^{\text{test}} rises from 5.85.8 at p=5p = 5 to 49.749.7 at p=20p = 20, 801801 at p=36p = 36, over 10610^6 at p=40p = 40, then falls: 16831683 at p=44p = 44, 172172 at p=80p = 80, 97.397.3 at p=160p = 160. Test-error column matches the first cell at common pp values (same seeds) and follows the same pattern. At p=160p = 160 the model has 160 raw and about 97 effective test parameters; at p=30p = 30, 30 raw and about 202 effective: the larger model is simpler by this measure.

The critique does not say double descent is false; it says “parameter count” should not replace norms, effective parameters or EMC as a capacity measure, and apparent contradictions of the classical U-curve challenge a poorly chosen complexity measure. Norm-based bounds (studied with benign interpolation next lesson) and EMC itself are attempts in that direction.

The library version

In scikit-learn, RBFSampler produces random Fourier features for Gaussian kernel e−γ∥x−x′∥2e^{-\gamma\norm{\vb{x} - \vb{x}'}^2} by sampling frequencies from N(0,2γI)\Normal(\vb{0}, 2\gamma\mat{I}); at γ=0.5/d\gamma = 0.5/d these are the same N(0,I/d)\Normal(\vb{0}, \mat{I}/d) used here. LinearRegression solves least squares with lstsq, returning the minimum-norm solution in the underdetermined case, and RidgeCV efficiently chooses λ\lambda by leave-one-out cross-validation.

[ ]The same with scikit-learnBrowser
from sklearn.kernel_approximation import RBFSampler
from sklearn.linear_model import LinearRegression, RidgeCV

rng = np.random.default_rng(11)
X_tr = rng.normal(size=(n, d))
y_tr = f_star(X_tr) + 0.2 * rng.normal(size=n)
print('   p   mínima norma   RidgeCV (LOO)')
for p in [20, 40, 160]:
    mn_err, rd_err = [], []
    for s in range(8):
        rff = RBFSampler(gamma=0.5 / d, n_components=p, random_state=s).fit(X_tr)
        F, Ft = rff.transform(X_tr), rff.transform(X_test)
        lin = LinearRegression(fit_intercept=False).fit(F, y_tr)     # lstsq: solución de mínima norma
        rcv = RidgeCV(alphas=np.logspace(-6, 1, 15), fit_intercept=False).fit(F, y_tr)
        mn_err.append(np.mean((lin.predict(Ft) - f_test) ** 2))
        rd_err.append(np.mean((rcv.predict(Ft) - f_test) ** 2))
    print(f'{p:4d}  {np.mean(mn_err):10.3f}   {np.mean(rd_err):10.3f}')

With one training set and 8 feature draws, the pattern is the same: minimum norm goes from 1.171.17 at p=20p = 20 to 45.045.0 at p=n=40p = n = 40 and 0.4460.446 at p=160p = 160; RidgeCV gives 0.6500.650, 0.4790.479 and 0.2760.276 without a peak. The much lower value at p=np = n than in the first cell is not a contradiction: it averages 8 samples of a heavy-tailed variable and depends on how close the worst smallest singular value is to zero.

Common mistakes

Exercises

ProofLeast-squares variance with Gaussian design
Prove: If rows of X∈Rn×p\mat{X} \in \R^{n\times p} are iid N(0,Ip)\Normal(\vb{0}, \mat{I}_p), y=Xw+ε\vb{y} = \mat{X}\vb{w} + \vb{\eps} with ε\vb{\eps} independent of X\mat{X}, Eε=0\E\vb{\eps} = \vb{0}, Cov⁡(ε)=σ2In\Cov(\vb{\eps}) = \sigma^2\mat{I}_n, and p<n−1p < n - 1, then the least-squares estimator satisfies E∥w^−w∥2=σ2p/(n−p−1)\E\norm{\hat{\vb{w}} - \vb{w}}^2 = \sigma^2 p/(n - p - 1).
0
Lemma (inverse Wishart mean): if W∼Wp(Ip,n)\mat{W} \sim \mathcal{W}_p(\mat{I}_p, n), i.e. W=∑i=1nzizi⊤\mat{W} = \sum_{i=1}^n \vb{z}_i\vb{z}_i\T with zi∼iidN(0,Ip)\vb{z}_i \iid \Normal(\vb{0}, \mat{I}_p), and n>p+1n > p + 1, then E[W−1]=Ip/(n−p−1)\E[\mat{W}\inv] = \mat{I}_p/(n - p - 1).

Step 1 of 4. What is w^−w\hat{\vb{w}} - \vb{w}?

NumericVariance with p = 50 and n = 100
With covariates N(0,Ip)\Normal(\vb{0}, \mat{I}_p), p=50p = 50, n=100n = 100 and σ2=1\sigma^2 = 1, what is least-squares estimator variance E∥w^−w∥2\E\norm{\hat{\vb{w}} - \vb{w}}^2?
NumericAsymptotic risk at γ = 2
Using the Hastie et al. asymptotic formula for γ>1\gamma > 1, r2=1r^2 = 1 and σ2=0.25\sigma^2 = 0.25, calculate minimum-norm risk at γ=2\gamma = 2.
NumericWhere is the local minimum?
In the well-specified isotropic model with SNR=r2/σ2=9\text{SNR} = r^2/\sigma^2 = 9, at what γ>1\gamma > 1 does asymptotic minimum-norm risk have its local minimum?
NumericExact versus asymptotic
With isotropic Gaussian covariates, n=100n = 100, p=200p = 200, r2=1r^2 = 1 and σ2=0.25\sigma^2 = 0.25, what is exact E∥w^−w∥2\E\norm{\hat{\vb{w}} - \vb{w}}^2 for the minimum-norm interpolator?
NumericOptimal ridge
In the isotropic linear model with p=200p = 200, σ2=0.5\sigma^2 = 0.5 and r2=∥w∥2=4r^2 = \norm{\vb{w}}^2 = 4, what is optimal ridge λ\lambda with penalty ∥Xw−y∥2+λ∥w∥2\norm{\mat{X}\vb{w} - \vb{y}}^2 + \lambda\norm{\vb{w}}^2?
QuizWhat removes the peak?
In linear regression with isotropic covariates, noisy labels and the minimum-norm estimator, test error versus nn has a hump at n≈pn \approx p. Which intervention removes it?
QuizWhat double descent does and does not say
Which statements are true?

More than one answer may be correct.

QuizA suspicious validation curve
You train a large ResNet with Adam on CIFAR-10 with 20% noisy labels. Test error falls through epoch 30, rises through epoch 150 and then falls continuously to epoch 4000, below its epoch-30 value. Which explanation fits generalized double descent?
QuizRaw and effective parameters
With p>np > n random features and the minimum-norm interpolator, what best describes increasing pp according to Curth, Jeffares and van der Schaar?
CodeDouble descent in a function
Implement min_norm_rf_risk(n, p_list, d, noise, seeds, rng) returning an array of mean minimum-norm-interpolator test error for each pp in p_list. Model: inputs x∼N(0,Id)\vb{x} \sim \Normal(\vb{0}, \mat{I}_d), target f∗(x)=x1+0.5sin⁡(2x2)f^*(\vb{x}) = x_1 + 0.5\sin(2x_2), labels y=f∗(x)+noise⋅εy = f^*(\vb{x}) + \text{noise}\cdot\varepsilon with ε∼N(0,1)\varepsilon \sim \Normal(0, 1); ReLU features ϕ(x)=max⁡(0,W⊤x)/p\phi(\vb{x}) = \max(0, \mat{W}\T\vb{x})/\sqrt{p} with W∈Rd×p\mat{W} \in \R^{d\times p} entries N(0,1/d)\Normal(0, 1/d); fit a^=Φ+y\hat{\vb{a}} = \Phi\pinv\vb{y}; test error 1500∑j(f^(xj)−f∗(xj))2\frac{1}{500}\sum_j(\hat{f}(\vb{x}_j) - f^*(\vb{x}_j))^2 on 500 test points. For each of seeds repetitions, draw new data and, for each pp, new features; use only rng (a np.random.Generator) for randomness. Tests check that the maximum is at p≈np \approx n and error at p=4np = 4n is below p=np = n.
import numpy as np

def min_norm_rf_risk(n, p_list, d, noise, seeds, rng):
  """Error de test medio del interpolador de mínima norma con p características ReLU, para cada p."""
  risks = np.zeros(len(p_list))
  # tu código: conjunto de test, bucle de semillas (datos nuevos), bucle de p (características nuevas),
  # ajuste con la pseudoinversa y error frente a f* en test
  return risks
Shift+Enter to run

Summary

Key idea
The double-descent peak is variance: when parameter count equals data count, the design matrix’s smallest singular value collapses and noise is amplified by 1/smin⁡21/s_{\min}^2. Far from the threshold in either direction, conditioning improves, and optimal regularization removes the peak.
  • The interpolation threshold is the smallest capacity with zero training error; for least squares with pp features, p=np = n. Belkin et al. (2019) showed test error peaks there and falls to the right with random features, networks, forests and boosting.
  • With isotropic Gaussian design, exact risk is σ2p/(n−p−1)\sigma^2 p/(n - p - 1) for p≤n−2p \le n - 2 and r2(1−n/p)+σ2n/(p−n−1)r^2(1 - n/p) + \sigma^2 n/(p - n - 1) for p≥n+2p \ge n + 2; at ∣p−n∣≤1\abs{p - n} \le 1 it is infinite. Asymptotically (Hastie et al.), σ2γ/(1−γ)\sigma^2\gamma/(1 - \gamma) and r2(1−1/γ)+σ2/(γ−1)r^2(1 - 1/\gamma) + \sigma^2/(\gamma - 1).
  • The peak is variance; without noise and misspecification there is no peak. In random features, peak variance is mostly feature-data interaction (Adlam and Pennington), addressed by model averaging.
  • In the well-specified isotropic model the global minimum is at γ→0\gamma \to 0; an overparameterized global minimum requires new features to bring signal (misspecification, random features).
  • Ridge with λ∗=pσ2/r2\lambda^* = p\sigma^2/r^2 makes risk monotone in nn; validated λ\lambda also removes the random-feature peak.
  • Deep networks show model-wise, epoch-wise and sample-wise double descent, unified by training procedure effective complexity (EMC).
  • Parameter count is a poor complexity axis: measured on new points, effective complexity falls beyond the threshold (Curth et al.), so the second descent decreases complexity.