Random matrices: the spectrum of noise, data and neural networks
Understand random-matrix spectra, the Wigner and Marchenko–Pastur laws, BBP transitions, covariance cleaning and neural-network applications.
After this lesson you can
- Compare classical and proportional spectral limits.
- Derive semicircle moments and interpret the Marchenko–Pastur law.
- Analyze spike detection and eigenvector overlap across the BBP threshold.
- Clean correlation matrices and compare realized portfolio risk.
- Interpret network spectra using appropriate controls and assumptions.
Before you start
- 02Spectral theoremSingular value decompositionPositive definite matrixEckart-Young-Mirsky theoremNumerical rankCondition number of a matrixTraceGram matrixRayleigh quotientLow-rank approximation
- 04Weak law of large numbersCentral limit theoremCovariance matrixCovariance estimation errorConcentration of the normConcentration on the sphere
Motivation: as many variables as observations
Classical statistics reasons as follows: with observations from a distribution with covariance , the sample covariance converges to as by the law of large numbers. This convergence holds with fixed. In relevant problems and have the same order: 500 assets with 1000 trading days, 20 000 genes with 300 patients, a weight matrix whose learning you want to understand. Here is not a slightly blurry . It is something else, with a precise shape, and this lesson studies that shape.
Start with the most boring case possible: Gaussian data without any structure, . Everyone expects to resemble identity, eigenvalues clustered at 1. See what happens.
Three features of the figure govern the rest of the lesson.
- Eigenvalues of are not those of . All of equal 1, while those of spread between and with . The largest overestimates and the smallest underestimates, turning a matrix with condition number 1 into one with condition number near 14.
- A large eigenvalue of does not prove structure. There is none here and the largest eigenvalue is . Distinguishing signal from noise requires knowing how far noise reaches.
- But that noise has a predictable, exact shape. The continuous curve is not fitted to data: it uses only . Knowing where the bulk ends helps identify which eigenvalues are noise and which are not.
This is what random matrices offer a data specialist:
- Finance. A minimum-variance portfolio uses , amplifying precisely the smallest-eigenvalue directions, most contaminated by noise. With that portfolio’s actual risk is 41 % above optimum, even with no anomalies in the data.
- PCA. How many principal components are structure and how many noise? The answer has an exact threshold, the BBP transition.
- Neural networks. A newly initialized weight matrix is random. If after training its spectrum resembles the one above, training has left no mark; if it differs, the nature of the mark remains to be established. Signal propagation through a deep network depends on singular values of a random-matrix product.
We first cover vocabulary (spectral distribution and proportional regime), then two fundamental results (Wigner’s semicircle and Marchenko–Pastur laws), then the BBP transition specifying when signal survives noise, and finally applications (correlation cleaning and network weights) and a guide to reading the literature without confusing theorem with intuition.
Empirical spectral distribution and the proportional regime
A symmetric matrix has real eigenvalues by the spectral theorem. As grows there is no single number they converge to, but a cloud condensing into a curve. The tool capturing that curve is the measure placing mass at each eigenvalue.
Equality of moments and traces bridges two worlds. An eigenvalue is an implicit quantity, a root of a degree- polynomial. But is a sum of products of entries, which can be averaged over randomness by counting. This is the moment method used for Wigner.
We must specify how the matrix grows. There are two asymptotic regimes; confusing them is the root of most misunderstandings in the area:
- Classical regime. fixed and . Here in any norm and each eigenvalue of converges to that of .
- Proportional regime (or high-dimensional). with . Now does not converge to in norm: with we have (we will see why), which vanishes only if . This is the precise content of the covariance-estimation error bound, of order : random matrix theory supplies the constant.
What does occur, and is the remarkable feature of this theory, is that a large random matrix’s ESD ceases to be random: it converges to a deterministic measure. The spectrum is said to self-average. One matrix of size 2000 suffices; averaging many realizations is unnecessary, as the second figure shows. The reason is concentration of measure (norm concentration): linear spectral statistics such as fluctuate , much less than any entry.
Wigner’s semicircle law
The simplest symmetric random matrix is a table of Gaussian numbers, symmetrized.
Normalization makes the result exist: a row of has variance-one entries, so its squared norm is of order and the matrix stretches by . Dividing by leaves eigenvalues in a fixed interval. Another normalization makes the histogram escape to infinity or collapse to 0. (Uniformly bounded moments of all orders are the classical proof’s assumption; for iid off-diagonal entries, truncation makes finite variance sufficient for ESD convergence, though not for largest-eigenvalue behavior, as we will see.)
The moment method: where Catalan numbers come from
The previous figure showed , , , and that odd moments are 0 by symmetry. These are the Catalan numbers , namely for . This is precisely the proof’s outline.
The semicircle moments are Catalan numbers. With , and ,
Use in the second equality, and in the third, giving . Odd moments are 0 by symmetry of .
Now the matrix moments. By the trace definition,
Each summand is a closed walk on indices , traversing edges . Since entries are independent and centered, a walk contributes only if every edge is traversed at least twice. Count by the number of distinct indices in the walk:
- If every edge is used at least twice there are at most distinct edges, and a connected graph with vertices has at least edges, hence . There are order walks with distinct indices, with bounded expectation (finite moments), so walks with contribute .
- Only survive (requiring even): the graph has exactly edges, is a tree, and each edge is traversed exactly twice, once each way. Each contributes .
It remains to count closed walks of steps traversing a tree of edges, each outward and back. Moving “outward” adds and returning subtracts : the walk is a path of length rising and falling by one, starting and ending at 0 and never going below 0. These Dyck paths are counted by Catalan numbers . Also choosing labels for vertices gives . Therefore
Since the semicircle has compact support it is determined by its moments, and moment convergence implies convergence in distribution. To pass from expectation to almost-sure convergence, verify the variance of is , summable, and apply Borel–Cantelli. You will work out small cases and in the guided proof exercise. For GOE they are exact: and , so at the fourth moment averages rather than (checked in the first code cell).
Simulating size 2000 in the browser
Diagonalizing an matrix costs order operations, too much for animation. For the figure uses a result by Dumitriu and Edelman (2002): GOE eigenvalues have exactly the same distribution as those of a symmetric tridiagonal matrix with diagonal and subdiagonal (chi variables with those degrees of freedom), all independent. A tridiagonal matrix has only numbers and its eigenvalues take . You implement it with scipy in the library section.
The Marchenko–Pastur law
We move from symmetric matrices to covariance matrices. Let have independent entries of mean 0 and variance 1, and
be its sample covariance when true covariance is and the mean is known. A convention warning: here, as in random matrix literature, observations are the columns of , the transpose of the rest of the course’s design matrix. is a Gram matrix and thus positive semidefinite; its eigenvalues are squared singular values of (SVD). With Gaussian entries it is called a Wishart matrix.
The motivation figure is exactly this theorem with . Several facts visible there and in the formula:
- Edges are . For they are and . For , and . The largest eigenvalue of overestimates the true one (1) by and the smallest underestimates it. This gives the promised result: (for entries with finite fourth moment; valid for all , because if , and if the smallest eigenvalue is 0 and ).
- Conditioning. For the condition number of tends to : for , for and over for . It diverges as , with identity as truth.
- Atom. If , , so at least eigenvalues are 0 and their proportion is . The nonzero eigenvalues of match those of matrix , with ratio : the laws are linked by this duality.
- Moments. Law mean is 1, its second moment and third . The second is calculated by hand in the Gaussian case: . Spectral variance is therefore : noise grows with the ratio.
- Scale. With variance the entire spectrum is multiplied by . Thus noise level can be estimated from the edge, as in the code exercise.
Where the edges come from: the Stieltjes transform
One way to obtain the law and understand its edges is the Stieltjes transform of a measure ,
It is an analytic function containing the whole measure: is recovered by inversion formula , density of at . For Marchenko–Pastur with one proves (removing one observation and applying the Schur complement) that satisfies a quadratic equation
Solving gives . The square root is real for outside the interval where , and imaginary inside. There the density appears: , and since , dividing by gives exactly the definition’s density. Edges are zeros of the discriminant, , namely . The whole result lies in one quadratic equation, which will shortly calculate the BBP transition.
Universality and its limits
The theorem requires only zero mean and finite variance: the law does not depend on entry distribution. This is universality, a kind of central limit theorem for spectra, visible in the motivation figure when switching Gaussian to Rademacher: the histogram is the same. But there is a caveat. The ESD (bulk) is universal with finite variance, whereas the edge is not: a classical Bai, Yin and colleagues result (1988) says almost surely if and only if . With Student with degrees of freedom (finite variance, infinite fourth moment), the histogram remains Marchenko–Pastur, but isolated eigenvalues appear far beyond , as the figure shows. For real heavy-tailed data such as financial returns, an eigenvalue above the MP edge therefore does not prove structure.
The spiked model and BBP transition
Until now there was nothing to find. Add signal. The simplest model with one privileged direction is the spiked covariance model (Johnstone 2001): all variables are variance-one noise except direction with greater variance.
One true eigenvalue has separated from the others; can we see it? A rank-one perturbation changes ESD by , so the bulk remains Marchenko–Pastur. All that can change is one eigenvalue leaving the bulk. Surprisingly, the answer is all or nothing with an exact threshold.
The BBP paper describes fluctuations of the largest eigenvalue around the threshold (with the Tracy–Widom law for complex data); first-order limits stated in the theorem are due to Baik and Silverstein (2006), Paul (2007), and Benaych-Georges and Nadakuditi (2011) in a more general framework. Before the proof, see the theorem in action.
Why that value: the secular equation
Deriving the limit of is short using the preceding Stieltjes result. Write with Marchenko–Pastur . Matrices and are similar, so is an eigenvalue of if and only if . If is not an eigenvalue of (it is outside the bulk), the rank-one determinant lemma, with , and , gives
where was used. Randomness enters here: since has rotationally invariant distribution, concentrates at its average over directions, . The equation reduces to , namely,
Substituting in and multiplying by gives , linear in , with solution
When is it valid? Function has derivative , vanishing at with value . But substitution in the quadratic is insufficient: check that is the correct transform branch. Better inspect equation with . For , is continuous and strictly decreasing, tends to 0 at and equals at the edge (zero discriminant, ). Thus a unique solution exists if and only if , namely , and then it is , increasing on that branch and above . For no solution lies outside the bulk: no outlier eigenvalue. The threshold is where the secular equation ceases to have a solution outside the bulk. This is a physicist’s derivation: the rigorous version justifies quadratic-form concentration and absence of eigenvalues of outside the bulk (Bai and colleagues), and handles the real case carefully. Overlap follows by differentiating the same equation with respect to ; we omit it.
Implications for PCA
- There is a detection threshold. With () a spike is visible only if its added variance exceeds noise variance, . With , if . Below it the eigenvalue lies in the bulk and cannot be distinguished from noise; one can prove (Onatski, Moreira and Hallin, 2013) that no test in this regime distinguishes “spike” from “no spike” with power tending to 1: the best attains power only somewhat above its level.
- The estimator is biased and can be corrected. Since is quadratic in , strength is recovered from with . With and this gives .
- The eigenvector is inconsistent. Even above threshold, : with and it is , an angle of . It tends to 1 only when or (for large , ). What we call “first principal component” with is rotated a finite amount from truth.
- With several separated spikes, each has its own threshold. Counting eigenvalues above (with estimated ) reasonably estimates component count, but has a fuzzy edge: the edge fluctuates , so the figure’s transition is rounded with .
In low-rank approximation language: Eckart–Young says the best rank- approximation retains the largest singular values, but not how many are signal. BBP does: those above and no more (up to fluctuations), replacing numerical rank by statistical rank.
Cleaning correlation matrices
Quantitative finance was where this theory first paid off. The correlation matrix of stocks is estimated with days and used to construct portfolios, so . The canonical problem is the minimum-variance portfolio: with unit-volatility returns and correlation ,
is unknown and sample correlation is used instead. Inverting, is dominated by smallest eigenvalues, directions that looked quiet in sample, precisely those most contaminated by noise (lower edge is much smaller than 1). The optimizer places weight where chance reported little risk. With and Gaussian data one proves and verifies by simulation that
so realized risk is times what the portfolio promises. With , twice the promise; with , four times. The portfolio optimized on the raw matrix promises more than it can deliver by construction, and the gap grows with .
The eigenvalue-clipping cleaning recipe by Laloux, Cizeau, Bouchaud and Potters (1999) uses Marchenko–Pastur to decide which spectrum can be trusted:
- Diagonalize .
- Calculate bulk edge . Correlations have trace and real factors take part of it, so noise has : fit by fixed point, , iterating with new until unchanged.
- Retain eigenvalues above and replace all others by their mean, preserving trace.
- Reconstruct the matrix and renormalize its diagonal to 1.
In the figure true structure has three large eigenvalues (market and two sector contrasts: the three sector indicators span a 3-dimensional space) and the rest of is white noise with variance . With default strength and , clipping retains those three on average (in 100 simulations with ), fits (true is ), and cleaned portfolio realized risk is 8 % above optimum versus 38 % for raw (slightly below asymptotic of ). With raw reaches about times optimum and cleaned remains . If strength is lowered to , clipping retains only market, but cleaned remains around : a sector too weak to emerge from the bulk added little to the portfolio.
Random matrices inside networks
A neural network is a stack of weight matrices, all initially random. This makes the theory a reading tool for two distinct questions: what happens at initialization (whether signals and gradients survive many layers) and what the weight spectrum says after training.
A newly initialized layer is a Marchenko–Pastur matrix
A linear layer initialized with entries is with having entries . Then
is exactly the previous section’s matrix, with , and . Its squared singular values follow Marchenko–Pastur with , and singular values of fill interval . A square layer with () preserves length only on average: it doubles some directions and nearly collapses others to 0. One layer is not the issue. A deep network is.
Matrix products and dynamical isometry
Propagating a signal through linear layers of units gives output–input Jacobian product , traversed transposed by backpropagation gradients. Its singular values govern gradient explosion or vanishing. For square Gaussian matrices the spectrum of has upper edge (the Fuss–Catalan law, giving 4 for , the Marchenko–Pastur edge with ), order for large . But this describes the few largest singular values. The typical value sinks: median singular value decays exponentially with , so nearly all directions vanish while a few explode. The Jacobian is poorly conditioned at moderate depth.
Pennington, Schoenholz and Ganguli (2017) call dynamical isometry the concentration of the entire singular spectrum of near 1, analyzing it with free random matrices including nonlinearities. For the linear case the remedy is immediate: a product of orthogonal matrices is orthogonal and all singular values equal 1 exactly. Their analysis finds dynamical isometry with and orthogonal weights (properly scaled), but not with ReLU. The code section measures the linear case.
Trained networks: observations and conclusions
The second question is subtler. Martin and Mahoney (2021) study empirical spectra of weight matrices in trained networks. They observe that, depending on layer training, the spectrum shifts from Marchenko–Pastur-like (as at initialization) to a bulk with outliers and, in well-trained layers of large networks, a heavy tail fitted to power law . Later work (Martin, Peng and Mahoney, 2021, Nature Communications) proposes metrics based on exponent as a quality indicator without test data, used to compare pretrained models. Their results are empirical and interpretation is debated: heavy tails can arise from different mechanisms, and fitting a power law to a few dozen eigenvalues is statistically delicate.
Rather than trust appearances, measure. The next cell (with GPU) trains a small multilayer perceptron on MNIST twice from the same initialization: once with true labels and once with random labels (same images with unrelated labels, which cannot generalize). For each layer it calculates spectrum and compares it with Marchenko–Pastur using estimated from its own entry variance.
import copy, os, time
import numpy as np
import matplotlib.pyplot as plt
import torch, torch.nn as nn
from torchvision import datasets
t0 = time.time()
torch.manual_seed(0)
dev = "cuda" if torch.cuda.is_available() else "cpu"
root = os.path.join(os.path.expanduser("~"), ".cache", "atlas-data") # MNIST se descarga la primera vez (unos 11 MB)
tr = datasets.MNIST(root, train=True, download=True)
te = datasets.MNIST(root, train=False, download=True)
prep = lambda d: ((d.data.float() / 255 - 0.1307) / 0.3081).view(-1, 784).to(dev)
Xtr, ytr, Xte, yte = prep(tr), tr.targets.to(dev), prep(te), te.targets.to(dev)
def mlp():
return nn.Sequential(nn.Linear(784, 512), nn.ReLU(), nn.Linear(512, 512), nn.ReLU(), nn.Linear(512, 10)).to(dev)
def entrenar(modelo, etiquetas, epocas=20, lr=0.05, lote=128):
opt = torch.optim.SGD(modelo.parameters(), lr=lr, momentum=0.9)
for _ in range(epocas):
perm = torch.randperm(len(Xtr), device=dev)
for i in range(0, len(Xtr), lote):
idx = perm[i:i + lote]
perdida = nn.functional.cross_entropy(modelo(Xtr[idx]), etiquetas[idx])
opt.zero_grad(); perdida.backward(); opt.step()
with torch.no_grad():
return (modelo(Xtr).argmax(1) == etiquetas).float().mean().item(), (modelo(Xte).argmax(1) == yte).float().mean().item()
inicial = mlp()
verdaderas, aleatorias = copy.deepcopy(inicial), copy.deepcopy(inicial)
print("etiquetas verdaderas: (acierto en entrenamiento, acierto en test) =", tuple(round(a, 3) for a in entrenar(verdaderas, ytr)))
barajadas = ytr[torch.randperm(len(ytr), device=dev)] # las mismas imágenes con etiquetas sin relación
print("etiquetas aleatorias: (acierto en entrenamiento, acierto en test) =", tuple(round(a, 3) for a in entrenar(aleatorias, barajadas)))
def mp_density(x, gamma, sigma2):
lo, hi = sigma2 * (1 - np.sqrt(gamma)) ** 2, sigma2 * (1 + np.sqrt(gamma)) ** 2
out = np.zeros_like(x)
ok = (x > lo) & (x < hi)
out[ok] = np.sqrt((hi - x[ok]) * (x[ok] - lo)) / (2 * np.pi * gamma * sigma2 * x[ok])
return out
def espectro(W):
"""Autovalores de la matriz de Gram pequeña de W (los no nulos de W W^T)."""
W = W.detach().double().cpu().numpy()
G = W @ W.T if W.shape[0] <= W.shape[1] else W.T @ W
return np.linalg.eigvalsh(G)
def alfa_hill(ev, xmin):
"""Estimador de máxima verosimilitud (Hill) del exponente de una cola de potencias, con xmin dado."""
x = ev[ev >= xmin]
return 1 + len(x) / np.sum(np.log(x / xmin)) if len(x) >= 10 else float("nan")
print(f"\n{'capa':>11} {'modelo':>11} {'|W|/|W0|':>9} {'|W-W0|/|W0|':>12} {'λmax/borde':>11} {'sobre borde':>12} {'α (Hill)':>9}")
fig, ejes = plt.subplots(1, 3, figsize=(11, 3.2), sharey=True)
with torch.no_grad():
for li in (0, 2):
W0 = inicial[li].weight
d_out, d_in = W0.shape
gam, grande = min(d_out, d_in) / max(d_out, d_in), max(d_out, d_in)
for j, (nombre, modelo) in enumerate((("inicial", inicial), ("verdaderas", verdaderas), ("aleatorias", aleatorias))):
W = modelo[li].weight
ev = espectro(W)
s2 = float((W.double() ** 2).mean()) * grande # varianza de las entradas, escalada: el sigma² de MP
borde = s2 * (1 + np.sqrt(gam)) ** 2
n_sobre = int((ev > borde).sum())
a = alfa_hill(ev, borde)
print(f"{str(tuple(W.shape)):>11} {nombre:>11} {float(W.norm() / W0.norm()):9.2f} {float((W - W0).norm() / W0.norm()):12.2f} {ev[-1] / borde:11.2f} {n_sobre:12d} {a:9.2f}")
if li == 2:
u = np.log10(ev / s2)
ejes[j].hist(u, bins=40, density=True, alpha=0.7)
xs = np.linspace(u.min(), max(u.max(), 0.6), 400)
ejes[j].plot(xs, mp_density(10 ** xs, gam, 1.0) * 10 ** xs * np.log(10), "k")
ejes[j].axvline(np.log10((1 + np.sqrt(gam)) ** 2), ls="--", c="gray")
ejes[j].set_title(nombre); ejes[j].set_xlabel("log10(λ / σ²), σ² de las entradas")
ejes[0].set_ylabel("densidad")
plt.tight_layout(); plt.show()
print(f"[{time.time() - t0:.0f} s]")npm run lab and open the connection link.Column λmax/borde divides the largest eigenvalue by the Marchenko–Pastur edge with from that matrix’s own entries, and sobre borde counts eigenvalues above it. Results from one run (yours will vary somewhat with GPU and system):
| Layer | Model | /edge | above edge | |||
|---|---|---|---|---|---|---|
| initial | 1.00 | 0.00 | 0.99 | 0 | n/a | |
| true | 1.60 | 1.21 | 5.4 | 30 | 2.2 | |
| random | 3.53 | 3.25 | 5.1 | 51 | 3.2 | |
| initial | 1.00 | 0.00 | 1.01 | 1 | n/a | |
| true | 1.30 | 0.75 | 6.1 | 15 | 2.1 | |
| random | 3.17 | 2.88 | 10.3 | 16 | 4.4 |
The true-label network reaches training accuracy and test accuracy; the random-label network reaches and (memorizing part of training without generalizing). What the numbers do and do not say:
- Initialization matches theory. With and at most one eigenvalue above the edge, the initial spectrum is Marchenko–Pastur with entry variance. This checks theory and cell.
- Training drives eigenvalues out of the bulk, 5 to 10 times the edge and dozens of them, in both networks. This is a matrix fact: training added structure to (low-rank or heavy-tailed) that independent noise with that variance does not explain.
- But the random-label network moves farther from initialization ( times versus ) and has as many or more outliers. A non-MP spectrum does not prove generalizable learning. It proves weights moved.
- The Hill exponent does separate the two cases here (2.1 and 2.2 for true labels, 3.2 to 4.4 for random), in the direction predicted by Martin and Mahoney. But with one network per case, one optimizer, 15 to 50 tail points and manually fixed , the estimator’s typical error ranges from to , and a tail fit to a few dozen eigenvalues poorly distinguishes a power law from other tails.
That is the methodological lesson: always check with a control (here, random labels) before reading meaning into spectral shape.
How to read a random matrix paper
The literature mixes four kinds of claim that look similar but guarantee different things. For a first pass, ask which kind each statement is.
| Type | Example | What to check |
|---|---|---|
| Theorem | “The ESD of converges almost surely to MP” | Assumptions (independence, moments, normalization), convergence type (weak, almost sure, in probability) |
| Asymptotic result used at finite size | “ implies signal” | Values of and , edge fluctuations (), approximation quality at actual size |
| Heuristic derivation | Replicas, cavity method, the secular equation above | Which step lacks justification; subsequent numerical or rigorous verification |
| Empirical evidence | “ correlates with test accuracy” | Model count, controls (random labels, other optimizers), whether relation is causal |
A checklist for each result:
- Which ensemble and normalization? is not , and is not . Many apparent contradictions between papers are normalization differences.
- Which regime? fixed, finite, or . Results do not transfer automatically.
- What converges? Bulk (ESD), extreme eigenvalues, eigenvectors and fluctuations are different results with different assumptions (edge needs a fourth moment, bulk does not).
- What is assumed about entries? Independence, equal variance, finite moments. Real data have dependence across variables and time and heavy tails.
- How large is “large”? If a paper simulates with , the edge is fuzzy by or ; if it discusses , it is not.
- What is proved and what is analogy? Much statistical physics of networks uses random matrices heuristically, sometimes without a theorem.
Implementation from scratch
First simulate the Wigner semicircle, comparing moments against Catalan numbers. In the cell’s second part, averaging many small matrices confirms exact GOE corrections and .
import numpy as np
from math import comb
rng = np.random.default_rng(0)
def wigner(n, rng):
"""GOE: fuera de la diagonal varianza 1, en la diagonal varianza 2."""
G = rng.normal(size=(n, n))
return (G + G.T) / np.sqrt(2)
def semicirculo(x):
return np.sqrt(np.clip(4 - x**2, 0, None)) / (2 * np.pi)
def catalan(j):
return comb(2 * j, j) // (j + 1)
n = 200
ev = np.linalg.eigvalsh(wigner(n, rng) / np.sqrt(n))
print(f"n = {n}: λmin = {ev[0]:.3f}, λmax = {ev[-1]:.3f} (el semicírculo acaba en ±2)")
for k in (2, 4, 6, 8):
print(f" m_{k} = {np.mean(ev**k):6.3f} Catalan C_{k // 2} = {catalan(k // 2)}")
# promedio sobre muchas matrices pequeñas: E[m2] = 1 + 1/n y E[m4] = 2 + 5/n + 5/n²
n_small, reps = 40, 150
m = np.array([[np.mean(np.linalg.eigvalsh(wigner(n_small, rng) / np.sqrt(n_small)) ** k) for k in (2, 4)] for _ in range(reps)])
print(f"\nn = {n_small}, {reps} matrices: m2 = {m[:, 0].mean():.3f} (1 + 1/n = {1 + 1/n_small:.3f}), m4 = {m[:, 1].mean():.3f} (2 + 5/n + 5/n² = {2 + 5/n_small + 5/n_small**2:.3f})")With the second and fourth moments match Catalan within tenths of a percent and a few percent (higher moments fluctuate more: order 8 differs by for one matrix), and smallest and largest eigenvalues are within of , as distance predicts. Now Marchenko–Pastur: density, its distribution function (numerical quadrature), Kolmogorov distance of spectrum to theory for four entry distributions, and the atom at 0 when .
def mp_edges(gamma, sigma2=1.0):
return sigma2 * (1 - np.sqrt(gamma)) ** 2, sigma2 * (1 + np.sqrt(gamma)) ** 2
def mp_density(x, gamma, sigma2=1.0):
lo, hi = mp_edges(gamma, sigma2)
x = np.asarray(x, dtype=float)
dentro = (x > lo) & (x < hi)
out = np.zeros_like(x)
out[dentro] = np.sqrt((hi - x[dentro]) * (x[dentro] - lo)) / (2 * np.pi * gamma * sigma2 * x[dentro])
return out
def mp_cdf(x, gamma, sigma2=1.0):
lo, hi = mp_edges(gamma, sigma2)
malla = np.linspace(lo, hi, 4001)
dens = mp_density(malla, gamma, sigma2)
acum = np.concatenate([[0], np.cumsum((dens[1:] + dens[:-1]) / 2 * np.diff(malla))])
atomo = max(0.0, 1 - 1 / gamma)
return atomo + np.interp(x, malla, acum, left=0, right=acum[-1]) * (np.asarray(x) >= 0)
def ks(autovalores, gamma):
w = np.sort(autovalores)
F = mp_cdf(w, gamma)
i = np.arange(1, len(w) + 1) / len(w)
return max(np.max(np.abs(i - F)), np.max(np.abs(i - 1 / len(w) - F)))
p, n = 200, 600
gamma = p / n
muestras = {
"gaussiana": lambda s: rng.normal(size=s),
"Rademacher": lambda s: rng.choice([-1.0, 1.0], size=s),
"t con ν = 5": lambda s: rng.standard_t(5, size=s) / np.sqrt(5 / 3), # varianza 1
"t con ν = 3": lambda s: rng.standard_t(3, size=s) / np.sqrt(3), # varianza 1, sin cuarto momento
}
lo, hi = mp_edges(gamma)
print(f"γ = {gamma:.3f}: bordes teóricos [{lo:.3f}, {hi:.3f}]\n")
espectros = {}
for nombre, sorteo in muestras.items():
X = sorteo((p, n))
w = np.linalg.eigvalsh(X @ X.T / n)
espectros[nombre] = w
print(f"{nombre:12s} λmin = {w[0]:.3f} λmax = {w[-1]:6.3f} distancia KS = {ks(w, gamma):.3f}")
# más variables que observaciones: el átomo en 0
Xw = rng.normal(size=(300, 150))
w = np.linalg.eigvalsh(Xw @ Xw.T / 150)
print(f"\nγ = 2: fracción de autovalores nulos = {np.mean(w < 1e-9):.3f} (1 - 1/γ = 0.5)")Kolmogorov distance is of order for the first three distributions, and largest eigenvalues of Gaussian and Rademacher lie somewhat below edge (the edge is a limit and at this size the maximum often stays slightly inside). with 5 degrees has finite fourth moment and its () is somewhat above, but converges to very slowly. with 3 degrees retains an MP bulk (distance increases to due to tails) and its largest eigenvalue is : 34 % above the edge, much more for other seeds.
Now the spiked model. The cell measures and overlap and compares with theorem formulas, using and (, threshold ).
def con_pico(p, n, theta, rng):
X = rng.normal(size=(p, n))
X[0] *= np.sqrt(1 + theta) # Σ = I + θ e1 e1ᵀ: la variable 1 tiene varianza 1 + θ
w, V = np.linalg.eigh(X @ X.T / n)
return w[-1], V[0, -1] ** 2
def limite_lambda(theta, gamma):
return (1 + theta) * (1 + gamma / theta) if theta > np.sqrt(gamma) else (1 + np.sqrt(gamma)) ** 2
def limite_solape(theta, gamma):
return (1 - gamma / theta**2) / (1 + gamma / theta) if theta > np.sqrt(gamma) else 0.0
p, n = 100, 400
gamma = p / n
print(f"γ = {gamma}, umbral √γ = {np.sqrt(gamma):.3f}, borde λ+ = {(1 + np.sqrt(gamma))**2:.3f}\n")
print(f"{'θ':>5} {'λ1 medido':>10} {'λ1 teoría':>10} {'cos² medido':>12} {'cos² teoría':>12}")
for theta in (0.3, 0.5, 1.0, 2.0, 4.0):
r = np.array([con_pico(p, n, theta, rng) for _ in range(6)])
print(f"{theta:5.1f} {r[:, 0].mean():10.3f} {limite_lambda(theta, gamma):10.3f} {r[:, 1].mean():12.3f} {limite_solape(theta, gamma):12.3f}")Above threshold (), follows theory within a few percent ( versus ; versus ), and overlap differs by up to (at , measured and theoretical ), because is not infinite. Below, the eigenvalue remains at the edge and overlap is small. At finite size blurs the threshold: measured overlap is rather than 0, as in the figure.
Finally, end-to-end correlation cleaning: a true correlation with three sectors, minimum-variance portfolios built with raw and clipped matrices using fixed-point fit of , and realized risk against optimum, known exactly because is known.
def correlacion_verdadera(p, intensidad=1.0, sectores=3):
s = np.arange(p) * sectores // p
C = 0.12 * intensidad + 0.18 * intensidad * (s[:, None] == s[None, :])
np.fill_diagonal(C, 1.0)
return C
def recorte_mp(E, q):
"""Conserva los autovalores sobre el borde de MP y promedia el resto; σ² por punto fijo."""
w, V = np.linalg.eigh(E)
p = len(w)
sigma2 = 1.0
for _ in range(100):
ruido = w <= sigma2 * (1 + np.sqrt(q)) ** 2
nuevo = (p - w[~ruido].sum()) / ruido.sum() # la traza es p: el ruido se lleva lo que sobra
if abs(nuevo - sigma2) < 1e-10:
break
sigma2 = nuevo
ruido = w <= sigma2 * (1 + np.sqrt(q)) ** 2
w_lim = np.where(ruido, w[ruido].mean(), w)
A = (V * w_lim) @ V.T
d = np.sqrt(np.diag(A))
return A / np.outer(d, d), int((~ruido).sum()), sigma2
def cartera_minvar(A):
y = np.linalg.solve(A, np.ones(len(A)))
return y / y.sum()
p, T = 50, 100
C = correlacion_verdadera(p)
L = np.linalg.cholesky(C)
w0 = cartera_minvar(C)
optimo = np.sqrt(w0 @ C @ w0)
cruda, limpia, prometido = [], [], []
for _ in range(40):
R = rng.normal(size=(T, p)) @ L.T # T días de rendimientos con correlación C
E = np.corrcoef(R, rowvar=False)
w = cartera_minvar(E)
cruda.append(np.sqrt(w @ C @ w) / optimo)
prometido.append(np.sqrt(w @ E @ w) / optimo)
A, k, s2 = recorte_mp(E, p / T)
wl = cartera_minvar(A)
limpia.append(np.sqrt(wl @ C @ wl) / optimo)
print(f"p = {p}, T = {T} (q = {p / T}), 40 muestras. Riesgo relativo al óptimo:")
print(f" prometido por la cruda (en muestra): {np.mean(prometido):.3f} (√(1-q) = {np.sqrt(1 - p / T):.3f} si C = I)")
print(f" realizado con la cruda: {np.mean(cruda):.3f}")
print(f" realizado con el recorte MP: {np.mean(limpia):.3f} (conserva {k} autovalores, σ² = {s2:.3f})")The raw portfolio promises risk below optimum (impossible!) and ends above it, while clipping retains the three structural eigenvalues, estimates (true is ) and ends above optimum.
The professional version
For the semicircle, scipy.linalg.eigvalsh_tridiagonal computes tridiagonal matrix eigenvalues in instead of , so Dumitriu–Edelman simulates GOE size 2000 without constructing it.
from scipy.linalg import eigvalsh_tridiagonal
def goe_tridiagonal(n, rng):
d = rng.normal(size=n) * np.sqrt(2) # diagonal N(0, 2)
e = np.sqrt(rng.chisquare(np.arange(n - 1, 0, -1))) # subdiagonal chi_{n-1}, ..., chi_1
return eigvalsh_tridiagonal(d, e) / np.sqrt(n)
ev = goe_tridiagonal(2000, rng)
F = 0.5 + ev * np.sqrt(4 - ev**2) / (4 * np.pi) + np.arcsin(ev / 2) / np.pi # función de distribución del semicírculo
i = np.arange(1, len(ev) + 1) / len(ev)
ks_sc = max(np.abs(i - F).max(), np.abs(i - 1 / len(ev) - F).max())
print(f"n = 2000 (tridiagonal): λmax = {ev[-1]:.3f}, m2 = {np.mean(ev**2):.3f}, m4 = {np.mean(ev**4):.3f}, KS = {ks_sc:.4f}")GOE of size 2000 has , and Kolmogorov distance order , without forming a matrix of 4 million entries.
For cleaning, the standard alternative always worth comparing with clipping is Ledoit and Wolf’s (2004) linear shrinkage: rather than clipping the spectrum it mixes sample covariance with a scaled identity, , with weight estimated from the data. The calculation fits in six lines.
def ledoit_wolf(R):
"""Encogimiento lineal hacia mu*I de Ledoit y Wolf (2004). R: observaciones en filas."""
n_obs, p_var = R.shape
X = R - R.mean(axis=0)
S = X.T @ X / n_obs
mu = np.trace(S) / p_var
d2 = np.sum((S - mu * np.eye(p_var)) ** 2) / p_var # dispersión de los autovalores
b2 = (np.sum(np.sum(X**2, axis=1) ** 2) - n_obs * np.sum(S**2)) / (n_obs**2 * p_var) # ruido de estimar S
delta = min(b2, d2) / d2
return (1 - delta) * S + delta * mu * np.eye(p_var), delta
lw_riesgo, deltas = [], []
for _ in range(40): # las mismas 40 muestras (en distribución) que la celda anterior
R = rng.normal(size=(T, p)) @ L.T
Cc, delta = ledoit_wolf(R)
d = np.sqrt(np.diag(Cc))
w_lw = cartera_minvar(Cc / np.outer(d, d))
lw_riesgo.append(np.sqrt(w_lw @ C @ w_lw) / optimo)
deltas.append(delta)
print(f"Ledoit-Wolf, 40 muestras: encogimiento medio = {np.mean(deltas):.3f}, riesgo realizado / óptimo = {np.mean(lw_riesgo):.3f}")The scikit-learn version performs the same calculation with input checks and returns the same coefficient:
from sklearn.covariance import LedoitWolf
lw = LedoitWolf().fit(R) # R: matriz (observaciones, variables)
Cc, delta = lw.covariance_, lw.shrinkage_
Linear shrinkage (mean coefficient ) moves realized risk from times optimum to : much better than raw, but not matching clipping () in this example, where a few strong factors match clipping assumptions. Elsewhere the ordering can change, which is why both options should be measured.
Finally, depth’s effect on the spectrum of a matrix product, Gaussian versus orthogonal, with .
def producto(N, L, rng, ortogonal):
P = np.eye(N)
for _ in range(L):
G = rng.normal(size=(N, N))
W = np.linalg.qr(G)[0] if ortogonal else G / np.sqrt(N)
P = W @ P
return P
N = 100
print(f"{'L':>3} | {'gaussianas: s_max':>18} {'mediana':>9} {'s_min':>9} | {'ortogonales: s_max':>19} {'s_min':>7} | cota (L+1)^(L+1)/L^L para s_max²")
for L_ in (1, 5, 10, 20):
sg = np.linalg.svd(producto(N, L_, rng, False), compute_uv=False)
so = np.linalg.svd(producto(N, L_, rng, True), compute_uv=False)
print(f"{L_:3d} | {sg[0]:18.3f} {np.median(sg):9.2e} {sg[-1]:9.1e} | {so[0]:19.3f} {so[-1]:7.3f} | {(L_ + 1) ** (L_ + 1) / L_ ** L_:.2f} (medido: {sg[0] ** 2:.2f})")With Gaussian matrices, median singular value goes from () to about at depth 20 and the smallest falls below double-precision resolution (printed is already rounding error: the true value is smaller), while the largest grows from to : spread exceeding three orders of magnitude that no optimizer compensates well. With orthogonal matrices, maximum and minimum are 1 at every depth. The Fuss–Catalan edge is the limit with fixed and at is reached only slowly (at measured is less than half theoretical), another reminder that asymptotic formulas require .
Common mistakes
Exercises
More than one answer may be correct.
More than one answer may be correct.
More than one answer may be correct.
Step 1 of 4. What is ?
mp_density(x, gamma, sigma2=1.0) returns the continuous part of Marchenko–Pastur density with parameters at points of x (a NumPy array), zero outside , and also works for (the atom at 0 is excluded). estimar_sigma2(autovalores, gamma) estimates noise level of a pure-noise sample covariance from the upper bulk edge.import numpy as np
def mp_density(x, gamma, sigma2=1.0):
x = np.asarray(x, dtype=float)
# tu código: bordes, máscara de los puntos dentro del soporte y la fórmula
return np.zeros_like(x)
def estimar_sigma2(autovalores, gamma):
# tu código: invierte la fórmula del borde superior
return 1.0Summary
- Empirical spectral distribution has moments . In the proportional regime it converges to a deterministic law, although in norm.
- Wigner: the spectrum of converges to semicircle on . Its moments are Catalan numbers: surviving closed walks traverse a tree outward and back.
- Marchenko–Pastur: that of converges to a law with edges and, if , an atom at 0. Edges are discriminant zeros of a quadratic Stieltjes-transform equation. Bulk is universal (finite variance); the edge needs a fourth moment.
- BBP: with spike , the largest eigenvalue leaves the bulk only if , toward (always above ), and its eigenvector has overlap with truth.
- Correlation cleaning: inverting raw matrix overpromises (realized risk is times optimum for ). Clipping bulk eigenvalues (with fitted by trace) recovers nearly all optimum with strong factors. It is not optimal and fails with heavy tails or dependence.
- Networks: an initialized layer is an MP matrix, a Gaussian product degrades with depth and an orthogonal product does not. Spectrum changes after training, but that does not prove generalization: compare a control (random labels) and distrust tail fits with few points.
- Reading a paper: ask about ensemble and normalization, regime, what converges, assumptions and whether a claim is theorem, finite-size approximation, heuristic or empirical evidence.