Benign overfitting and the puzzle of deep generalization
Deep networks can fit random labels and still generalize from real labels. This rules out explanations that depend only on the hypothesis class. Reproduce the random-label experiment, study effective ranks and benign interpolation in linear regression, classify benign, tempered, and catastrophic interpolation, and examine spectral margin bounds and the limits of uniform convergence.
After this lesson you can
- Reproduce the random-label experiment and explain which explanations it rules out.
- State the effective-rank conditions for benign linear interpolation and explain how the covariance separates signal from a tail that absorbs noise.
- Classify interpolation by nearest neighbors, singular-kernel Nadaraya–Watson, unregularized kernels, and neural networks as benign, tempered, or catastrophic.
- Compute a spectrally normalized margin bound and compare it with a trained network’s observed error.
- Explain Nagarajan and Kolter’s argument about the limits of uniform convergence.
- Compare empirical measures of generalization examined by Jiang et al. and Dziugaite et al.
Before you start
- 13Double descentMinimum-norm interpolatorRademacher complexityMargin-based generalization boundPAC-Bayes boundNonvacuous generalization boundsEffective dimension
- 15Multilayer perceptron
- 00Canonical training and evaluation loop
- 02Operator normFrobenius norm
- 04Multivariate Gaussian distributionAffine transformations of Gaussians
The experiment that made theorists rethink generalization
In 2017, Zhang, Bengio, Hardt, Recht and Vinyals published a straightforward experiment. Take a network that works well on CIFAR-10, replace the training labels with random ones, and train with the same architecture, optimizer and hyperparameters. Training error reaches zero. Test error is about 90%, the chance rate for ten classes, because training labels tell the model nothing about the images.
Table 1 gives the numbers. A reduced Inception network with parameters reaches training accuracy on both real and random labels. Test accuracy is with real labels, without data augmentation or weight decay, and with random labels. AlexNet, with parameters, achieves versus . An MLP with three 512-unit hidden layers and parameters achieves versus . On ImageNet, with a million random labels spread across a thousand classes, Inception V3 reaches top-1 training accuracy with unchanged hyperparameters. Networks also fit when the inputs are Gaussian noise or each image’s pixels have been randomly permuted.
Three observations matter:
- These networks have enough effective capacity to memorize the entire training set.
- Random labels remain easy to optimize. Training time increases by only a small constant factor in Figure 1b.
- Randomization changes the data while holding the model, algorithm and parameter count fixed.
The same procedure generalizes on one dataset and fails to generalize on another. An explanation must distinguish the two cases, so it must depend on the data. This lesson first establishes what the experiment rules out. It then analyzes overparameterized linear regression, where interpolating noise can be harmless, and classifies interpolating methods by what happens to their noise. Finally it studies norm- and margin-based neural network bounds and Nagarajan and Kolter’s argument about the limits of uniform convergence.
Run the race in your browser
For the orange network reaches zero training error by drawing islands around incorrect labels. Between the islands the decision boundary stays near the true boundary. Increase and the islands take over the plane. Compare the steps at which each network fits. Isolating a few wrong labels inside the opposite class region can take as many steps as fitting entirely unstructured labels, or more. The picture suggests that the model learns signal globally and noise locally. Benign interpolation theory formalizes this intuition for linear models. In practice, memorized noise can leave neural networks with residual test error even as the dataset grows.
With classes and replacement probability , the expected fraction of incorrect labels is . A replacement matches the true class with probability . In the two-class widget the fraction is . For CIFAR-10 with , it is .
Fitting arbitrary labels takes a shallow network
It is unsurprising that a network with millions of parameters can fit labels. Zhang et al. make the expressiveness claim precise with an explicit construction.
Proof
Consider , with and . Its single hidden layer has units with shared direction and different thresholds, for weights in total. The are distinct, so directions with for some form a finite union of measure-zero hyperplanes. There is therefore a direction with distinct projections . Reorder the points so and choose interleaved thresholds . Matrix is lower triangular because implies . Its diagonal is positive, which makes it invertible. The system has a solution, so .
∎The construction reduces to a linear solve. The cell uses points in dimension , the size of a CIFAR-10 image, and random labels.
import numpy as np
rng = np.random.default_rng(0)
n, d = 200, 3072 # tantos píxeles como una imagen de CIFAR-10
Z = rng.standard_normal((n, d))
y = rng.integers(0, 10, n).astype(float) # etiquetas aleatorias (como números reales)
a = rng.standard_normal(d) # dirección genérica: las proyecciones son distintas
x = Z @ a
order = np.argsort(x); xs = x[order]
b = np.empty(n) # umbrales intercalados: b_1 < x_1 < b_2 < x_2 < ...
b[0] = xs[0] - 1.0
b[1:] = (xs[:-1] + xs[1:]) / 2
A = np.maximum(xs[:, None] - b[None, :], 0) # A_ij = max(x_i - b_j, 0): triangular inferior
w = np.linalg.solve(A, y[order])
pred = np.maximum((Z @ a)[:, None] - b[None, :], 0) @ w # la red c(z) = sum_j w_j relu(<a, z> - b_j)
print('parámetros: n + n + d =', 2 * n + d)
print('¿A triangular inferior?', np.allclose(A, np.tril(A)), ' menor elemento de su diagonal: %.3g' % np.diag(A).min())
print('error máximo de ajuste: %.2e' % np.abs(pred - y).max())
print('norma de w: %.3g' % np.linalg.norm(w))The fit is exact up to rounding. The norm of is on the order of because the thresholds are close together and the system is poorly conditioned. This suggests examining data-dependent quantities such as norms and margins to distinguish memorization from generalization.
What the experiment rules out
Recall the empirical Rademacher complexity of a class of functions valued in on the sample:
where are independent uniform signs. It measures how well can fit random labels. If for each assignment of signs some gives , the supremum is 1, so attains its maximum. For 0–1 loss, the Rademacher bound gives, with probability at least , for all . It becomes vacuous with . The same problem arises with VC dimension, which must be at least .
The experiment supports a more general argument.
Proof
The bound must hold under . If , the event that returns an with gap at least has probability greater than , and the bound fails on that event. This is a contradiction. Because is distribution-free, the same number is the guarantee under the real distribution.
∎On CIFAR-10, . Such a bound can at best guarantee test error for a network whose actual accuracy is . The same reasoning applies to an algorithm-wide bound. A bound depending only on and , such as one based on uniform stability, must also cover training with random labels, as Zhang et al. point out.
Several explanations remain possible:
- Bounds that depend on the learned predictor and therefore on the data. Its margin, norms, distance from initialization or local loss flatness can differ between real and random labels. A bound can be small in one case and vacuous in the other.
- The algorithm’s implicit bias. Gradient descent selects a particular interpolator, such as a minimum-norm solution for linear models or a maximum-margin classifier under suitable conditions. See implicit regularization. The relevant class can be the predictors the algorithm produces on data like these.
- PAC-Bayes bounds with data-dependent posteriors. Dziugaite and Roy (2017) obtained nonvacuous bounds for neural networks on MNIST by optimizing the posterior in a PAC-Bayes bound.
Removing data augmentation and weight decay drops Inception test accuracy from to in Table 1. The effect is appreciable, but random labels reduce it to . The paper argues that explicit regularizers help while leaving the main explanation of generalization open.
Benign interpolation in linear regression
Overparameterized linear regression with the minimum-norm interpolator gives a complete answer in one setting. Gradient descent from zero converges to this solution. The double descent lesson computed its risk in the isotropic proportional regime. Here the question is which covariance structures make interpolating noise harmless, with risk converging to the optimum.
The model
We follow the Gaussian version of Bartlett, Long, Lugosi and Tsigler (2020). Inputs are with , hence . This is a multivariate Gaussian obtained by an affine transformation of a standard Gaussian, in finite dimension or a separable Hilbert space. Responses are , with independent of . The eigenvalues of are , with . The paper allows the components of to be independent and sub-Gaussian, and noise conditional on to be sub-Gaussian with conditional variance at least . Gaussian noise suffices to illustrate the argument.
With observations stored as rows of and , matrix is invertible almost surely. The minimum-norm interpolator is
Its excess risk is .
The first exercise proves this in four algebraic steps. Bias comes from the component of orthogonal to the row space. Variance comes from noise , which the interpolator fits exactly into and carries into predictions on new . Two notions of dimension explain when is small.
Effective ranks
Both quantify how many directions contribute significantly in the tail . When the tail contains equal eigenvalues, . If one eigenvalue dominates, both ranks approach 1. They are related to the effective dimension of kernel ridge regression. compares tail mass with its largest eigenvalue, while is the reciprocal of its purity, .
Proof
Write and . Since is the largest tail eigenvalue, . This gives and , hence . Finally, gives .
∎The theorem
Here is the sub-Gaussian constant of the noise, equal to in the Gaussian case. Matching upper and lower orders characterize the variance. The bias bound is upper-only, and the paper adds a lower bound that makes it necessary in the worst case over . Interpolation is near optimal when is small relative to , is small relative to , and is large relative to .
Proof sketch
Focus on the variance. Write and for the normalized columns of in the covariance eigenbasis. They are independent vectors. Then and by Lemma 8,
Split the sum into the first directions and the tail. Let be the tail contribution to the Gram matrix.
Step 1. The tail Gram matrix is nearly a scalar multiple of the identity. By Lemma 9, with probability at least , every eigenvalue of lies between and . When , the term is a small fraction of , and with , up to constants. The intuition is a law of large numbers. adds many small rank-one matrices in random directions, and no single direction dominates. This is precisely the condition . Tail mass divided by the largest tail eigenvalue must exceed .
Step 2. The tail absorbs label noise. If along the tail directions, each contribution is approximately , giving the sum
Step 3. The signal directions behave like ridge regression. For , the Sherman–Morrison identity with gives
This is the variance per coordinate of ordinary least squares. The first directions sum to . Together the two parts give . Lemma 17 shows that the best , up to constants, is the smallest one satisfying , namely .
Step 4. Bound the bias. The tail imposes an effective ridge penalty of size on the signal directions. The interpolator shrinks each signal coordinate by a factor on the order of . When is comparable to , this suppresses the signal. A small ensures this implicit regularization preserves it. See Appendices J and K.
The first signal directions behave like least squares regularized by the tail. Noise spreads over many directions of very small variance, with total cost .
Which spectra are benign?
The paper’s Theorem 6 treats two families:
- Infinite dimension with fixed covariance. If , the covariance is benign exactly when and . Eigenvalues must decay fast enough to be summable, with finite , but an overly fast decay can fail. With , for example, and , so grows only like , is on the order of , and does not vanish.
- Finite dimension with an isotropic floor. If for and afterward, with , the sequence is benign exactly when and . Dimension grows faster than . Total isotropic tail mass grows more slowly than , without becoming exponentially small.
The second case gives a general picture of signal in a few directions and a nearly flat tail in dimension much larger than . Bartlett et al. conclude that overparameterization is essential to benign interpolation in this model.
Lab: reproduce the theorem’s predictions
The lab generates Gaussian observations with specified spectra, computes the minimum-norm interpolator and its exact risk conditional on , then averages the bias and variance over four design matrices. It compares them with the theorem’s terms using to calculate . The theorem leaves the constants unspecified, so compare orders of magnitude and patterns.
import numpy as np
def tail_spectrum(k, p_t, mass, alpha):
"""k autovalores de señal iguales a 1 y una cola de p_t autovalores con perfil i^(-alpha) y suma `mass`."""
t = np.arange(1, p_t + 1) ** (-float(alpha))
return np.concatenate([np.ones(k), mass * t / t.sum()])
def ranks(lam, n, b=1.0):
"""r_0, k* = min{k : r_k >= b n} y los rangos efectivos r_{k*}, R_{k*} (lam en orden decreciente)."""
s1 = np.cumsum(lam[::-1])[::-1] # s1[k] = suma de los autovalores de índice > k (desde 0)
s2 = np.cumsum((lam ** 2)[::-1])[::-1]
r = s1 / lam # r[k] = r_k(Sigma)
ok = np.nonzero(r >= b * n)[0]
if len(ok) == 0:
return r[0], None, None, None
k = ok[0]
return r[0], k, r[k], s1[k] ** 2 / s2[k]
def min_norm_risk(lam, theta, n, reps, rng):
"""Sesgo theta^T B theta y tr(C) del interpolador de mínima norma, promediados en `reps` diseños."""
bias, trC = 0.0, 0.0
for _ in range(reps):
X = rng.standard_normal((n, len(lam))) * np.sqrt(lam) # filas x_i ~ N(0, Sigma)
Gi = np.linalg.inv(X @ X.T)
XS = X * lam # X Sigma
trC += np.trace(Gi @ (XS @ X.T) @ Gi) / reps # tr((XX^T)^-1 X Sigma X^T (XX^T)^-1)
u = theta - X.T @ (Gi @ (X @ theta)) # (I - P) theta
bias += np.sum(lam * u * u) / reps
return bias, trC
rng = np.random.default_rng(0)
n, k, sigma = 50, 5, 0.5
presets = {'benigno': (100 * n, 0.1 * n, 0.0), 'cola corta': (int(1.5 * n), 0.1 * n, 0.0),
'cola pesada': (100 * n, 3 * n, 0.0), 'cola empinada': (100 * n, 0.1 * n, 1.5)}
print(f'n = {n}, k = {k}, sigma^2 = {sigma**2}')
print(f"{'espectro':>14} {'r0/n':>6} {'k*':>4} {'R_k*/n':>7} {'sesgo':>7} {'varianza':>9} {'teoría':>8} {'exceso/s2':>9}")
for name, (p_t, mass, alpha) in presets.items():
lam = tail_spectrum(k, p_t, mass, alpha)
theta = np.zeros(len(lam)); theta[:k] = 1 / np.sqrt(k)
r0, ks, rk, Rk = ranks(lam, n)
b, tC = min_norm_risk(lam, theta, n, 4, rng)
th = sigma**2 * (ks / n + n / Rk) if ks is not None else float('nan')
print(f'{name:>14} {r0/n:6.3f} {str(ks):>4} {Rk/n if Rk else float("nan"):7.2f} {b:7.4f} {sigma**2*tC:9.4f} {th:8.4f} {(b+sigma**2*tC)/sigma**2:9.3f}')The recorded run uses , five signal directions of eigenvalue 1, and a unit-norm spread across those directions. Always predicting zero gives risk 1 in these units.
- Benign: the flat tail has eigenvalues of total mass . The run gives , , variance versus prediction , and bias . Excess risk is of , even after fitting all 50 labels with noise standard deviation .
- Short tail: the same mass is spread over only eigenvalues. Now and variance rises to , nearly twice . The prediction is . The factor of 2.4 is within the scale left open by the constants. The setup is also close to the interpolation threshold, versus , where the previous lesson showed a variance spike.
- Heavy tail: tail mass is . This gives and because the tail alone satisfies . Variance is only , and bias is . The tail acts like a ridge penalty of size 150 against and suppresses the signal.
- Steep tail: with profile the tail is uneven. exceeds only at , comparable to . Variance is , or of .
The second experiment increases with a spectrum of the form in Theorem 6.2. It uses five signal directions and a flat tail with eigenvalues and total mass , so and .
rng = np.random.default_rng(1)
sigma, k = 0.5, 5
print(f"{'n':>4} {'p':>6} {'r0/n':>6} {'k*':>3} {'R_k*/n':>7} {'sesgo':>7} {'varianza':>8} {'teoría':>7} {'exceso/s2':>9}")
for n in [16, 32, 64, 128]:
p_t = n * n // 4 # p_n = n^2/4, mucho mayor que n
mass = np.sqrt(n) # eps_n p_n = sqrt(n) = o(n)
lam = tail_spectrum(k, p_t, mass, 0.0)
theta = np.zeros(len(lam)); theta[:k] = 1 / np.sqrt(k)
r0, ks, rk, Rk = ranks(lam, n)
b, tC = min_norm_risk(lam, theta, n, 4, rng)
print(f'{n:4d} {len(lam):6d} {r0/n:6.3f} {ks:3d} {Rk/n:7.2f} {b:7.4f} {sigma**2*tC:8.4f} {sigma**2*(ks/n+n/Rk):7.4f} {(b+sigma**2*tC)/sigma**2:9.3f}')Excess risk in units of falls from with to , and with . Simulated variance matches the prediction within in every row and roughly halves as doubles, as predicts. Bias falls with . Every model interpolates its noisy labels, yet its risk approaches Bayes risk.
For a library implementation, np.linalg.lstsq and np.linalg.pinv return the minimum-norm solution to an underdetermined system. sklearn.linear_model.LinearRegression(fit_intercept=False) uses scipy.linalg.lstsq underneath and gives the same solution.
from sklearn.linear_model import LinearRegression
rng = np.random.default_rng(2)
lam = tail_spectrum(5, 2000, 2.0, 0.0)
X = rng.standard_normal((40, len(lam))) * np.sqrt(lam)
y = X[:, :5].sum(1) / np.sqrt(5) + 0.5 * rng.standard_normal(40)
th_formula = X.T @ np.linalg.solve(X @ X.T, y)
th_lstsq = np.linalg.lstsq(X, y, rcond=None)[0]
th_sk = LinearRegression(fit_intercept=False).fit(X, y).coef_
print('lstsq frente a la fórmula: %.1e' % np.abs(th_lstsq - th_formula).max())
print('sklearn frente a la fórmula: %.1e' % np.abs(th_sk - th_formula).max())
print('residuo de entrenamiento: %.1e' % np.abs(X @ th_sk - y).max())Signal and the tail that absorbs noise
The theorem turns a question about the estimator into a question about its covariance spectrum. A benign covariance separates into two parts:
- Signal. A few directions () with large eigenvalues contain . In those directions, the interpolator behaves like least squares with an implicit ridge penalty of size .
- Tail. Many directions () have small, similar eigenvalues. The interpolator finds in the tail the degrees of freedom it needs to fit points. Each tail direction has low variance, so can have large tail coefficients while changing predictions on new points very little.
Bartlett, Montanari and Rakhlin (2021) frame this as a general principle. An interpolator can decompose into a simple predictive part and a spiky part that fits noise without substantially affecting predictions in favorable settings. The theorem’s conditions identify three failure modes. A short tail keeps below and prevents variance from vanishing. A steep tail delays from exceeding , so grows and remains large. A heavy tail raises so the implicit ridge penalty suppresses signal. Keeping the tail long, flat and light requires dimension much larger than .
With a flat tail, the theoretical marker and variance bar move together as , or changes, even when their heights differ. The theorem leaves multiplicative constants unspecified. For a fixed tail, increasing eventually breaks benign behavior. falls, which helps bias. With a flat tail, for is at most tail length . As approaches , no reaches and variance spikes. Shorten the tail to a few hundred eigenvalues and raise to see this. The tail must grow with for risk to vanish, as in Theorem 6.
Benign, tempered and catastrophic overfitting
Benign interpolation is one extreme. At the other, fitting noise can make the predictor arbitrarily bad. Mallinar, Simon, Abedsoltan, Pandit, Belkin and Nakkiran (2022) found that many practical methods sit between these extremes and proposed three categories.
Any consistent estimator is benign, whether it interpolates or not. The interesting question is where interpolating methods fall. Take and with continuous and of variance . Then , and excess risk is .
1-NN has tempered overfitting
Proof
Let be the training point closest to , and let be its noise. Then . The neighbor’s noise is independent of its position and , with zero mean and variance . The cross term has mean zero, so . Now in probability. The chance that no point lies within distance of decays geometrically in . Because is continuous and bounded, the first term tends to zero by dominated convergence.
∎Interpolation with 1-NN incurs one full noise variance even in the limit. Cover and Hart’s 1967 result gives the classification analogue: asymptotic 1-NN risk satisfies for two classes. Averaging the nearest neighbors with fixed lowers the noise term to . The positive limit still gives tempered overfitting. Consistency requires and .
Unregularized kernels: Laplace is tempered and Gaussian is catastrophic
The minimum-norm interpolant for kernel is with , equivalent to kernel ridge with . The one-dimensional Laplace kernel has a closed-form solution. Its reproducing kernel Hilbert space is first-order Sobolev, and the minimum-norm interpolant solves between consecutive points. This gives an exponential spline
As increases with fixed , gaps become much smaller than and the spline approaches piecewise linear interpolation. If lies in gap at relative position , its predicted noise component is , of variance . Since is uniform within the gap, and . Excess risk tends to , giving tempered overfitting. Mallinar et al. cite this argument from Belkin et al. (2018) and extend it with an empirically checked spectral approximation of kernel ridge risk. Unregularized kernel ridge with a power-law spectrum, such as a Laplace or ReLU neural tangent kernel, is tempered in that analysis.
The Gaussian kernel behaves differently. Its Gram matrix approaches singularity when sample spacing falls below . Its eigenvalues in one dimension decay like . To fit noisy points the interpolant uses huge alternating coefficients and oscillates sharply between the points. The spectral trichotomy in Mallinar et al., Theorem 3.1, gives benign behavior with positive ridge or eigenvalue decay as slow as with . It gives tempered behavior for power law with , and catastrophic behavior if decay is at least as fast as . The Gaussian kernel is in the last category.
Singular-kernel Nadaraya–Watson is benign
Benign interpolators can exist in fixed dimension. Belkin, Rakhlin and Tsybakov (2019) use the Nadaraya–Watson estimator
with a kernel singular at the origin. Because , each dominates in a tiny neighborhood of , producing interpolation. Under their standard assumptions on the density of and on the noise, if is -Hölder with , and , Theorem 1 gives pointwise squared error , the minimax rate. Noise is fit in arbitrarily narrow spikes, and away from the spikes the estimator averages like a smoother. Devroye, Györfi and Krzyżak (1998) had already proved consistency for the bandwidth-free Hilbert kernel .
The NumPy simulation gives the numerical results.
f = lambda x: np.sin(2 * np.pi * x)
t = (np.arange(600) + 0.5) / 600 # puntos de evaluación en [0, 1]
def nn1(x, y): # x ordenado
j = np.clip(np.searchsorted(x, t), 1, len(x) - 1)
left = (t - x[j - 1]) <= (x[j] - t)
return np.where(left, y[j - 1], y[j])
def nw_singular(x, y, a=0.45): # K(u) = |u|^-a 1{|u| <= 1}, ventana h = n^(-1/3)
h = len(x) ** (-1 / 3)
d = np.abs(t[:, None] - x[None, :]) / h
with np.errstate(divide='ignore'):
w = np.where(d <= 1, d ** (-a), 0.0)
return (w @ y) / w.sum(1)
def laplace(x, y, l=0.2): # mínima norma del núcleo e^{-|s-t|/l}: spline exponencial
j = np.clip(np.searchsorted(x, t), 1, len(x) - 1)
a, b = x[j - 1], x[j]
out = (y[j - 1] * np.sinh((b - t) / l) + y[j] * np.sinh((t - a) / l)) / np.sinh((b - a) / l)
out = np.where(t < x[0], y[0] * np.exp(-(x[0] - t) / l), out)
return np.where(t > x[-1], y[-1] * np.exp(-(t - x[-1]) / l), out)
def gauss(x, y, l=0.05): # kernel ridge gaussiano sin regularizar
K = np.exp(-(x[:, None] - x[None, :]) ** 2 / (2 * l * l))
try:
L = np.linalg.cholesky(K)
except np.linalg.LinAlgError:
return None
if len(x) / np.min(np.diag(L)) ** 2 > 1e13: # indicador de mal condicionamiento (el mismo del interactivo)
return None # fuera del alcance de la doble precisión
alpha = np.linalg.solve(L.T, np.linalg.solve(L, y))
pred = np.exp(-(t[:, None] - x[None, :]) ** 2 / (2 * l * l)) @ alpha
return pred if np.all(np.isfinite(pred)) else None
rng = np.random.default_rng(0)
sigma = 0.5
methods = {'1-NN': nn1, 'NW singular': nw_singular, 'Laplace': laplace}
print('riesgo en exceso / sigma^2, media de 12 muestras')
print(f"{'n':>5}" + ''.join(f'{m:>13}' for m in methods))
for n in [8, 16, 32, 128, 512, 1024]:
acc = {m: [] for m in methods}
for s in range(12):
x = np.sort(rng.uniform(0, 1, n)); y = f(x) + sigma * rng.standard_normal(n)
for m, fit in methods.items():
acc[m].append(np.mean((fit(x, y) - f(t)) ** 2) / sigma**2)
print(f'{n:5d}' + ''.join(f'{np.mean(v):13.3g}' for v in acc.values()))
# el gaussiano tiene colas enormes (dos puntos muy juntos bastan para disparar los coeficientes):
# se resume con la mediana de 100 muestras, contando cuántas se pueden calcular en doble precisión
print('\ngaussiano sin regularizar: mediana de 100 muestras (calculables)')
for n in [8, 12, 16, 20, 24, 28, 32]:
v = []
for s in range(100):
x = np.sort(rng.uniform(0, 1, n)); y = f(x) + sigma * rng.standard_normal(n)
pred = gauss(x, y)
if pred is not None:
v.append(np.mean((pred - f(t)) ** 2) / sigma**2)
print(f'{n:5d} {np.median(v):12.3g} ({len(v)})')From onward, 1-NN stays between and . The Laplace kernel stays between and . The plateaus match and with variability across 12 samples. Singular Nadaraya–Watson falls from at to at while still interpolating. Gaussian errors have heavy tails because two close points are enough to yield huge coefficients. The cell reports the median of 100 runs. It goes from at to at , at , and at . At that point only 92 of 100 runs are computable in double precision. The overfitting is catastrophic, and computation starts to break down long before becomes large.
How neural networks behave
Mallinar et al. train a Wide ResNet 28×10 on binary CIFAR-10 (animals versus vehicles) with label flips and increasing in Figure 2. They also train ResNets on all ten classes in Figure 6a. Test error increases with label noise and does not return to the optimum as grows, so the interpolating networks are tempered. The same architectures can behave benignly with early stopping. Even a three-layer MLP on a simple synthetic problem with inputs on sphere and constant labels stops learning the constant function once it trains to interpolate a little noise.
The orange network in the opening experiment memorizes wrong labels in islands and pays residual test error for them. That is tempered behavior: prediction is still useful and the added error persists as data grow.
Memorization can help on long-tailed distributions
If memorization carries a cost, why does more regularization not solve the problem? Feldman (2020) gave an architecture-independent answer. On long-tailed distributions, a learner that avoids memorization can be necessarily suboptimal.
The model mixes many subpopulations, such as pictures taken at night of a rare dog breed. Frequencies are drawn from prior . In a sample of size , many subpopulations appear once and are called singletons. From one example the learner cannot distinguish a subgroup of frequency on the order of , likely to be tested again, from a very rare outlier. If the singleton’s label cannot be inferred from other data, memorizing it is the only way to predict correctly on its subgroup.
Feldman’s Theorem 2.3 quantifies the cost. In the special case discussed here,
where counts training singletons the learned predictor misclassifies, and is the frequency distribution. Each missed singleton costs in expected generalization error. For a long tail, is on the order of while singletons remain a constant fraction of . The total excess is constant. The cell reproduces the paper’s numerical example, using Zipf frequencies () over elements and samples.
N = n = 50_000
p = 1 / np.arange(1, N + 1); p /= p.sum() # frecuencias de Zipf
w = (1 - p) ** (n - 1)
tau1 = np.sum(p**2 * w) / np.sum(p * w) # pérdida esperada por cada singleton que no se ajusta
singletons = n * np.sum(p * w) # número esperado de elementos vistos una sola vez
missing = np.sum(p * (1 - p) ** n) # masa de los elementos que no aparecen en la muestra
print(f'tau_1 = {tau1 * n:.3f} / n')
print(f'fracción esperada de singletons: {singletons / n:.3f}')
print(f'exceso si se acierta al azar en los singletons (2 clases): {tau1 * singletons / 2:.4f}')
print(f'exceso si se acierta al azar en los singletons (10 clases): {tau1 * singletons * 0.9:.4f}')
print(f'masa no observada: {missing:.4f} (error óptimo con 2 clases: {missing / 2:.4f})')The result is and singletons, as in the paper. A predictor that performs at chance on singletons loses error points with two classes, against optimum , and points with ten classes. Feldman extends this to noisy labels in Theorem 2.4. If a singleton’s observed label is the most likely one, fitting it remains optimal even when it is sometimes wrong. That helps explain why methods that generalize on natural data also remember some incorrect labels and why discouraging memorization through differential privacy or compression can cost accuracy in low-frequency groups. Memorized rare examples can also expose private information through membership inference and data extraction, covered in the reliability module.
Norm- and margin-based bounds for neural networks
If parameter count fails to quantify the relevant capacity, what does? The most studied alternative comes from linear models. The margin lesson showed that the class on data satisfying has Rademacher complexity at most , independent of dimension. The margin bound bounds test error by margin error plus a term on the order of . Capacity depends on a norm divided by the margin.
For a network with -Lipschitz activations and , as for ReLU and nonoverlapping max pooling with , the network’s Lipschitz constant is bounded by , the product of spectral norms. Bartlett, Foster and Telgarsky (2017) build their complexity measure from this quantity.
Lemma A.8 gives explicit constants after fixing norm bounds in advance. The theorem’s union over norm bounds adds logarithmic terms. The lemma gives
and the lab evaluates it. The ratio is the normalized margin. The paper recommends comparing full normalized-margin distributions because the bound applies across margin levels.
Quantity is invariant under rescalings that preserve the function. A bias-free ReLU network satisfies for , so scaling one layer by and another by leaves the function unchanged. The product of spectral norms and the ratios are unchanged. The sum of squared Frobenius norms changes.
rng = np.random.default_rng(0)
A = [rng.standard_normal((64, 20)) / 4, rng.standard_normal((64, 64)) / 8, rng.standard_normal((3, 64)) / 8]
X = rng.standard_normal((100, 20)); y = rng.integers(0, 3, 100)
def net(A, X):
h = X.T
for W in A[:-1]:
h = np.maximum(W @ h, 0)
return (A[-1] @ h).T
def medidas(A):
spec = [np.linalg.norm(W, 2) for W in A]
l21 = [np.linalg.norm(W, axis=1).sum() for W in A] # ||A^T||_{2,1}: suma de normas de filas
R_A = np.prod(spec) * sum((l / s) ** (2 / 3) for l, s in zip(l21, spec)) ** 1.5
out = net(A, X)
marg = out[np.arange(100), y] - np.max(np.where(np.eye(3)[y] == 1, -np.inf, out), axis=1)
return np.prod(spec), sum(np.linalg.norm(W) ** 2 for W in A), R_A, marg / R_A
c = 10.0
B = [A[0] * c, A[1] / c, A[2]] # misma función: relu(c z) = c relu(z)
print('misma salida:', np.allclose(net(A, X), net(B, X)))
res = [medidas(W) for W in (A, B)]
for name, (p, f2, R, nm) in zip(['original', 'reescalada'], res):
print(f'{name:>10}: prod ||A_i||_2 = {p:.4f} sum ||A_i||_F^2 = {f2:9.2f} R_A = {R:.4f}')
print('márgenes normalizados idénticos:', np.allclose(res[0][3], res[1][3]))The sum of squared Frobenius norms goes from to for the same function. To compare networks with different parameterizations, such as different initialization scales or use of batch normalization, use invariant measures or normalize them first.
Lab: random labels and spectral norms on a GPU
The lab reproduces the Zhang et al. experiment and uses the measurements of Bartlett, Foster and Telgarsky. It trains an MLP like the one in the paper and a small CNN with two convolutions of 32 and 64 channels, max pooling and two linear layers. Both omit biases to meet the bound’s assumptions. CIFAR-10 labels are randomized at rates , , and . The lab uses SGD with momentum 0.9, learning rate 0.01, batches of 128, and no augmentation or weight decay. Each network stops when mean training cross-entropy falls below . A common stopping criterion makes norms and margins more comparable across runs. Jiang et al. (2020) use the same idea and stop at . The lab records the first epoch with zero training error, clean-label test error, and each layer’s spectral, Frobenius and norms. It treats convolutions as linear operators over the full image. Power iteration uses convolution and its transpose, and the norm sums the exact row norms. It also records , the normalized-margin distribution, and the Lemma A.8 bound with set to the tenth percentile of training margins and .
Run the full configuration with , all CIFAR-10 and three seeds. With ORYON_VERIFY_SHORT=1 the shorter run uses , two seeds and 5,000 test images. Automated checks skip this cell because of its runtime. Data come from a pinned copy of CIFAR-10 on Hugging Face (uoft-cs/cifar10) downloaded once.
"""Etiquetas aleatorias y cotas espectrales: el experimento de Zhang et al. (2017) medido como Bartlett, Foster y Telgarsky (2017).
Una MLP 3x512 y una CNN pequeña, ambas sin sesgos (como en la cota de BFT), se entrenan con SGD sobre un subconjunto de
CIFAR-10 con una fracción p de etiquetas aleatorias (con probabilidad p, la etiqueta se sustituye por una clase uniforme,
sorteada una vez). Cada red se entrena hasta que su entropía cruzada media de entrenamiento baja de 0.001 (o hasta MAX_EPOCHS).
Se registran la época en que ajusta, el error de test (con etiquetas limpias), las normas espectral, de Frobenius y (2,1)
de cada capa, la complejidad espectral R_A, los márgenes normalizados y la cota del lema A.8 de BFT.
ORYON_VERIFY_SHORT=1 ejecuta una versión corta (menos datos, dos semillas) que comprueba el flujo.
"""
import io as _io
import json
import math
import os
import time
from pathlib import Path
import numpy as np
import pyarrow.parquet as pq
import torch
import torch.nn.functional as F
from huggingface_hub import hf_hub_download
from PIL import Image
from torch import nn
SHORT = os.environ.get('ORYON_VERIFY_SHORT') == '1'
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if SHORT:
N_TRAIN, N_TEST, MAX_EPOCHS, SEEDS = 10000, 5000, 500, [0, 1]
else:
N_TRAIN, N_TEST, MAX_EPOCHS, SEEDS = 50000, 10000, 2000, [0, 1, 2]
NOISES = [0.0, 0.2, 0.5, 1.0]
LR, MOMENTUM, BATCH, DELTA = 0.01, 0.9, 128, 0.05
CE_STOP = 0.001 # se para cuando la entropía cruzada media de entrenamiento baja de aquí (Jiang et al. usan 0.01)
OUT = Path(os.environ.get('ORYON_SPECTRAL_OUTPUT', 'random-labels-spectral.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)
X_raw, y_clean = load_cifar('train', gen.permutation(50000)[:N_TRAIN])
mean, std = X_raw.mean((0, 2, 3), keepdim=True), X_raw.std((0, 2, 3), keepdim=True)
Xtr = ((X_raw - mean) / std).to(device)
Xte_raw, yte = load_cifar('test', gen.permutation(10000)[:N_TEST])
Xte, yte = ((Xte_raw - mean) / std).to(device), yte.to(device)
X_NORM = Xtr.flatten(1).norm().item() # ||X||_2 de BFT: norma de Frobenius de la matriz de datos (n x d)
print(f'n = {N_TRAIN}, test limpio = {N_TEST}, ||X||_2 = {X_NORM:.1f}')
def corrupt(p, seed):
"""Con probabilidad p, la etiqueta se sustituye por una clase uniforme (puede coincidir con la verdadera)."""
g = np.random.default_rng(1000 + seed)
mask = torch.tensor(g.random(N_TRAIN) < p)
rand = torch.tensor(g.integers(0, 10, N_TRAIN))
return torch.where(mask, rand, y_clean).to(device)
# ---------------------------------------------------------------- modelos (sin sesgos: F_A(x) = s_L(A_L ... s_1(A_1 x)))
def make_mlp():
return nn.Sequential(nn.Flatten(), nn.Linear(3072, 512, bias=False), nn.ReLU(), nn.Linear(512, 512, bias=False),
nn.ReLU(), nn.Linear(512, 512, bias=False), nn.ReLU(), nn.Linear(512, 10, bias=False))
def make_cnn():
return nn.Sequential(nn.Conv2d(3, 32, 3, padding=1, bias=False), nn.ReLU(), nn.MaxPool2d(2),
nn.Conv2d(32, 64, 3, padding=1, bias=False), nn.ReLU(), nn.MaxPool2d(2),
nn.Flatten(), nn.Linear(4096, 256, bias=False), nn.ReLU(), nn.Linear(256, 10, bias=False))
IN_SHAPES = {'mlp': None, 'cnn': [(3, 32, 32), (32, 16, 16), None, None]}
# ---------------------------------------------------------------- normas de cada capa como operador lineal
@torch.no_grad()
def layer_norms(layer, in_shape):
"""(espectral, Frobenius del operador, ||A^T||_{2,1}, dimensión de salida) de una capa lineal o convolucional."""
W = layer.weight.float()
if isinstance(layer, nn.Linear):
s = torch.linalg.matrix_norm(W, ord=2).item()
return s, W.norm().item(), W.norm(dim=1).sum().item(), W.shape[0]
# convolución (paso 1, relleno 1) como matriz de (C_out H W) x (C_in H W)
x = torch.randn(1, *in_shape, device=W.device)
for _ in range(100): # iteración de potencias con A y su traspuesta
x = F.conv_transpose2d(F.conv2d(x, W, padding=1), W, padding=1)
x = x / x.norm()
s = F.conv2d(x, W, padding=1).norm().item()
row_sq = F.conv2d(torch.ones(1, *in_shape, device=W.device), W ** 2, padding=1) # ||fila||^2 de cada salida
return s, row_sq.sum().sqrt().item(), row_sq.sqrt().sum().item(), row_sq.numel()
def spectral_stats(model, kind):
layers = [m for m in model if isinstance(m, (nn.Linear, nn.Conv2d))]
shapes = IN_SHAPES[kind] or [None] * len(layers)
rows = [layer_norms(l, sh) for l, sh in zip(layers, shapes)]
spec = [r[0] for r in rows]
lip = math.prod(spec)
R_A = lip * sum((r[2] / r[0]) ** (2 / 3) for r in rows) ** 1.5 # ec. (1.2) con M_i = 0
W_max = max([3072] + [r[3] for r in rows])
return {'spectral': spec, 'frobenius': [r[1] for r in rows], 'l21': [r[2] for r in rows],
'lipschitz': lip, 'R_A': R_A, 'W': W_max}
@torch.no_grad()
def margins_and_error(model, X, y):
model.eval()
out = torch.cat([model(X[i:i + 1000]).float() for i in range(0, len(X), 1000)])
model.train()
true = out.gather(1, y[:, None])[:, 0]
other = out.scatter(1, y[:, None], float('-inf')).max(1).values
return (true - other), (out.argmax(1) != y).float().mean().item(), F.cross_entropy(out, y).item()
# ---------------------------------------------------------------- entrenamiento hasta ajustar
def run(kind, p, seed):
y = corrupt(p, seed)
torch.manual_seed(seed)
model = (make_mlp() if kind == 'mlp' else make_cnn()).to(device)
opt = torch.optim.SGD(model.parameters(), lr=LR, momentum=MOMENTUM)
g = torch.Generator(device=device).manual_seed(seed)
curve, fit_epoch = [], None
for ep in range(1, MAX_EPOCHS + 1):
perm = torch.randperm(N_TRAIN, device=device, generator=g)
for i in range(0, N_TRAIN, BATCH):
b = perm[i:i + BATCH]
loss = F.cross_entropy(model(Xtr[b]), y[b])
opt.zero_grad(set_to_none=True)
loss.backward()
opt.step()
_, tr_err, ce = margins_and_error(model, Xtr, y)
if fit_epoch is None and tr_err == 0:
fit_epoch = ep
if ep in (1, 2, 3, 5, 7) or ep % 10 == 0 or ce <= CE_STOP or ep == MAX_EPOCHS:
_, te_err, _ = margins_and_error(model, Xte, yte)
curve.append({'epoch': ep, 'train': tr_err, 'test': te_err, 'ce': ce})
if ce <= CE_STOP:
break
marg, tr_err, ce = margins_and_error(model, Xtr, y)
_, te_err, _ = margins_and_error(model, Xte, yte)
st = spectral_stats(model, kind)
n = N_TRAIN
gamma = torch.quantile(marg, 0.10).item() # margen que deja un 10 % de puntos por debajo
ramp = (marg <= gamma).float().mean().item()
complexity = X_NORM * st['R_A'] / (gamma * n) # término de BFT sin factores logarítmicos
bound = ramp + 8 / n + 72 * complexity * math.log(2 * st['W']) * math.log(n) + 3 * math.sqrt(math.log(1 / DELTA) / (2 * n))
norm_m = (marg / (st['R_A'] * X_NORM / n)).cpu().numpy()
res = {'model': kind, 'noise': p, 'seed': seed, 'fit_epoch': fit_epoch, 'epochs': curve[-1]['epoch'],
'steps': curve[-1]['epoch'] * math.ceil(n / BATCH), 'train_err': tr_err, 'test_err': te_err,
'wrong_labels': (y.cpu() != y_clean).float().mean().item(), 'gamma': gamma, 'margin_err': ramp,
'complexity': complexity, 'bound': bound, 'curve': curve,
'norm_margin_q': np.quantile(norm_m, np.linspace(0, 1, 41)).tolist(), **st}
del model, opt
if device.type == 'cuda':
torch.cuda.empty_cache()
return res
results = {'config': {'n_train': N_TRAIN, 'n_test': N_TEST, 'max_epochs': MAX_EPOCHS, 'lr': LR, 'momentum': MOMENTUM,
'batch': BATCH, 'delta': DELTA, 'x_norm': X_NORM, 'short': SHORT}, 'runs': []}
t0 = time.time()
for kind in ['mlp', 'cnn']:
for p in NOISES:
for seed in SEEDS:
r = run(kind, p, seed)
results['runs'].append(r)
print(f"{kind} p={p:.1f} s={seed}: ajusta en época {r['fit_epoch']}, para en {r['epochs']}, test {r['test_err']:.3f}, "
f"Lip {r['lipschitz']:.3g}, R_A {r['R_A']:.3g}, gamma {r['gamma']:.3g}, "
f"cota {r['bound']:.3g} [{time.time() - t0:.0f} s]")
OUT.write_text(json.dumps(results), encoding='utf-8')
print('guardado en', OUT)npm run lab and open the connection link.Fitting random labels takes only modestly longer. On real labels, the MLP reaches zero training error at epochs 38 and 48, one per seed. On fully random labels it takes 60 and 68. The CNN takes 22 and 21 versus 38 and 36. This is the small factor seen by Zhang et al., between and times as many epochs. Test error approaches chance. The MLP goes from test error on real labels to , and at , and . The CNN goes from to , and . Both train with 10,000 images and without data augmentation. The bound increases with noise. The MLP mean goes from for real labels to , and , in order and differing by a factor of between endpoints. Its spectral-norm product rises from 47 to 72 as the tenth-percentile margin barely changes, from to . For the CNN the sequence is , , and . It separates real from noisy labels, but between and the mean differs by , less than the gap between seeds, while test error jumps from to . The normalized-margin distributions show more detail. In the MLP the median drops from , averaged across seeds, to . The curves move left as noise increases, as in Bartlett et al., Figure 2b.
Holding architecture and hyperparameters fixed while adding noise increases the bound, which demonstrates its data dependence. Its absolute values and exceed 1, making the error guarantees vacuous, and the ratio between endpoints, 1.5 or 1.4, is much smaller than the observed difference in generalization. The full results in the source study show a similar separation for AlexNet on CIFAR-10 at the end of training (Figure 2b). Use the full dataset and three seeds before drawing conclusions about small differences.
Empirical measures of generalization
A vacuous bound can still be useful if it ranks models correctly as hyperparameters change. Jiang, Neyshabur, Mobahi, Krishnan and Bengio (2020) tested this with more than 10,000 convolutional networks trained on CIFAR-10 and SVHN, varying seven hyperparameters systematically. They studied more than 40 complexity measures and used rank correlations designed to distinguish causal relationships from spurious ones. PAC-Bayes and sharpness measures performed best overall. Sharpness measures how much the loss rises when weights are perturbed, as discussed in the flatness lesson. Spectral complexity correlated negatively with generalization across hyperparameter types, especially changes in depth. Path norm performed well, and several optimization measures such as training speed had substantial predictive value.
Dziugaite, Drouin, Neal, Rajkumar, Caballero, Wang, Mitliagkas and Roy (2020) argued that average performance can hide systematic failure under a particular intervention. They evaluated 24 measures over more than 1,600,000 experiment pairs using robust sign error, a worst-case score over environments where just one hyperparameter changes. No measure beat chance by this statistic. Every measure had at least one environment where it consistently predicted the wrong direction. Most families predicted sample-size effects, though some Frobenius-based measures grew with for shallow, narrow networks. Depth and width were difficult for all measures, with some PAC-Bayes measures robust in a substantial fraction of environments. Norm-based measures did best when learning rate changed.
Limits of uniform convergence
The bounds in this lesson and nearly all those in this module use uniform convergence. They bound over a class and apply the result to the learned predictor. The random-label experiment already shows why cannot include the full architecture without giving a vacuous bound. A natural approach is to narrow the class to predictors the algorithm actually returns on typical samples, perhaps using bounded norms, proximity to initialization or large margins. Nagarajan and Kolter (2019) showed that even the tightest version of this approach fails in simple examples.
A set of probability can exclude rare samples. The definition requires one set of probability shared by all predictors, rather than a different set for each . The limits of uniform convergence appear when an algorithm generalizes well and yet is close to 1.
The linear example
Inputs are with and . Label is uniform. Set for fixed with . The noise is independent of everything else. Starting from the origin, the algorithm takes one gradient step of size 1 to maximize with . This gives and . The margin of a point is
because .
- Training. For training point , . Every point is classified correctly with a large margin.
- Test. is independent of , so with . Its standard deviation is , below 4 when . Test error is small.
- Noise-negated sample. In each margin is . The classifier trained on gets every point wrong.
Crucially, has exactly the same distribution as because the Gaussian noise is symmetric. If has probability with small , then for most samples , both and lie in . Both are typical. Then and , so the definition forces
Theorem 3.1 of Nagarajan and Kolter states that for every with , if , generalization error is at most and still . This holds for 0–1 loss and margin losses with .
def nagarajan_kolter(m, D, rng, n_test=2000):
"""Clasificador lineal de un paso de gradiente: margen y h(x) = 4 + y w2.x2 (sección 3.1 de N&K)."""
y = rng.choice([-1.0, 1.0], m)
X2 = rng.standard_normal((m, D)) * np.sqrt(32 / D) # ruido de alta dimensión
w2 = y @ X2 # w2 = sum_i y_i x2_i (y w1 = 2 m u)
s = (y[:, None] * X2) @ w2 # y_j w2.x2_j
train = 4 + s # margen en S
neg = 4 - s # margen en S' = {((x1, -x2), y)}
# en test, x2 es independiente de w2: y w2.x2 ~ N(0, ||w2||^2 32/D) exactamente
test = 4 + np.linalg.norm(w2) * np.sqrt(32 / D) * rng.standard_normal(n_test)
return [np.mean(v <= 0) for v in (train, test, neg)]
rng = np.random.default_rng(0)
print(f"{'m':>4} {'D':>6} {'error S':>8} {'test':>6} {'error S_':>8}")
for m, D in [(64, 512), (64, 4096), (64, 16384), (128, 16384)]:
tr, te, ng = nagarajan_kolter(m, D, rng)
print(f'{m:4d} {D:6d} {tr:8.3f} {te:6.3f} {ng:8.3f}')With and , test error is and error on is . With , test error increases to and every point of remains misclassified. Doubling at fixed , with and , raises test error to , as predicted by standard deviation . The theorem thus needs on the order of .
Neural networks and sample size
Nagarajan and Kolter repeat the argument with a two-layer ReLU network and hidden units. Inputs lie on two concentric spheres of radii 1 and 1.1 in . They train with SGD at learning rate 0.1 and batch size 64 until of points has margin at least 10. With between and , test error falls like . Every point of the sample is misclassified. Projecting each point onto the other sphere and flipping the label preserves the data distribution. The paper finds a related pattern in five-layer, width-1024 networks on MNIST trained by batch-size-one SGD to the same margin criterion. Test error falls like while distance from initialization and the product of spectral norms grow with . Bounds based on these quantities grow like . Such a bound worsens as sample size grows, even as observed error improves.
The argument targets two-sided bounds, which also bound . The paper shows that PAC-Bayes bounds, usually stated one-sided, become nearly vacuous in its examples. Other avenues include analyzing stability for the actual data and algorithm, sample-dependent information bounds, or direct analysis of the predictor. Bartlett et al.’s linear regression analysis is an example of the last approach: it computes the minimum-norm interpolator’s risk without uniform convergence.
Open problems
- A theory of interpolating networks. The taxonomy is understood for linear models and kernels with known spectra. Networks trained to interpolate with SGD appear tempered in Mallinar et al.’s experiments. A theory that predicts the cost of memorized noise from the architecture and data is still open.
- Nonvacuous bounds that rank models. Optimized PAC-Bayes bounds are nonvacuous in some settings. None of the measured quantities passes Dziugaite et al.’s robust sign error test.
- Beyond uniform convergence. The examples motivate studying a particular algorithm on its data. Bartlett, Montanari and Rakhlin (2021) survey the limits of uniform convergence, implicit regularization in gradient descent, benign interpolation and the linear regime of networks.
- The role of memorization. Feldman explains why memorization can help in long-tailed populations. Determining how much a network needs to memorize, and how much is avoidable tempered error, remains an empirical question with privacy consequences.
Common mistakes
Exercises
Step 1 of 4. What is ?
More than one answer may be correct.
effective_ranks(eigs, k). It takes covariance eigenvalues as a nonnegative array in any order and an integer . Return with and , using descending eigenvalues and indices starting at 1 in the formulas and 0 in code. Leave the input array intact. The tests use constant, geometric, and power-law spectra with closed-form results.import numpy as np
def effective_ranks(eigs, k):
"""Devuelve (r_k, R_k) de los autovalores eigs (en cualquier orden)."""
raise NotImplementedErrorSummary
- Zhang et al. (2017) found that the same networks reached zero training error on real and random labels, with only a modest increase in training time. Bounds based only on the class or algorithm and must cover the random case and can be vacuous.
- In Bartlett, Long, Lugosi and Tsigler’s theorem, for , if and , minimum-norm risk is bounded up to constants and confidence factors by . The upper and lower bounds on the variance term match in order.
- The covariance tail absorbs noise across many low-variance directions () and induces a ridge penalty of size on signal directions.
- Mallinar et al.’s taxonomy distinguishes benign (), tempered (a finite plateau) and catastrophic () behavior. 1-NN (excess ), unregularized Laplace ( in 1D) and the studied interpolating networks are tempered. Singular-kernel Nadaraya–Watson is benign and unregularized Gaussian interpolation is catastrophic.
- In Feldman’s long-tailed distributions, skipping memorization costs in error per singleton. With Zipf frequencies and , it costs four error points for two classes.
- Spectrally normalized margin bounds depend on data and rise with label noise, but are vacuous by many orders of magnitude. In large-scale studies no measure robustly predicts generalization across interventions.
- Nagarajan and Kolter exhibit algorithms with generalization error and a tightest uniform bound of at least , even when the class is restricted to the algorithm’s outputs.