High-dimensional and robust PCA: noise, rank and outliers
High-dimensional PCA, noise spectra, signal detection, covariance estimation and robust PCA.
After this lesson you can
- Explain the Marchenko-Pastur spectrum and BBP transition.
- Select components using parallel analysis and singular-value thresholds.
- Assess covariance estimation and robustness in high dimensions.
- Implement techniques for identifying and recovering low-rank signals.
Before you start
- 12Principal component analysisExplained variance and number of componentsPCA as minimum reconstruction error
- 04Marchenko-Pastur lawBBP phase transition
- 02Schatten norms and nuclear normOperator norm
- 06Proximal operatorSoft-thresholdingAlternating direction method of multipliers
- 09Monte Carlo estimatorMonte Carlo error and confidence intervals
Motivation: 500 assets and two years of data
You have daily returns for stocks over two years, around trading days. You want to know how many common factors move the market (the overall market, sectors, size…), which stocks each loads on, and then build a minimum-risk portfolio using estimated covariance. The previous lesson’s PCA recipe seems direct: compute from centered data, diagonalize it, inspect the scree plot and retain components before the elbow.
With comparable to , that recipe misleads in four ways. No market is needed to see it: pure noise suffices, independent returns with variance 1 whose true covariance is identity and has no factor.
import numpy as np
rng = np.random.default_rng(0)
n, d = 504, 500
X = rng.standard_normal((n, d))
Xc = X - X.mean(axis=0)
lam = np.linalg.eigvalsh(Xc.T @ Xc / n)[::-1]
g = d / n
lo, hi = (1 - np.sqrt(g)) ** 2, (1 + np.sqrt(g)) ** 2
print(f"gamma = d/n = {g:.3f}; bulk de Marchenko-Pastur: [{lo:.1e}, {hi:.3f}]")
print("cinco mayores:", np.round(lam[:5], 3), "(los verdaderos valen 1)")
print(f"menor: {lam[-1]:.1e}")
print(f"varianza 'explicada' por las 10 primeras: {lam[:10].sum() / lam.sum():.3f} (le tocaría {10 / d:.3f})")- The spectrum widens. All true eigenvalues equal 1, while sample values range from almost 0 to 3.9. The first ten “components” explain 7.4% of variance when their share should be 2%, and the scree plot falls smoothly as with real data. Without a noise reference, there is no way to tell if an eigenvalue of 3.9 is signal.
- Directions are also noise. If a weak component emerges above noise, its eigenvector can be closer to a random direction than the true one. Interpreting its loadings (“this factor is banking”) is reading tea leaves.
- Covariance cannot be inverted reliably. The smallest eigenvalue is of order when the true value is 1. A minimum-variance portfolio uses , amplifying precisely those falsely safe directions: perceived and actual risk can differ by an order of magnitude.
- One bad observation changes everything. A day with a wrongly recorded price multiplied by 100 can take over the first component. Classical PCA minimizes squared error and has no protection against this.
This lesson addresses all four. Its tools are two random-matrix results proved in the probability module, the Marchenko-Pastur law and BBP transition, and one convex optimization idea: separating a matrix into low-rank and sparse parts using the nuclear norm and norm.
Recap: the regime on one page
Let independent have mean 0 and covariance , with . The entire lesson lives in the proportional regime: with
Mind the order: is variables divided by observations. Financial literature often writes , the same ratio, while some texts use its inverse. Small gives the classical world (); order-1 does not.
Pure noise. If (independent entries, variance , finite fourth moment), the Marchenko-Pastur law says the eigenvalue histogram of converges to a deterministic density supported on
plus an atom at 0 of mass if . This interval is the bulk. The largest eigenvalue converges to edge with fluctuations of order following the Tracy-Widom law (Johnstone, 2001). With the bulk is : exactly what you saw.
One signal. If with (Johnstone’s spiked model), the BBP transition says that with and :
Below threshold the signal is invisible to the spectrum: neither eigenvalue nor eigenvector reveals it. Above it, the eigenvalue separates from the bulk but is upward biased (with and , the limit is 3.0, not 2), and the eigenvector only partially aligns. With several well-separated spikes, the result applies to each separately.
The same story in singular values. For recovering a matrix rather than covariance use the additive model , with having standard normal entries and fixed-rank . In units of , noise singular values fill (for a rectangular matrix with , the interval ). Benaych-Georges and Nadakuditi (2012) calculated the BBP analogue: if ,
and if the singular value sticks to edge 2 and overlaps tend to 0. We use this to derive the Gavish-Donoho threshold.
How many components are signal?
The scree plot mixes two things: what is present and what sampling manufactures. The first figure below, with factors set to zero, is pure fabrication, yet its shape invites searching for an elbow. To separate them we need a reference: what spectrum would these same data produce with no common structure? There are two ways to obtain it.
The Marchenko-Pastur edge. If noise is homoscedastic with variance , retain eigenvalues above . Estimating from mean eigenvalue fails because strong factors bias it. Robustly match medians instead. Since almost all eigenvalues are noise, the sample median of barely notices signal, and , with the Marchenko-Pastur median at , is consistent. Add a margin of a few Tracy-Widom scales to the edge, because in a finite sample the largest noise eigenvalue fluctuates around at scale and exceeds it with appreciable probability.
Horn’s parallel analysis. Horn (1965) proposed generating random data of the same size , computing eigenvalues and retaining components whose eigenvalue exceeds that of simulated data at the same index. Buja and Eyuboglu (1992) replaced simulated data with permutations: independently shuffle each column of , destroying dependence between variables while exactly preserving each marginal distribution. Repeat times and use the mean (Horn) or a high quantile (Glorfeld, 1995, proposed 95%) of the -th permuted eigenvalues as the index- reference.
Each reference embodies a different null hypothesis. The edge assumes isotropic noise with one variance. Parallel analysis assumes independent columns of noise with arbitrary marginals: it adapts to different variances and heavy tails because permutation preserves each column exactly. But it has two weaknesses the figure reveals:
- Shadow of strong factors. A factor loading on every variable contributes variance to each column, preserved by permutation: permuted columns have variance instead of 1, raising their spectrum. Dobriban (2020) showed parallel analysis consistently selects large factors in certain high-dimensional models but not small ones; the figure shows it can miss a factor visible in the spectrum. In finance, where the market factor is huge, this matters.
- Dependent noise. If noise is correlated across variables (neighboring sensors, assets from one country) or over time (autocorrelated series), the permuted reference does not reproduce it and parallel analysis counts that dependence as factors.
Three things the figure shows and the lab quantifies:
- Undetectable cannot be rescued with a better criterion. Below , the information is absent from the spectrum. The only way out is changing : more observations or fewer variables (for example by aggregation).
- The elbow misleads both ways. With pure noise it suggests nonexistent components; with a huge dominant factor, the jump after hides smaller real factors that do exceed the bulk.
- A single- Marchenko-Pastur edge is fragile. With heteroscedastic noise it counts high-variance noise directions as factors, while parallel analysis adapts.
The optimal Gavish-Donoho hard threshold
Counting factors differs from deciding how many components to use to reconstruct a matrix. Suppose you observe (an image, ratings matrix or measurement table) and want to estimate by truncated SVD: retain singular values above threshold and zero the rest,
This is PCA’s low-rank reconstruction, with data-selected rank. Gavish and Donoho (2014) ask which minimizes squared error . The natural answer, “the bulk edge, so no noise passes,” is incorrect.
Proof
Work in units of . Since , no bulk singular value exceeds the threshold, so decide only for each component with whether to retain it. Cross terms between distinct components vanish in the limit (their singular vectors are asymptotically orthogonal), and component contributes to normalized error : if discarded and, if retained (with signs of aligned with ),
with by Benaych-Georges and Nadakuditi. Retaining is better if and only if , that is . Substitute : . Since increases for , the signal condition equals an observed condition: . Any other threshold retains some component with or discards one with , increasing error either way.
∎The difference from the edge is the difference between seeing a signal and using it. A component with emerges above the bulk, but its singular vector is so misaligned () that adding it introduces more error than it removes. The winner lies above the edge: versus 2.
The general result (Gavish and Donoho, 2014) covers matrices with : the threshold is with
which equals at . If is unknown, estimate it from the median observed singular value (the same median matching as before), yielding for square matrices. The authors quantify gains for a rank- matrix : asymptotic squared error of the optimal threshold is at most , versus for SVD truncated to true rank, for best-tuned soft thresholding and for optimal singular-value shrinkage. That optimal thresholding beats truncation at the true rank is surprising: knowing does not help if the last components are weak.
import numpy as np
rng = np.random.default_rng(3)
n = 400
xs = np.array([3.0, 2.0, 1.6, 1.3]) # señales en unidades de sqrt(n) sigma
A = np.linalg.qr(rng.standard_normal((n, 4)))[0]
B = np.linalg.qr(rng.standard_normal((n, 4)))[0]
X = (A * xs * np.sqrt(n)) @ B.T
Y = X + rng.standard_normal((n, n)) # sigma = 1
U, s, Vt = np.linalg.svd(Y)
y = s[:4] / np.sqrt(n)
cu = np.abs(np.sum(U[:, :4] * A, axis=0))
cv = np.abs(np.sum(Vt[:4].T * B, axis=0))
print(" x y medido x + 1/x cos² (u, v) 1 - 1/x² conservar - descartar (medido / límite)")
for k, x in enumerate(xs):
gain = y[k] ** 2 - 2 * x * y[k] * cu[k] * cv[k]
lim = (x + 1 / x) * (3 / x - x)
print(f"{x:.1f} {y[k]:.3f} {x + 1 / x:.3f} {cu[k] ** 2:.3f}, {cv[k] ** 2:.3f} {1 - 1 / x ** 2:.3f} {gain:+.3f} / {lim:+.3f}")
print(f"borde 2; umbral 4/sqrt(3) = {4 / np.sqrt(3):.4f}; señal mínima útil sqrt(3) = {np.sqrt(3):.4f}")With asymptotic formulas already agree to the second digit. The two signals above reduce error when retained ( and in units of ); the two below add error ( and ), even though their observed singular values, 2.28 and 2.06, exceed edge 2.
Eigenvectors near the threshold: loadings you cannot interpret
The limiting overlap has a more serious practical consequence than eigenvalue bias. Write the estimated eigenvector as
In the isotropic noise model, is asymptotically a uniform direction in the orthogonal complement of , so each coordinate is order . If the factor loads on a sector of variables with , an estimated sector loading is plus error with standard deviation , while an outside variable has only error. With , and , , the limit is : signal per variable is and noise . Even in the sector, an individual loading has signal-to-noise ratio just above 2, and several of the 180 outside variables will have loadings as large as sector variables by chance.
import numpy as np
rng = np.random.default_rng(4)
n, d = 400, 200
g = d / n
u = np.zeros(d)
u[:20] = 1 / np.sqrt(20)
print(" beta <v1,u>^2 medido (4 muestras) límite BBP")
for beta in [0.5, 0.75, 1.0, 1.5, 3.0, 8.0]:
ov = []
for rep in range(4):
X = rng.standard_normal((n, d)) + np.sqrt(beta) * np.outer(rng.standard_normal(n), u)
Xc = X - X.mean(axis=0)
w, V = np.linalg.eigh(Xc.T @ Xc / n)
ov.append((V[:, -1] @ u) ** 2)
lim = (1 - g / beta ** 2) / (1 + g / beta) if beta > np.sqrt(g) else 0.0
print(f"{beta:5.2f} {np.mean(ov):8.3f} {lim:.3f}")Far from the threshold the formula is accurate (0.598 versus 0.583 at ; 0.809 versus 0.810 at ). Near it finite size matters: at measured overlap is 0.198 versus limit 0.333 because the transition, abrupt in the limit, smooths over a window of width order around . Below it (), overlap is 0.03, small and tending to zero as grows (a random direction gives ).
Practical rule: before interpreting component loadings, check how far its eigenvalue is from the edge. Near the edge, loadings are mostly noise even if the eigenvalue is significant. An empirical check independent of any model is stability: recompute the component on bootstrap row resamples and inspect how each loading changes.
Cleaning a covariance matrix
For covariance inversion, small eigenvalues are the problem, not large ones. The minimum-variance portfolio of assets with covariance is
Replacing with makes portfolio load on directions where has small eigenvalues, much smaller than the truth in the proportional regime. Measure two risks: predicted, , seen by the portfolio builder, and realized, , actually incurred.
Proof
Write with a normalized white Wishart matrix (sample covariance of isotropic data) and . Then , and . The law of is rotation invariant, so a quadratic form concentrates around , converging to with . For Marchenko-Pastur with , and . Predicted risk is and its ratio to tends to ; realized risk is , and its ratio tends to .
∎With , the portfolio promises half the optimal risk and delivers twice it: a factor-4 difference between predicted and realized, despite nothing wrong with the data. The solution is not to use as-is.
The oracle deserves a line. Among estimators with eigenvectors of , the closest to in Frobenius norm uses , because . It requires , but in the proportional regime can be estimated from the sample spectrum alone: Ledoit and Wolf’s (2012) nonlinear shrinkage and Bun, Bouchaud and Potters’ (2017) rotation-invariant estimator derive it from the Marchenko-Pastur Stieltjes transform. In synthetic data below we can calculate the exact oracle as a bound on cleaning that retains eigenvectors.
Ledoit-Wolf intensity minimizes expected squared error in normalized Frobenius norm, , and is estimated with
with centered . measures how covariance varies from one observation to another (variance of ), and how far lies from scaled identity: shrink more when the estimate is noisier relative to existing structure.
The next section’s lab measures the same with several samples per point. Three results: with near 1 any cleaning greatly improves on sample covariance; with small the sample is nearly optimal and clipping stalls above it because replacing the whole bulk by its mean erases idiosyncratic-risk differences that are real here; and the oracle shows that even retaining sample eigenvectors with the best possible eigenvalues does not reach optimal risk, because eigenvectors themselves are noisy.
Lab: how many components are signal
Four tools from scratch: median matching for , the Marchenko-Pastur edge, permutation parallel analysis and the Gavish-Donoho threshold, applied to the figure’s spiked model.
import numpy as np
from scipy import integrate, optimize
def mp_edges(g, s2=1.0):
return s2 * (1 - np.sqrt(g)) ** 2, s2 * (1 + np.sqrt(g)) ** 2
def mp_median(g):
"""Mediana de la ley de Marchenko-Pastur con sigma^2 = 1 y gamma <= 1."""
lo, hi = mp_edges(g)
dens = lambda x: np.sqrt((hi - x) * (x - lo)) / (2 * np.pi * g * x)
return optimize.brentq(lambda t: integrate.quad(dens, lo, t)[0] - 0.5, lo, hi)
def sigma2_hat(lam, g):
"""sigma^2 por ajuste de medianas: casi todos los autovalores son ruido."""
return np.median(lam) / mp_median(g)
def eigs(X):
Xc = X - X.mean(axis=0)
return np.linalg.eigvalsh(Xc.T @ Xc / len(X))[::-1]
def parallel_analysis(X, B=10, q=95, rng=None):
"""Referencia de Horn por permutación: cada columna se baraja por separado."""
rng = rng or np.random.default_rng(0)
E = np.empty((B, X.shape[1]))
for b in range(B):
Xp = np.column_stack([rng.permutation(col) for col in X.T])
E[b] = eigs(Xp)
return E.mean(axis=0), np.percentile(E, q, axis=0)
def count_seq(lam, ref):
"""Componentes retenidas: mientras lambda_k supere la referencia del índice k."""
ref = np.broadcast_to(ref, lam.shape)
k = 0
while k < len(lam) and lam[k] > ref[k]:
k += 1
return k
def gd_coef(b):
"""lambda*(beta) de Gavish y Donoho para m x n con beta = m/n <= 1."""
return np.sqrt(2 * (b + 1) + 8 * b / ((b + 1) + np.sqrt(b * b + 14 * b + 1)))
def spiked(n, d, betas, rng):
U = np.linalg.qr(rng.standard_normal((d, len(betas))))[0]
F = rng.standard_normal((n, len(betas))) * np.sqrt(betas)
return F @ U.T + rng.standard_normal((n, d))
rng = np.random.default_rng(1)
n, d = 400, 200
g = d / n
X = spiked(n, d, [8, 4, 2, 1, 0.4], rng)
lam = eigs(X)
m, p95 = parallel_analysis(X, B=10, rng=rng)
s2 = sigma2_hat(lam, g)
print(f"gamma = {g}; umbral BBP sqrt(gamma) = {np.sqrt(g):.3f}; sigma^2 estimada = {s2:.3f}")
print("mayores autovalores: ", np.round(lam[:6], 3))
print("análisis paralelo (media): ", np.round(m[:6], 3))
print("análisis paralelo (95 %): ", np.round(p95[:6], 3))
print(f"borde MP: {s2 * mp_edges(g)[1]:.3f}; umbral de Gavish-Donoho en autovalores: {s2 * gd_coef(g) ** 2:.3f}")
print("componentes: PA media", count_seq(lam, m), "| PA 95 %", count_seq(lam, p95),
"| borde MP", count_seq(lam, s2 * mp_edges(g)[1]), "| Gavish-Donoho", count_seq(lam, s2 * gd_coef(g) ** 2))The Gavish-Donoho threshold for singular values of (, with ) is ; since , on the eigenvalue scale it becomes , which the cell uses. Of five spikes, four exceed ; does so narrowly and its BBP limit is 3.0, just above edge 2.93, so at this size it remains in noise and all three detection criteria count 3. Gavish-Donoho counts 2: the spike is detectable but below its usefulness threshold.
rng = np.random.default_rng(2)
casos = [(400, 100, [8, 4, 2, 1, 0.4]), (400, 200, [8, 4, 2, 1, 0.4]),
(400, 400, [8, 4, 2, 1, 0.4]), (400, 200, [60, 1.5, 1.0])]
print(f"{'n':>4} {'d':>4} {'betas':<20} {'detect.':>7} {'PA med':>7} {'PA 95':>6} {'MP':>5} {'GD':>5}")
for n, d, betas in casos:
g = d / n
out = []
for rep in range(3):
X = spiked(n, d, betas, rng)
lam = eigs(X)
m, p95 = parallel_analysis(X, B=5, rng=rng)
s2 = sigma2_hat(lam, g)
out.append([count_seq(lam, m), count_seq(lam, p95),
count_seq(lam, s2 * mp_edges(g)[1]), count_seq(lam, s2 * gd_coef(g) ** 2)])
det = sum(b > np.sqrt(g) for b in betas)
o = np.mean(out, axis=0)
print(f"{n:>4} {d:>4} {str(betas):<20} {det:>7} {o[0]:>7.2f} {o[1]:>6.2f} {o[2]:>5.2f} {o[3]:>5.2f}")Each row averages three datasets. The “detect.” column counts spikes with . Three interpretations:
- Horn’s mean overestimates as grows, especially at . The cause is an index shift: if there are factors, data noise eigenvalues occupy indices but behave like the first noise eigenvalues, exceeding permuted eigenvalues at those same indices. This over-extraction led Glorfeld (1995) to propose the 95th percentile, partly correcting it.
- The market factor’s shadow. With , parallel analysis counts 1 despite 3 factors exceeding threshold; the edge with median-matched recovers nearly all. The median is unaffected by the large factor; permutation is not.
- Gavish-Donoho counts fewer, as it should. It answers a different question: which components help reconstruction. With it discards the spike, detectable but too noisy to be useful.
Now cleaning. Clipping operates on correlation, whose noise bulk has mean 1; Ledoit-Wolf shrinkage uses the formula above and is compared with sklearn.covariance.LedoitWolf.
import numpy as np
from sklearn.covariance import LedoitWolf
def clip_corr(S, n):
"""Recorte de autovalores sobre la correlación: el bulk se sustituye por su media."""
d = len(S)
sd = np.sqrt(np.diag(S))
C = S / np.outer(sd, sd)
lam, V = np.linalg.eigh(C)
edge = (1 + np.sqrt(d / n)) ** 2 # la media de los autovalores de C es 1
bulk = lam <= edge
lam[bulk] = lam[bulk].mean() # conserva la traza
return (V * lam) @ V.T * np.outer(sd, sd)
def ledoit_wolf(X):
"""Contracción lineal hacia mu I con la intensidad de Ledoit y Wolf (2004)."""
n, d = X.shape
Xc = X - X.mean(axis=0)
S = Xc.T @ Xc / n
mu = np.trace(S) / d
delta2 = np.sum((S - mu * np.eye(d)) ** 2) / d
b2 = (np.sum(np.sum(Xc ** 2, axis=1) ** 2) / n - np.sum(S ** 2)) / (n * d)
rho = min(b2, delta2) / delta2
return rho * mu * np.eye(d) + (1 - rho) * S, rho
def gmv(S):
w = np.linalg.solve(S, np.ones(len(S)))
return w / w.sum()
def factor_model(d, rng):
"""Mercado (varianza 0.04) + tres sectores (0.01) + riesgo idiosincrásico de 0.01 a 0.03."""
B = np.zeros((d, 4))
B[:, 0] = 1 + 0.3 * rng.standard_normal(d)
for k in range(3):
idx = np.arange(d) % 3 == k
B[idx, k + 1] = 0.6 + 0.2 * rng.standard_normal(idx.sum())
fvar = np.array([0.04, 0.01, 0.01, 0.01])
idio = 0.02 * (0.5 + rng.uniform(size=d))
return B, fvar, idio
def returns(n, B, fvar, idio, rng):
return (rng.standard_normal((n, 4)) * np.sqrt(fvar)) @ B.T + rng.standard_normal((n, len(idio))) * np.sqrt(idio)
rng = np.random.default_rng(5)
d = 100
B, fvar, idio = factor_model(d, rng)
Sigma = (B * fvar) @ B.T + np.diag(idio)
X = returns(200, B, fvar, idio, rng)
mine, rho = ledoit_wolf(X)
lw = LedoitWolf().fit(X)
print(f"intensidad de contracción: nuestra {rho:.6f}, sklearn {lw.shrinkage_:.6f}; "
f"diferencia máxima entre matrices {np.abs(mine - lw.covariance_).max():.1e}")The implementation matches scikit-learn to rounding. Intensity is small (0.017) because this model’s covariance is dominated by a huge market factor, and distance from scaled identity is large relative to estimation variance. Now compare out of sample, with the oracle as bound:
def oracle(S, Sigma):
"""Mejor estimador con los autovectores muestrales: xi_i = v_i^T Sigma v_i."""
lam, V = np.linalg.eigh(S)
xi = np.einsum("ji,jk,ki->i", V, Sigma, V)
return (V * xi) @ V.T
w_opt = gmv(Sigma)
r_opt = w_opt @ Sigma @ w_opt
print(f"{'n':>5} {'gamma':>6} {'muestral':>9} {'recorte':>8} {'LW':>6} {'oráculo':>8} {'previsto':>9} {'1/(1-g)':>8}")
for n in [120, 150, 200, 300, 500, 1000]:
res = []
for rep in range(5):
X = returns(n, B, fvar, idio, rng)
Xc = X - X.mean(axis=0)
S = Xc.T @ Xc / n
row = [gmv(Sh) @ Sigma @ gmv(Sh) / r_opt for Sh in [S, clip_corr(S, n), ledoit_wolf(X)[0], oracle(S, Sigma)]]
row.append(gmv(S) @ S @ gmv(S) / r_opt)
res.append(row)
r = np.mean(res, axis=0)
g = d / n
print(f"{n:>5} {g:>6.2f} {r[0]:>9.3f} {r[1]:>8.3f} {r[2]:>6.3f} {r[3]:>8.3f} {r[4]:>9.3f} {1 / (1 - g):>8.3f}")All figures are risk divided by optimal risk, averaged over five samples. Sample and predicted-risk columns follow and , as predicted, with five-sample error (0.14 to 0.88 versus 0.17 to 0.90 for predicted). At sample portfolio risk is almost seven times optimal and clipping reduces it to 1.48, while Ledoit-Wolf reaches 1.97: linear shrinkage toward identity moves all eigenvalues with the same affine rule, and here the whole bulk is the problem. At sample risk is within 11% of optimal, Ledoit-Wolf matches it, and clipping stalls around 1.30: bias from flattening idiosyncratic variances. The oracle is always below all others, between 1.07 and 1.23.
PCA’s fragility to outliers
Return to the fourth motivation problem. The first component is the principal eigenvector of an average of products , and one point enters with weight growing as . No sample size can compensate: move one point far enough and the first component points at it. In robust-statistics terms, classical PCA’s breakdown point (fraction of data to corrupt to move the result arbitrarily far) is , tending to 0.
The cleanest case is calculable by hand. Take a cloud of points with covariance (dividing by ), eigenvalues and axes and , and add one point at , distance from center in the direction perpendicular to the principal axis. The new mean shifts by and, calculating, the covariance of points in basis is
(if cloud axes are exactly and ). The first component jumps from to when the second entry exceeds the first:
With 40 points, and , one point about 9 units from center suffices, just over six cloud standard deviations along its long axis. In other directions rotation is gradual rather than a jump, but equally inevitable.
import numpy as np
rng = np.random.default_rng(31)
n = 40
th = np.deg2rad(30)
a = np.array([np.cos(th), np.sin(th)])
b = np.array([-np.sin(th), np.cos(th)])
P = np.outer(1.6 * rng.standard_normal(n), a) + np.outer(0.3 * rng.standard_normal(n), b)
c = P.mean(axis=0)
l1, l2 = np.linalg.eigvalsh(np.cov(P.T, bias=True))[::-1]
print(f"autovalores de la nube: {l1:.3f} y {l2:.3f}; R* = sqrt((n+1)(l1 - l2)) = {np.sqrt((n + 1) * (l1 - l2)):.2f}")
def angle(R):
Q = np.vstack([P, c + R * b])
w, V = np.linalg.eigh(np.cov(Q.T, bias=True))
return np.degrees(np.arccos(abs(V[:, -1] @ a)))
for R in [0, 4, 8, 8.5, 9, 9.5, 12, 20]:
print(f"R = {R:>4}: PC1 clásica a {angle(R):5.1f} grados del eje")The figure compares two robust versions defined next, with an instructive difference. The outlier is an entire corrupted row, one bad observation. The rowwise version (outlier pursuit, Xu, Caramanis and Sanghavi, 2010) penalizes the sum of Euclidean norms of outlier rows, invariant to variable-space rotation: it isolates the row and leaves direction intact. The entrywise version (PCP) separately penalizes each entry with the norm, which is not rotation invariant, and here every row has noise: it favors distributing residuals along coordinate axes, and on this cloud direction deviates by over ten degrees even without an outlier. It is designed for a different corruption type, individual entries in a large matrix, and two dimensions are outside its domain.
Robust PCA: low rank plus sparse
Many data matrices combine low-rank structure with a few large anomalies: video from a fixed camera (nearly constant background plus moving objects), service metrics (daily and weekly cycles plus incidents), a face database (diffuse lighting plus shadows and highlights). If with low-rank and sparse of arbitrarily large entries, classical PCA seeks the best low-rank least-squares approximation of and is pulled by . Naturally one might seek
where counts nonzero entries. This combinatorial problem is intractable. Convex relaxation replaces each term by its convex envelope on the corresponding unit ball: rank by nuclear norm , the order-1 Schatten norm (Fazel, 2002, proved it is rank’s convex envelope on the unit spectral norm ball), and by entrywise norm.
Both terms are homogeneous of degree 1, so multiplying by a constant scales the solution by the same constant: does not depend on global units. But it is not invariant to rescaling columns separately: if one variable is in milliseconds and another in fractions, treats them as comparable. Therefore robustly standardize each variable (median and median absolute deviation) before applying PCP to heterogeneous units.
When can separation succeed? Not always. If , the low-rank matrix is also sparse (one nonzero entry), and nothing distinguishes “low rank” from “anomaly.” If corrupts an entire column, the sparse part also has rank 1. Theory excludes both with two assumptions: singular vectors of are spread out (incoherence) and the support of is randomly distributed.
Remarkably the fraction of corrupted entries can be a constant, not something tending to 0, and corruptions can be arbitrarily large: does not average them, it isolates them. The theorem also fixes without tuning. For rectangular matrices replace by in and the logarithm, and by in the rank bound. The authors experimentally show random problems with rank and 10% corrupted entries are recovered with relative error below .
Two variants cover what the model leaves out:
- Entire corrupted observations. If outliers are whole rows (a badly recorded day, a fraudulent customer), the entrywise model is unsuitable: replace by the sum of Euclidean row norms, . This is the previous figure’s outlier pursuit, recovering the good-row subspace and identifying corrupted rows.
- Dense noise. Real data also have small noise in every entry, . Stable PCP (Zhou, Li, Wright, Candès and Ma, 2010) relaxes the constraint to and guarantees error bounded by a matrix-size-dependent multiple of . The lab shows what happens if you ignore it and a simple way to account for it using the first half’s ideas.
The algorithm: ADMM with two thresholds
PCP is convex but nondifferentiable and has exactly the structure for ADMM: two variable blocks with their own terms, coupled by a linear constraint. The augmented Lagrangian with multiplier and penalty is
Minimizing over with the rest fixed gives, completing the square, : the proximal operator of . Minimizing over is the proximal of . Both have closed forms.
The first is separable and familiar. You prove the second in a guided exercise at the end; von Neumann’s trace inequality is the key. With both, each ADMM iteration is
Candès, Li, Ma and Wright use , and stop when . Convergence follows from two-block ADMM for convex problems. Cost is dominated by an SVD per iteration, potentially partial since only singular values above matter. Interpret it: the update is PCA with a threshold (as in Gavish-Donoho, but soft) and declares anomalous what deviates from it by more than .
Lab: robust PCA with ADMM
First the implementation, checked on its intended problem: a random low-rank matrix with 5% of entries corrupted by very large values.
import numpy as np
def svt(X, t):
"""Proximal de t ||.||_*: umbral suave de los valores singulares."""
U, s, Vt = np.linalg.svd(X, full_matrices=False)
s = np.maximum(s - t, 0)
r = int((s > 0).sum())
return (U[:, :r] * s[:r]) @ Vt[:r], r
def soft(X, t):
"""Proximal de t ||.||_1: umbral suave entrada a entrada."""
return np.sign(X) * np.maximum(np.abs(X) - t, 0)
def pcp(M, lam=None, tol=1e-7, maxit=500):
"""Principal component pursuit por ADMM con los parámetros de Candès, Li, Ma y Wright."""
n1, n2 = M.shape
lam = lam if lam is not None else 1 / np.sqrt(max(n1, n2))
mu = n1 * n2 / (4 * np.abs(M).sum())
S = np.zeros_like(M)
Y = np.zeros_like(M)
nM = np.linalg.norm(M)
for k in range(1, maxit + 1):
L, r = svt(M - S + Y / mu, 1 / mu)
S = soft(M - L + Y / mu, lam / mu)
R = M - L - S
Y += mu * R
if np.linalg.norm(R) <= tol * nM:
break
return L, S, {"iter": k, "rango": r, "residuo": np.linalg.norm(R) / nM}
rng = np.random.default_rng(6)
n, r = 150, 7
L0 = rng.standard_normal((n, r)) @ rng.standard_normal((r, n)) / np.sqrt(n)
mask = rng.uniform(size=(n, n)) < 0.05
amp = 5 * np.abs(L0).max()
S0 = np.where(mask, rng.choice([-1.0, 1.0], size=(n, n)) * amp, 0.0)
L, S, info = pcp(L0 + S0)
print(f"n = {n}, rango {r}, {mask.mean():.1%} de entradas corruptas de amplitud {amp:.2f}")
print(f"iteraciones {info['iter']}, rango de L {info['rango']}, "
f"error relativo de L {np.linalg.norm(L - L0) / np.linalg.norm(L0):.1e}, "
f"soporte de S acertado en {np.mean((np.abs(S) > 1e-3) == mask):.2%} de las entradas")
U, s, Vt = np.linalg.svd(L0 + S0, full_matrices=False)
L1 = (U[:, :r] * s[:r]) @ Vt[:r]
print(f"PCA clásica de rango {r} (sabiendo el rango): error relativo {np.linalg.norm(L1 - L0) / np.linalg.norm(L0):.2f}")PCP recovers with relative error below in 36 iterations and identifies every entry’s support. Classical PCA, even knowing rank, has relative error 2.5: corruptions outweigh signal. The figure’s video:
def video(H=18, W=24, T=40):
"""Fondo con iluminación variable (rango 1) y dos objetos en movimiento; un fotograma por columna."""
yy, xx = np.mgrid[0:H, 0:W]
bg = 0.3 + 0.4 * xx / W + 0.1 * np.sin(yy / 3)
bg[3:9, 4:10] = 0.85
bg[11:16, 14:21] = 0.15
illum = 1 + 0.15 * np.sin(2 * np.pi * np.arange(T) / (T - 1))
F = bg[None] * illum[:, None, None]
L0 = F.reshape(T, -1).T.copy()
for t in range(T):
for y0, x0, h, w, val in [(6, (27 * t) // 40 - 3, 4, 3, 1.0), (13 - t // 6, W - 1 - (3 * t) // 5, 3, 3, 0.0)]:
F[t, max(0, y0):min(H, y0 + h), max(0, x0):min(W, x0 + w)] = val
return F.reshape(T, -1).T, L0
M, L0 = video()
truth = np.abs(M - L0) > 0.02
print(f"M: {M.shape}, rango del fondo {np.linalg.matrix_rank(L0)}, objetos en {truth.mean():.1%} de las entradas")
for f in [0.25, 1.0, 2.0]:
L, S, info = pcp(M, lam=f / np.sqrt(M.shape[0]), maxit=150)
det = np.abs(S) > 0.02
prec = (det & truth).sum() / max(det.sum(), 1)
rec = (det & truth).sum() / truth.sum()
print(f"lambda = {f:>4} / sqrt(432): {info['iter']:>3} iteraciones, rango(L) = {info['rango']}, "
f"error del fondo {np.linalg.norm(L - L0) / np.linalg.norm(L0):.1e}, precisión {prec:.3f}, recall {rec:.3f}")With the theorem’s and twice that value, separation is exact in about twenty iterations: background error is order and precision and recall are 1. With four times smaller, ADMM does not converge in 150 iterations and half the sparse part is false positives (precision 0.53). Candès and coauthors’ original experiment does the same with real video: 200 airport frames of , a matrix.
Service metrics with incidents. Thirty hourly series over two weeks: latency (milliseconds), error rate (fraction) and CPU use (%) for ten services, all with daily cycles and weekend effects, plus 3% noise and six injected incidents sized between 6 and 40 noise standard deviations. One is large: a whole service degraded for 12 hours. For classical PCA and PCP, flag residuals exceeding 4 column median absolute deviations as anomalous.
def metrics(seed=7):
"""30 métricas (latencia en ms, tasa de error, CPU en %) de 10 servicios, cada hora durante dos semanas."""
rng = np.random.default_rng(seed)
T, ns = 336, 10
t = np.arange(T)
daily = np.sin(2 * np.pi * t / 24)
weekend = (t // 24 % 7 >= 5).astype(float)
cols = []
for s in range(ns):
a = 0.6 + 0.4 * rng.uniform()
b = rng.uniform()
cols += [120 * (1 + 0.3 * a * daily - 0.2 * b * weekend),
0.01 * (1 + 0.5 * a * daily - 0.3 * b * weekend),
50 * (1 + 0.4 * a * daily - 0.25 * b * weekend)]
L0 = np.column_stack(cols)
sd = 0.03 * np.abs(L0).mean(axis=0)
X = L0 + rng.standard_normal(L0.shape) * sd
truth = np.zeros(X.shape, bool)
# (servicio, hora de inicio, duración, métricas afectadas, tamaño en desviaciones del ruido)
incidentes = [(2, 100, 12, [0, 1, 2], 40), (5, 30, 3, [1], 8), (7, 200, 4, [0, 2], 10),
(1, 260, 2, [2], 12), (8, 150, 6, [0], 6), (4, 300, 3, [1, 2], 9)]
for s, t0, dur, js, mag in incidentes:
for j in js:
X[t0:t0 + dur, 3 * s + j] += mag * sd[3 * s + j]
truth[t0:t0 + dur, 3 * s + j] = True
return X, truth
def robust_scale(X):
med = np.median(X, axis=0)
return (X - med) / (1.4826 * np.median(np.abs(X - med), axis=0))
def flag(R, c=4.0):
"""Marca |residuo| > c MAD por columna."""
dev = np.abs(R - np.median(R, axis=0))
return dev > c * 1.4826 * np.median(dev, axis=0)
def score(det, truth):
tp = (det & truth).sum()
return f"precisión {tp / max(det.sum(), 1):.3f}, recall {tp / truth.sum():.3f}"
X, truth = metrics()
Z = robust_scale(X)
print(f"{X.shape[0]} horas x {X.shape[1]} métricas; {truth.sum()} celdas anómalas ({truth.mean():.1%})")
Zc = Z - Z.mean(axis=0)
U, s, Vt = np.linalg.svd(Zc, full_matrices=False)
print("valores singulares:", s[:5].round(1))
print("métricas con más peso en la segunda componente:", np.argsort(-np.abs(Vt[1]))[:3], "(servicio 2: columnas 6, 7, 8)")
for k in [1, 2]:
R = Zc - (U[:, :k] * s[:k]) @ Vt[:k]
print(f"PCA clásica de rango {k}: {score(flag(R), truth)}")
L, S, info = pcp(Z, maxit=400)
print(f"PCP con lambda = 1/sqrt(336): rango(L) = {info['rango']}, {score(flag(Z - L), truth)}")Classical PCA fails in both possible ways. At rank 1 it omits part of normal structure (weekend effect varies by service) and flags it anomalous (precision 0.34). At true rank 2, the second component is not the weekend but the large incident: its three largest loadings are service 2’s three metrics, and once absorbed into the “normal” model it stops being anomalous, as do small incidents sharing its direction. Recall is 0.38. PCP detects everything, but with precision 0.68 and rank-17 : model has no dense noise, and PCP can explain 3% noise in every entry only by distributing it between a high-rank part and a part that is not sparse.
The correction uses the lesson’s first half. Add a fitting term, , and minimize by blocks: , . This is exact block descent on a convex function whose nondifferentiable term separates blocks, and converges (Tseng, 2001). To choose , require noise alone not to pass the singular-value threshold: the largest singular value of () is approximately , the bulk edge, so . Estimate using Gavish-Donoho median matching.
def stable_pcp(M, sigma, lam=None, iters=200):
"""Rango bajo + disperso + ruido denso: umbral de L en el borde del bulk, sigma (sqrt(n1) + sqrt(n2))."""
n1, n2 = M.shape
lam = lam if lam is not None else 1 / np.sqrt(max(n1, n2))
tau = sigma * (np.sqrt(n1) + np.sqrt(n2))
S = np.zeros_like(M)
for _ in range(iters):
L, r = svt(M - S, tau)
S = soft(M - L, lam * tau)
return L, S, r
def sigma_hat(M):
"""sigma por la mediana de los valores singulares (n1 >= n2): s^2/n1 sigue Marchenko-Pastur con gamma = n2/n1."""
n1, n2 = M.shape
return np.median(np.linalg.svd(M, compute_uv=False)) / np.sqrt(n1 * mp_median(n2 / n1))
tipo = np.arange(30) % 3
def por_tipo(det):
return "; ".join(f"{nom} {(det & truth)[:, tipo == k].sum()}/{truth[:, tipo == k].sum()} "
f"(falsas {(det & ~truth)[:, tipo == k].sum()})" for k, nom in enumerate(["latencia", "errores", "CPU"]))
sig = sigma_hat(Z)
L, S, r = stable_pcp(Z, sig)
print(f"escalado robusto: sigma = {sig:.4f}, rango(L) = {r}, {score(flag(Z - L), truth)}")
print(" |S| > 3 sigma:", por_tipo(np.abs(S) > 3 * sig))
Xm = X - np.median(X, axis=0)
sig = sigma_hat(Xm)
L, S, r = stable_pcp(Xm, sig)
print(f"sin escalar: sigma = {sig:.4f}, rango(L) = {r}")
print(" |S| > 3 sigma:", por_tipo(np.abs(S) > 3 * sig))With scaled data, the noise-aware variant returns rank-2 , the true rank, and detects incidents with precision and recall 0.97. The sparse part directly detects anomalies: flagging finds all 61 incidents with 12 false alarms. Without scaling, the same procedure seems to work (rank 2), but global scale is set by latency in milliseconds: error rates of 0.01 never reach the threshold, their 18 anomalous cells go unnoticed, and latency accumulates over two hundred false alarms. This is the mistake of choosing and threshold without scaling first.
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. Which inequality compares to something depending only on singular values?
clip_covariance(S, n): accept a sample covariance S computed from n observations and return the clipped matrix. Use , noise variance and edge ; retain eigenvalues above , replace the others by their mean (preserving trace), and retain eigenvectors. Tests check structure and out-of-sample minimum-variance portfolio risk in a one-factor model with .import numpy as np
def clip_covariance(S, n):
"""Recorte de autovalores: el bulk de Marchenko-Pastur se sustituye por su media."""
S = np.asarray(S, dtype=float)
d = S.shape[0]
# tu código: autodescomposición, borde, sustitución del bulk, reconstrucción
return S.copy()Summary
- With comparable to , sample covariance misleads predictably: pure noise occupies bulk , signal is visible only if (BBP transition), and even then its eigenvalue is biased and eigenvector only partly aligned, .
- How many components depends on the question. For detection: the Marchenko-Pastur edge with median-matched or Horn’s parallel analysis, each with its null (isotropic noise; independent columns) and failures (heteroscedasticity; strong-factor shadow, dependent noise, over-extraction with the mean). For reconstruction: Gavish-Donoho threshold for square matrices, discarding visible components with signal below .
- Loadings of a component near the edge are mostly noise: do not interpret them without checking distance to edge or stability.
- Cleaning covariance (clipping, Ledoit-Wolf, nonlinear shrinkage) corrects the mismatch between predicted and realized sample-portfolio risk. No method wins everywhere, and the oracle with sample eigenvectors sets the limit.
- Classical PCA has zero breakdown point. Robust PCA separates with nuclear norm plus (PCP), recovers exactly under incoherence and random support with , and uses ADMM alternating singular-value and entrywise soft thresholds. Include dense noise in the model and scale heterogeneous units first.