Principal component analysis
Principal component analysis through variance maximization, reconstruction, SVD and practical implementation.
After this lesson you can
- Derive principal components from maximum variance and minimum reconstruction error.
- Compute PCA using the singular value decomposition.
- Choose scaling and component count.
- Explain scalable and online PCA and its relationship to autoencoders.
Before you start
- 12Intrinsic dimension
- 02Singular value decompositionEckart-Young-Mirsky theoremSpectral theoremRayleigh quotientCondition number of a matrixRandomized SVD
- 06Lagrange multipliersRobbins-Monro stochastic approximation
- 09Conditioning of a problemBackward stabilityMatrix sketching
- 11Centering, standardization and the intercept
- 04Whitening
Motivation: compress, visualize, denoise and decorrelate
An -pixel image of a handwritten digit is a point in . But a digit does not have 64 degrees of freedom: neighboring pixels move together, the stroke is almost always central, and one 3 resembles another 3 more than noise made of 64 numbers. In lesson 1 of this module you called that intuition intrinsic dimension: data live near a set of much lower dimension than the ambient space. Principal component analysis (PCA) is the simplest, cheapest and oldest way to exploit this: find the linear subspace that best summarizes the cloud.
One algorithm addresses four recurring needs:
- Compress. Store numbers per example instead of , with measurable, bounded error. You will see with digits that a few numbers suffice to recognize the digit.
- Visualize. With or you can plot a high-dimensional cloud. This is the first plot you make with a new dataset.
- Denoise. If signal occupies few directions and noise spreads energy across all of them, discarding low-variance directions cleans the data (lesson 11 quantifies this with random matrix theory).
- Decorrelate. Component scores have diagonal covariance. This preprocessing is a first step for lesson 13 (ICA) and many models.
There are two definitions of PCA, and the lesson’s first surprise is that they are the same:
- Maximum variance: the direction in which projected data are most spread out.
- Minimum reconstruction error: the subspace onto which projection moves data the least.
You will derive them, prove they coincide (Pythagoras’ theorem), calculate them using the centered matrix’s SVD, and examine real practical issues: variable units, how many components to retain, matrices too large for an SVD, streaming data, and the connection with autoencoders in representation learning lessons.
Notation. You have examples (rows of ), with mean and centered matrix . Call the empirical covariance. Divide by so “variance” and “mean error” are actual averages and Pythagoras’ theorem has no extra factors; scikit-learn divides by , multiplying all eigenvalues by without changing directions or variance fractions. The eigenvalues of are with orthonormal eigenvectors , and is total variance.
Recap: spectral theorem, SVD, Eckart-Young and Rayleigh quotient
Four linear-algebra results do all the work in this lesson. They are stated with exact assumptions and used without reproving them.
- Spectral theorem (spectral theorem). If is symmetric, there is an orthonormal basis of eigenvectors and all eigenvalues are real: . The above is also positive semidefinite because .
- Rayleigh quotient (Rayleigh quotient). For symmetric , takes values in and attains the extremes at corresponding eigenvectors. In the eigenbasis, is an average of eigenvalues with weights summing to .
- SVD (singular value decomposition). Every can be written with having orthonormal columns and .
- Eckart-Young theorem (Eckart-Young). Among matrices of rank at most , the truncated matrix minimizes , with error . If the minimizer is unique.
Maximum variance
Projecting onto unit direction gives one number per example, , whose mean is zero. Its variance is
Before calculating anything, see what it means. The interactive places a line through a cloud’s centroid and rotates it. For each angle it draws projections and residuals (the lost perpendicular segments), measuring both at once.
Three facts are no coincidence and are proved in this lesson: the sum never changes; maximum and minimum occur at the same angle; and the extremes of are the two eigenvalues of , in perpendicular directions. First, the maximum.
Proof
Part 1 (Lagrange multipliers). The set is compact, so the maximum exists. With , on the sphere: the constraint is regular and at a maximum there is a with , that is, (using symmetry of ). A critical point is therefore an eigenvector, and its value is , its eigenvalue. The maximum is the largest critical value, . If attains it, with weights summing to 1 forces weights of to zero: lies in the eigenspace of .
Part 2 (without induction). Let be the rank- orthogonal projector onto the subspace of . Then with and . Thus
because and for , while and for . The bound is attained with ( for and otherwise). If , equality requires for and for , that is, .
∎Two consequences you will use constantly. First, the greedy algorithm (keep the best direction, remove it, repeat) and joint optimization of directions give the same subspace. Second, scores are decorrelated: their covariance is , and the variance of the -th score is .
Minimum reconstruction error
The other perspective: if you summarize each point by its projection onto a -dimensional subspace , how wrong is its reconstruction? With having orthonormal columns spanning , the orthogonal projector is , reconstruction of is , and mean squared error is
Proof
With and projector (), and the summands are orthogonal because (). By Pythagoras, . Average over : the left gives , the last term gives , and averaging gives . Since does not depend on , minimizing and maximizing projected variance are equivalent, and by the previous theorem the minimum is .
For affine subspace , error is . Write and expand: the cross term is because . What remains is , with equality if : the mean is already in the subspace.
∎This really is Pythagoras’ theorem, as drawn in the interactive: orange and magenta bars are the squared legs, averaged, and the hypotenuse is total variance. The reconstruction definition has its own name.
It connects to Eckart-Young: since and has rank , Eckart-Young says the minimum is , with the singular values of . PCA is the truncated SVD of the centered matrix. Without centering, the same calculation describes the best rank- approximation through the origin, mixing the mean with structure: this is the lesson’s first common mistake.
Principal axes in three dimensions
In 2D everything is a rotation. In 3D something deserves hands-on exploration: the plane of the first two components compresses the cloud least, but axes within that plane can be unstable while the plane is stable.
When , a small data change rotates and almost arbitrarily within their plane, while the plane stays put; when , the plane itself is unstable. Subspace stability depends on the spectral gap (the Davis-Kahan theorem quantifies it). This pattern reappears later with Oja’s rule and the linear autoencoder: PCA truly identifies the subspace, not individual directions.
PCA via SVD
With , covariance is . Therefore:
- components are columns of : ;
- variances are ;
- all data scores at once are ;
- rank- reconstruction is .
There are two ways to obtain and : diagonalize (eigenvectors of a symmetric matrix) or compute the SVD of . In exact arithmetic they agree; in floating-point arithmetic they do not. The reason is the condition number: . Forming already incurs, in every entry, relative error of order machine epsilon relative to , and a stable symmetric eigenvalue algorithm returns each with absolute error that in the worst case is order . A small eigenvalue can have relative error . SVD (a backward-stable algorithm on ) returns each with worst-case absolute error , and thus relative error in : the square root of the previous problem. These are a priori bounds; the cell below measures a concrete example. This is the difference between a well-conditioned problem solved on and the same problem with squared conditioning.
There are more practical reasons to prefer SVD: no need to form when is huge and small, truncated and randomized SVDs in the large-scale section start from it, and scores come from the same factorization. A reason against: if and the eigenvalues you care about are large, forming costs once and diagonalization . The thin SVD of is also , but with a several-times larger constant, while forming is one matrix product, the most optimized operation in any library: in double precision with good conditioning, covariance is the fast option.
Signs can break tests and comparisons: and are equally valid. To compare runs or libraries fix a convention; we use “the entry with largest absolute value in each component is positive.” With repeated eigenvalues this convention is insufficient: only the subspace is defined.
The first cell implements PCA three ways: using covariance eigenvectors, SVD and power iteration with deflation (calculate an eigenvector, remove it from the data, repeat), comparing them with each other and sklearn.decomposition.PCA. It uses load_digits with a fixed split: training = even-indexed examples (899), test = odd-indexed (898). PCA is fitted only on training data.
import numpy as np, time
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
X, y = load_digits(return_X_y=True)
Xtr, Xte = X[::2], X[1::2] # entrenamiento: índices pares; prueba: impares
n, d = Xtr.shape
mu = Xtr.mean(axis=0)
Xc = Xtr - mu # centrar: sin esto, no es PCA
def fijar_signos(V):
"""Convención: la entrada de mayor |valor| de cada componente (fila) es positiva."""
i = np.argmax(np.abs(V), axis=1)
return V * np.sign(V[np.arange(len(V)), i])[:, None]
def pca_covarianza(Xc, k):
C = Xc.T @ Xc / len(Xc)
lam, W = np.linalg.eigh(C) # eigh devuelve el orden creciente
return fijar_signos(W[:, ::-1][:, :k].T), lam[::-1][:k]
def pca_svd(Xc, k):
U, s, Vt = np.linalg.svd(Xc, full_matrices=False)
return fijar_signos(Vt[:k]), s[:k] ** 2 / len(Xc)
def pca_potencias(Xc, k, iters=3000, tol=1e-13, seed=0):
rng = np.random.default_rng(seed)
R, comps, lams, pasos = Xc.copy(), [], [], []
for _ in range(k):
v = rng.normal(size=R.shape[1]); v /= np.linalg.norm(v)
for it in range(1, iters + 1):
w = R.T @ (R @ v); w /= np.linalg.norm(w) # C v sin formar C
hecho = np.linalg.norm(w - v) < tol
v = w
if hecho: break
comps.append(v); lams.append(np.sum((R @ v) ** 2) / len(R)); pasos.append(it)
R = R - np.outer(R @ v, v) # deflación: se quita la componente
pca_potencias.pasos = pasos
return fijar_signos(np.array(comps)), np.array(lams)
k = 10
res = {}
for nombre, f in [("covarianza", pca_covarianza), ("SVD", pca_svd), ("potencias", pca_potencias)]:
t0 = time.perf_counter()
res[nombre] = (*f(Xc, k), time.perf_counter() - t0)
V0, lam0, _ = res["SVD"]
for nombre, (V, lam, t) in res.items():
coseno = np.sum(V * V0, axis=1)
print(f"{nombre:10s} mayor 1-|cos| con la SVD: {np.max(1 - np.abs(coseno)):.1e} "
f"mayor diferencia en lambda: {np.max(np.abs(lam - lam0)):.1e} signos como la SVD: {bool(np.all(coseno > 0))}")
print("iteraciones de potencias por componente:", pca_potencias.pasos)
print("cociente lambda_{j+1}/lambda_j para j = 1..10:", np.round(np.linalg.svd(Xc, compute_uv=False)[1:11] ** 2 / np.linalg.svd(Xc, compute_uv=False)[:10] ** 2, 2))
print("tiempos en esta máquina (s): " + ", ".join(f"{nombre} {t:.3f}" for nombre, (_, _, t) in res.items()))
sk = PCA(n_components=k, svd_solver="full").fit(Xtr)
print("sklearn: mismas componentes salvo signo:", bool(np.allclose(np.abs(sk.components_), np.abs(V0), atol=1e-8)),
"| signo incluido:", bool(np.allclose(sk.components_, V0, atol=1e-8)),
"| explained_variance_ = lambda * n/(n-1):", bool(np.allclose(sk.explained_variance_, lam0 * n / (n - 1))),
"| puntuaciones iguales:", bool(np.allclose(sk.transform(Xtr), Xc @ V0.T, atol=1e-8)))
print("varianza total tr C =", round(float(np.sum(np.linalg.svd(Xc, compute_uv=False) ** 2) / n), 2),
"| varianza explicada acumulada con k=2, 10:", np.round(np.cumsum(lam0)[[1, 9]] / (np.sum(np.linalg.svd(Xc, compute_uv=False) ** 2) / n), 3))All three agree with SVD on the first ten components (differences are rounding errors, order in eigenvalues), and with scikit-learn as well, including signs, because the version running the cell fixes signs by the same convention (do not assume that for other versions: always compare absolute values or use your own convention). Power iteration with deflation takes about 70 to 270 iterations per component, governed by the ratio : component 3, with ratio , converges in 72 iterations; component 9, with , needs 272. This matches theory because power-iteration error is multiplied by at each step. Printed timings depend on the machine and should not be overinterpreted: with columns, all three are instant, and power iteration is slowest because it performs hundreds of matrix-vector products. But that is double precision with a moderately conditioned matrix. The second cell builds a matrix with exactly known singular values (from to , with orthogonal and and zero-mean columns) and converts it to float32, with .
import numpy as np
rng = np.random.default_rng(1)
n, d = 400, 20
s_true = np.logspace(0, -6, d) # valores singulares exactos: de 1 a 1e-6
A = rng.normal(size=(n, d)); A -= A.mean(axis=0) # columnas de media cero
Q1, _ = np.linalg.qr(A) # columnas ortonormales y de media cero
Q2, _ = np.linalg.qr(rng.normal(size=(d, d)))
X64 = (Q1 * s_true) @ Q2.T
X32 = X64.astype(np.float32)
sv_svd = np.linalg.svd(X32, compute_uv=False).astype(np.float64) # SVD de la matriz en float32
lam_cov = np.linalg.eigvalsh(X32.T @ X32).astype(np.float64)[::-1] # autovalores de X^T X en float32
sv_cov = np.sqrt(np.maximum(lam_cov, 0))
print(" j sigma_j exacto err. rel. SVD err. rel. covarianza")
for j in [0, 4, 8, 10, 12, 14, 16, 19]:
e1 = abs(sv_svd[j] - s_true[j]) / s_true[j]
e2 = abs(sv_cov[j] - s_true[j]) / s_true[j]
print(f"{j + 1:2d} {s_true[j]:12.2e} {e1:13.1e} {e2:18.1e}")
print("autovalores de la covarianza en float32 que salen negativos:", int(np.sum(lam_cov < 0)), "de", d)
print("épsilon de float32:", float(np.finfo(np.float32).eps))The table shows it. With covariance, relative error rises from at to at , and beyond that no correct digits remain (relative error at least 1); 4 of 20 calculated eigenvalues are negative, impossible for a positive semidefinite matrix. The threshold matches the prediction: covariance only resolves singular values above , directions whose variance exceeds . Matrix SVD instead retains relative error even for the smallest, (below the a priori bound there, : a worst-case bound).
Reconstructing with components: digits
Here is PCA’s most intuitive use. Each digit component is a vector in , an image; reconstruction with components is the mean digit plus a sum of images weighted by scores. The interactive uses PCA from the previous cell (training, even indices) and shows test digits PCA has never seen.
With all digits reconstruct as the mean digit, and mean error per image is total variance: about 1199 squared gray-level units in training, 1205 in test. With it falls to about 308 (74% explained variance) and with to about 124 (90%). The first components are not digits: they are contrast patterns (a central stroke versus a ring, one diagonal versus another) combined together; the cloud on the right does partially separate classes without seeing labels. PCA does not know what a 3 is: it knows where intensity varies.
Also notice the two error curves. Training is lower because PCA was fitted on those data, but the gap is small (with , 308.0 versus 327.8). Both decrease monotonically with , a nontrivial fact for the next section.
Scaling and units: covariance versus correlation
PCA is invariant to translation (you center) and works well with rotations (if you rotate data by , components rotate with them and eigenvalues do not change), but not to rescaling a variable. Convert kilograms to grams and its variance is multiplied by , dominates the trace and makes the first component point toward it regardless of its relationship to other variables. Only the units have changed.
The usual solution is to diagonalize the correlation matrix, the covariance of standardized variables with the standard deviation of column (feature standardization). Each variable then contributes variance 1 and total variance is . There is no universal remedy, and it helps to know when each is reasonable:
- Covariance when all variables share units and scale means something: pixels, signal intensities from the same sensor, returns of assets in one class, already normalized gene expression.
- Correlation when mixing units (height, mass, income, age) with no reason for one to dominate. Its cost: a nearly constant variable, that is noise, is standardized and becomes as influential as an informative one.
- Middle ground: transform first (log for heavy-tailed variables), use a robust scale (median absolute deviation), or choose weights manually for the problem.
A real example, scikit-learn’s wine dataset (178 wines, 13 chemical measurements in very different units):
import numpy as np
from sklearn.datasets import load_wine
wine = load_wine()
W, nombres = wine.data, wine.feature_names
Wc = W - W.mean(axis=0)
Z = Wc / W.std(axis=0) # estandarización: media 0, desviación 1
def pca_svd_simple(M):
U, s, Vt = np.linalg.svd(M, full_matrices=False)
return Vt, s ** 2 / np.sum(s ** 2)
V_cov, f_cov = pca_svd_simple(Wc)
V_cor, f_cor = pca_svd_simple(Z)
print("desviación típica de la columna mayor y de la menor:", round(W.std(axis=0).max(), 2), round(W.std(axis=0).min(), 3))
print("covarianza : fracción explicada de las 3 primeras", np.round(f_cov[:3], 4))
print("correlación : fracción explicada de las 4 primeras", np.round(f_cor[:4], 4))
for etiqueta, V in [("covarianza ", V_cov), ("correlación", V_cor)]:
top = np.argsort(-np.abs(V[0]))[:3]
print(etiqueta, "variables con más peso en la 1ª componente:", [(nombres[i], round(float(abs(V[0][i])), 2)) for i in top])With covariance, the first component explains of variance and is essentially proline (weight ), simply because its numbers are largest: standard deviation about 314 versus 14 for the next and less than 4 for the rest. With correlation the distribution is much flatter (, , for the first three), and the first component mixes several chemical variables (flavanoids, total_phenols and od280/od315_of_diluted_wines with weights from to ). Which is “correct” depends on the question, but the first is a property of laboratory units, not wines.
Explained variance and number of components
Choosing has no single answer and common criteria are heuristics:
- Cumulative threshold: the smallest with (or , ). Simple, but the threshold is arbitrary.
- Scree plot elbow: where the curve stops falling quickly. Subjective, and sometimes there is no elbow.
- Kaiser rule: retain components with above the average eigenvalue (1 for the correlation matrix). Cheap, no guarantees.
- Parallel analysis (Horn): compare eigenvalues with data having the same marginals but no structure (for example permuted columns), retaining those that exceed them. More defensible; see Jolliffe and Cadima (2016).
- Reconstruction validation, which deserves particular care.
There is a trap: test-set reconstruction error never increases as grows, so it cannot select on its own. This is elementary: subspaces are nested, , and for each point (projection onto a larger subspace does not move it farther away). “Cross-validation” that only projects and reconstructs always chooses . What does have an interior minimum is predicting hidden data error, the idea of Wold’s (1978) component cross-validation leaving out individual matrix entries. Here we use a simple variant: for each test example hide a block of variables, estimate scores by least squares on visible variables, and use the scores to predict hidden ones. With few components the model is poor; with too many it fits noise in visible variables and predicts badly.
import numpy as np
import matplotlib.pyplot as plt
U, S, Vt = np.linalg.svd(Xc, full_matrices=False) # Xc, mu y Xte vienen de la primera celda
lam = S ** 2 / len(Xc)
frac = lam / lam.sum()
cum = np.cumsum(frac)
for umbral in (0.80, 0.90, 0.95, 0.99):
print(f"R_k >= {umbral:.0%}: k = {int(np.argmax(cum >= umbral)) + 1}")
print("regla de Kaiser (lambda mayor que la media de los autovalores): k =", int(np.sum(lam > lam.mean())))
Xtc = Xte - mu
def mse(M, k):
V = Vt[:k].T
R = M - M @ V @ V.T
return float(np.mean(np.sum(R ** 2, axis=1)))
ks = np.arange(0, 65)
e_tr = np.array([mse(Xc, k) for k in ks])
e_te = np.array([mse(Xtc, k) for k in ks])
print("error de prueba no creciente en k:", bool(np.all(np.diff(e_te) <= 1e-9)), "| error de prueba con k = 0, 10, 20, 64:", np.round(e_te[[0, 10, 20, 64]], 1))
# validación a la Wold: se oculta un cuarto de los píxeles y se predice con el resto
rng = np.random.default_rng(0)
bloques = np.array_split(rng.permutation(64), 4)
def press(k):
if k == 0:
return float(np.mean(np.sum(Xtc ** 2, axis=1)))
V = Vt[:k].T
tot = np.zeros(len(Xtc))
for ocultos in bloques:
vis = np.setdiff1d(np.arange(64), ocultos)
pts = Xtc[:, vis] @ np.linalg.pinv(V[vis]).T # puntuaciones por mínimos cuadrados con los visibles
tot += np.sum((Xtc[:, ocultos] - pts @ V[ocultos].T) ** 2, axis=1)
return float(np.mean(tot))
p = np.array([press(k) for k in range(0, 41)])
print("error de predicción de píxeles ocultos: mínimo en k =", int(np.argmin(p)), "con valor", round(float(p.min()), 1),
"| con k = 0, 5, 10, 15, 25, 40:", np.round(p[[0, 5, 10, 15, 25, 40]], 1))
fig, ax = plt.subplots(1, 3, figsize=(11, 3.2))
ax[0].semilogy(np.arange(1, 65), np.maximum(lam, 1e-3), "o-", ms=3); ax[0].set_title("sedimentación (autovalores)"); ax[0].set_xlabel("j")
ax[1].plot(ks, e_tr, label="entrenamiento"); ax[1].plot(ks, e_te, "--", label="prueba"); ax[1].set_title("reconstrucción: monótona en k"); ax[1].set_xlabel("k"); ax[1].legend()
ax[2].semilogy(range(0, 41), p); ax[2].axvline(int(np.argmin(p)), color="gray", ls=":"); ax[2].set_title("predecir píxeles ocultos: mínimo en k"); ax[2].set_xlabel("k")
plt.tight_layout(); plt.show()On digits, criteria disagree: the 80% threshold asks for 13 components, 90% for 21, 95% for 28 and 99% for 41; Kaiser gives 14; hidden-pixel validation is minimized at (error 649.5, versus 1204.8 at ; between 10 and 15 the curve is nearly flat: 666.2 at and 680.1 at ). It then rises: at error returns to the level (1217.9) and at is , because least-squares fitting 40 scores with only 48 visible pixels is unstable. Test reconstruction error instead decreases continuously (1204.8 at to 135.3 at and 0 at ), and the scree curve has no clear elbow. Lesson: there is no “true” ; there is an appropriate for the intended use (compression, visualization, feeding a classifier), and the honest approach is to measure that task.
Whitening
Dividing each score by its standard deviation gives identity covariance. PCA whitening (Gaussian whitening, seen in probability) is , and rotating back, , gives ZCA whitening (the version retaining original coordinates). It is the first step of ICA, many distance-based methods and some image models, because it removes second-order correlations and fixes scale in every direction.
It can help before methods measuring distances or regularizing isotropically, provided noise is not amplified, and adds nothing to methods already invariant to linear input transformations. The danger is division by : it amplifies the lowest-variance directions, which are most contaminated by noise. Therefore regularize with or whiten only the first components’ subspace.
import numpy as np
k = 40
V = Vt[:k] # componentes de los dígitos (celda anterior)
lam_k = lam[:k]
Z = (Xc @ V.T) / np.sqrt(lam_k) # blanqueado por PCA en el subespacio de k componentes
C_Z = Z.T @ Z / len(Z)
print("covarianza de las puntuaciones blanqueadas = identidad:", bool(np.allclose(C_Z, np.eye(k), atol=1e-8)))
Zzca = Xc @ (V.T @ np.diag(1 / np.sqrt(lam_k)) @ V) # ZCA: de vuelta al espacio de píxeles
print("ZCA conserva las coordenadas y las componentes giradas coinciden:", Zzca.shape, bool(np.allclose(Zzca @ V.T, Z, atol=1e-8)))
print("cociente de varianzas entre la primera y la última componente retenidas:", round(float(lam_k[0] / lam_k[-1]), 1),
"-> la última se multiplica por", round(float(np.sqrt(lam_k[0] / lam_k[-1])), 1), "respecto de la primera")
print("la última componente retenida tiene lambda =", round(float(lam_k[-1]), 3), "frente a lambda_1 =", round(float(lam_k[0]), 1))Both checks are exact: whitened scores have identity covariance and ZCA is the same transformation expressed in the pixel basis. The third line warns: with , the last retained component has versus , a ratio of 77, so whitening multiplies that direction by relative to the first. After whitening, a direction barely moving pixels weighs as much in distances as component 1’s contrast pattern. If the next method uses Euclidean distances (k-nearest neighbors, k-means), that may worsen results; choose and by measuring the task, not by default.
Large-scale PCA
A full SVD of costs operations and requires the whole in memory. With millions for or tens of thousands for it may not fit or pay off, and almost never are all components needed. There are two solution families.
Randomized SVD (randomized SVD, developed in numerical methods as matrix sketching). The idea of Halko, Martinsson and Tropp (2011): multiply by Gaussian matrix ( is oversampling by a few units) to capture the important subspace with high probability; with orthonormal basis of , the small SVD of gives values and vectors. When the spectrum decays slowly, power iterations (, orthonormalizing between steps) refine the basis. The paper’s theoretical bound (Theorem 1.2, eq. 1.10, spectral norm) for the algorithm with test vectors, returning rank , with , is
Read it as follows: the factor before (optimal rank- error) approaches 1 exponentially as increases. Each data pass costs .
Block incremental PCA. Process data in blocks of rows, keeping only , and (a summary). When a block with mean and rows arrives, stack
and compute its SVD, truncating to . The last row corrects the shift between means. Without truncation () the result is exact; truncation is approximate (the idea implemented by IncrementalPCA, following Ross et al., 2008). Memory is regardless of .
The next two cells implement both from scratch and compare them with scikit-learn.
import numpy as np
def svd_aleatoria(Xc, k, s=5, q=0, seed=0):
rng = np.random.default_rng(seed)
Q, _ = np.linalg.qr(Xc @ rng.normal(size=(Xc.shape[1], k + s))) # base de la imagen
for _ in range(q): # iteración de potencias, ortonormalizando
Q, _ = np.linalg.qr(Xc.T @ Q)
Q, _ = np.linalg.qr(Xc @ Q)
_, sv, Vt_ = np.linalg.svd(Q.T @ Xc, full_matrices=False)
return fijar_signos(Vt_[:k]), sv[:k] ** 2 / len(Xc)
def angulo_max(A, B):
"""Mayor ángulo principal, en grados, entre los subespacios generados por las filas de A y de B."""
sv = np.linalg.svd(A @ B.T, compute_uv=False)
return float(np.degrees(np.arccos(np.clip(sv.min(), -1, 1))))
def pca_incremental(X, k, b):
n_visto, mu_, SVt = 0, None, None
for i in range(0, len(X), b):
B = X[i:i + b]; nb = len(B); mb = B.mean(axis=0)
if n_visto == 0:
M, mu_nuevo = B - mb, mb
else:
M = np.vstack([SVt, B - mb, np.sqrt(n_visto * nb / (n_visto + nb)) * (mu_ - mb)])
mu_nuevo = (n_visto * mu_ + nb * mb) / (n_visto + nb)
n_visto += nb; mu_ = mu_nuevo
_, sv, Vt_ = np.linalg.svd(M, full_matrices=False)
SVt = sv[:k, None] * Vt_[:k]
return fijar_signos(Vt_[:k]), sv[:k] ** 2 / n_visto
k = 10
Vex, lam_ex = pca_svd(Xc, k)
print("SVD aleatorizada con s = 5 de sobremuestreo, k = 10:")
for q in (0, 1, 2, 4):
V, lam_a = svd_aleatoria(Xc, k, s=5, q=q)
print(f" q = {q}: ángulo máximo con el subespacio exacto = {angulo_max(V, Vex):6.2f} grados, error relativo máximo en lambda = {np.max(np.abs(lam_a - lam_ex) / lam_ex):.1e}")
print("PCA incremental con bloques de 100 filas:")
for kk in (10, 30, 64):
Vi, lam_i = pca_incremental(Xtr, kk, 100)
Ve, lam_e = pca_svd(Xc, kk)
print(f" k = {kk:2d}: ángulo máximo = {angulo_max(Vi, Ve):.2e} grados, error máximo en lambda relativo a lambda_1 = {np.max(np.abs(lam_i - lam_e)) / lam_e[0]:.1e}")
Vi, _ = pca_incremental(Xtr, 10, 100)
lam_all = np.linalg.svd(Xc, compute_uv=False) ** 2 / len(Xc)
print(f" k = 10: ángulo entre las 5 primeras incrementales y las 5 exactas = {angulo_max(Vi[:5], Vex[:5]):.2f} grados"
f" | lambda_10/lambda_11 = {lam_all[9] / lam_all[10]:.2f} | varianza descartada en el corte = {lam_all[10:].sum() / lam_all.sum():.0%}")Notice the first-half pattern: with the subspace is poor (maximum angle 43.5 degrees from exact) because digit eigenvalues decay slowly, with no clear gap around , and each power iteration improves it: 15.0, 8.0 and 1.5 degrees at . In the second half, without truncation () the result is exact (angle degrees), but with truncation, the full subspace is poor on this dataset: 46.6 degrees at and 65.9 at (scikit-learn’s IncrementalPCA implements the same algorithm and gives the same angles). The last line shows where it fails: the first 5 incremental components are only 3.0 degrees from exact; directions near the cutoff are damaged. The summary passed between blocks discards the tail each time, here 26% of variance, while the cutoff gap is modest (). What a block discards cannot be recovered, enough to mix directions on either side of the cutoff. This is the same spectral-gap lesson as Oja’s rule, and the next cell contrasts low-rank data plus noise with a large gap and small tail.
The library cell measures scaling with synthetic low-rank data plus noise (10 signals with decreasing spectrum), as and grow, and the data memory each method needs.
import numpy as np, time
from sklearn.decomposition import PCA, IncrementalPCA
def datos(n, d, seed=0, r=10):
rng = np.random.default_rng(seed)
escala = np.linspace(3.0, 1.0, r)
Fz = rng.normal(size=(n, r)) * escala
Ld, _ = np.linalg.qr(rng.normal(size=(d, r)))
return Fz @ Ld.T + 0.3 * rng.normal(size=(n, d))
print(" n d | ángulo máx. (grados): aleat. incr. | tiempo (s): exacta aleat. incr. | datos en RAM: exacta incremental")
for n, d in [(1000, 50), (1000, 150), (3000, 50), (3000, 150)]:
Xs = datos(n, d)
t0 = time.perf_counter(); ex = PCA(10, svd_solver="full").fit(Xs); t_ex = time.perf_counter() - t0
t0 = time.perf_counter(); al = PCA(10, svd_solver="randomized", random_state=0).fit(Xs); t_al = time.perf_counter() - t0
t0 = time.perf_counter(); inc = IncrementalPCA(10, batch_size=500).fit(Xs); t_in = time.perf_counter() - t0
a_al, a_in = angulo_max(ex.components_, al.components_), angulo_max(ex.components_, inc.components_)
print(f"{n:5d} {d:5d} | {a_al:6.3f} {a_in:6.3f} | {t_ex:6.3f} {t_al:6.3f} {t_in:6.3f} | {n * d * 8 / 1e6:5.1f} MB {500 * d * 8 / 1e6:5.2f} MB")How to choose. If data fit in memory and is moderate, full SVD (or covariance when and using double precision) gives everything needed and is the predictable choice. If they fit but , randomized SVD avoids computing unused components; with slow spectral decay (like digits), use or more. If data do not fit in memory or stream in, incremental PCA (blocks) or Oja’s rule are the available choices, and quality depends on the spectral gap around : memory is and respectively, independent of , but error is not.
The memory column is the size of data the algorithm must see, calculated analytically ( bytes per number): exact needs the whole matrix; incremental only one block, making it viable when data do not fit in memory (feed blocks with partial_fit). With this spectrum (a clear gap between 10 signals and noise), randomized recovers the subspace within degrees and incremental within to degrees at every tested size: contrast digits, where truncated incremental failed. Incremental error grows with (about at to about at ), because more dimensions mean a larger noise tail discarded each block. Do not cite timings as universal facts: they depend on machine, size and solver; at these small sizes the three methods take the same order of time and approximate methods’ advantage appears only with and much larger matrices. Angles, by contrast, do not depend on the machine.
Streaming PCA: Oja’s rule
If data arrive one at a time and cannot be stored (sensors, logs, network traffic), there is not even a covariance matrix to diagonalize. One rule learns the first component with memory and one computation per sample, originating as a neuron model.
Hebb’s rule (“neurons that fire together wire together”) is with a linear neuron’s output: weight grows when input and output coincide. Its problem is obvious: ‘s norm grows without bound. Oja (1982) proposed normalization. If , update and normalize to obtain , and since , the normalization factor is , yielding
Oja’s rule is thus with : Hebb with a forgetting term proportional to squared output. (The block version is the stochastic power method: with the block covariance and a QR factorization; for components with a per-sample rule, see Oja’s subspace rule and Sanger’s 1989 rule, which also orders components.)
Why does it converge? It is a case of stochastic approximation (Robbins-Monro): with mean field . With rates satisfying and , sample noise averages out and the trajectory follows the mean differential equation
Its fixed points are and ; only are stable (proof exercise), so under standard stochastic approximation assumptions the rule converges almost surely to (Oja and Karhunen, 1985, proved this for the rule). The mean equation gives more: in coordinates , , so ratio satisfies and
with for constant rate (the law is exact for the mean equation at ; in higher dimensions the tail is dominated by , decaying with ). Speed is set by spectral gap : if the eigenvalues are nearly equal, the first component is barely defined and the rule takes time to decide. With constant rate, the iterate also fluctuates around the optimum instead of converging, because sample noise does not average out. Linearizing near gives the fluctuation. In , with and the coordinates of in the eigenbasis, one step gives, ignoring second-order terms in ,
The factor has mean and the forcing term has mean zero and variance (for Gaussian data, and are independent). Equating stationary variances on both sides to first order in ,
Amplitude increases with (as ) and explodes as the gap closes. The approximation requires that value to be small; otherwise the iterate wanders far from and linearization fails. And if is so large that reaches order 1, the norm of oscillates or diverges: the final common mistake.
Before moving to decreasing rates, check the floor formula with the interactive’s model (, Gaussian data in 2D). The cell starts at , runs the rule at constant rate and averages over the last 45,000 of 60,000 samples.
import numpy as np
def suelo_oja(eta, l1, l2, T=60000, seed=0):
z = (np.random.default_rng(seed).normal(size=(T, 2)) * np.sqrt([l1, l2])).tolist() # coordenadas en la base propia
w0, w1, acum, m = 1.0, 0.0, 0.0, 0
for t, (x0, x1) in enumerate(z):
y = w0 * x0 + w1 * x1
w0, w1 = w0 + eta * y * (x0 - y * w0), w1 + eta * y * (x1 - y * w1)
if t >= T // 4:
acum += (w1 / w0) ** 2; m += 1
return acum / m
print(" eta lambda2 semilla E[tan^2] medido linealización cociente")
for eta, l2, seed in [(0.005, 1.0, 0), (0.01, 1.0, 0), (0.03, 1.0, 0), (0.02, 1.6, 0), (0.02, 1.6, 1)]:
med, teo = suelo_oja(eta, 2.0, l2, seed=seed), eta * 2.0 * l2 / (2 * (2.0 - l2))
print(f"{eta:5.3f} {l2:6.1f} {seed:6d} {med:15.4g} {teo:13.4f} {med / teo:8.3g}")With the interactive’s gap (), the formula works: measured-to-predicted ratio is at and at , with fluctuation growing in proportion to . At the ratio is already : those are the terms ignored by linearization. With a small gap (), the prediction, , is no longer small and the formula fails completely, with seed-dependent results (ratios of and over 3000): the iterate no longer fluctuates near but occasionally wanders almost perpendicular. This quantifies what the interactive shows as approaches 1.
The next cell implements the rule with decreasing rate (satisfying Robbins-Monro conditions) and the block QR version, measuring spectral-gap effects with spectra calculated by the cell: error is the angle to population eigenvectors, known because you constructed the covariance.
import numpy as np
def datos_gauss(n, lam, seed):
rng = np.random.default_rng(seed)
p = len(lam)
Q, _ = np.linalg.qr(rng.normal(size=(p, p))) # base propia poblacional (columnas de Q)
return (rng.normal(size=(n, p)) * np.sqrt(lam)) @ Q.T, Q
def angulo_cols(Q, W):
s = np.linalg.svd(Q.T @ W, compute_uv=False)
return float(np.degrees(np.arccos(np.clip(s.min(), -1, 1))))
def oja(X, c=1.0, t0=100.0, seed=0, ver=()):
rng = np.random.default_rng(seed)
w = rng.normal(size=X.shape[1]); w /= np.linalg.norm(w)
traza = {}
for t, x in enumerate(X, start=1):
eta = c / (t0 + t) # sum eta = infinito, sum eta^2 < infinito
y = w @ x
w = w + eta * y * (x - y * w)
if t in ver: traza[t] = w.copy()
return w, traza
def oja_bloques(X, k, b=50, c=3.0, t0=10.0, seed=0, ver=()):
rng = np.random.default_rng(seed)
W, _ = np.linalg.qr(rng.normal(size=(X.shape[1], k)))
traza = {}
for t, i in enumerate(range(0, len(X), b), start=1):
Xb = X[i:i + b]
W, _ = np.linalg.qr(W + (c / (t0 + t)) * (Xb.T @ (Xb @ W)) / len(Xb)) # potencias estocásticas + ortogonalización
if i + b in ver: traza[i + b] = W.copy()
return W, traza
p, n = 20, 20000
ver = (200, 1000, 5000, 20000)
print("regla de Oja, tasa c/(100 + t): ángulo (grados) con v1 tras 200, 1000, 5000 y 20000 muestras")
for nombre, lam2 in [("hueco grande (lambda1 = 4, lambda2 = 1.0)", 1.0), ("hueco medio (lambda1 = 4, lambda2 = 2.5)", 2.5), ("hueco pequeño (lambda1 = 4, lambda2 = 3.6)", 3.6)]:
lam = np.concatenate([[4.0], [lam2 * 0.97 ** j for j in range(p - 1)]])
X, Q = datos_gauss(n, lam, 0)
w, tr = oja(X, ver=ver)
print(f" {nombre}: ", [round(angulo_cols(Q[:, :1], tr[t][:, None]), 2) for t in ver], "| norma final", round(float(np.linalg.norm(w)), 3))
lam = np.concatenate([[5.0, 4.0, 3.0], [0.93 ** j for j in range(p - 3)]])
X, Q = datos_gauss(n, lam, 1)
Wb, tr = oja_bloques(X, 3, ver=ver)
Xc_ = X - X.mean(axis=0)
Vex_ = np.linalg.svd(Xc_, full_matrices=False)[2][:3].T
print("por bloques (k = 3, bloques de 50), ángulo del subespacio:", [round(angulo_cols(Q[:, :3], tr[t]), 2) for t in ver])
print("SVD exacta de la muestra completa, ángulo con el subespacio poblacional:", round(angulo_cols(Q[:, :3], Vex_), 2), "(el error de muestreo mínimo alcanzable)")With decreasing rate, angular error after 200, 1000, 5000 and 20000 samples is , , and degrees with a large gap (), , , and with a medium gap (), and , , and with a small gap (): at the same sample count, small-gap error is 5 to 8 times greater. Final norm is or in all three: the forgetting term brings it to 1 without explicit normalization, as predicted by the mean equation. With blocks (), the subspace reaches degrees from population after 20000 samples, versus for exact SVD on that same sample: the price of seeing data once with memory.
Linear autoencoders and the principal subspace
A linear autoencoder compresses with one matrix and reconstructs with another: with (encoder) and (decoder), trained to minimize squared error on centered data. It is a network with one hidden layer and no activation. It looks like another model, but it is PCA.
Proof
We prove parts 1–3; part 4 (classification of critical points) is in the original paper.
Let , of rank at most . Then and has rank . By Eckart-Young, , with equality if and only if (unique because ). This value is attained with , for example and : part 1. If is a minimum, , and since has full column rank it is injective and : part 2. For part 3, , so loss is unchanged.
∎Part 3 answers “what does it learn?”: the subspace, not the axes. The degrees of freedom of are a parameterization symmetry (any basis of the subspace works), and gradient descent chooses one depending on initialization. To obtain ordered axes add something else: tied weights with constraints, Sanger’s rule, or regularization breaking symmetry. This is a general lesson about representations: a model robustly learns what its loss determines, and squared loss determines only the subspace. (With nonlinear activations, the autoencoder is more expressive than PCA; the latent-representations lesson exploits that difference.)
import numpy as np
rng = np.random.default_rng(3)
d, k, n = 10, 3, 4000
lam_true = np.array([5.0, 3.0, 2.0, 0.5, 0.45, 0.4, 0.3, 0.2, 0.15, 0.1])
Qb, _ = np.linalg.qr(rng.normal(size=(d, d)))
Xa = (rng.normal(size=(n, d)) * np.sqrt(lam_true)) @ Qb.T
Xa -= Xa.mean(axis=0)
C = Xa.T @ Xa / n
lam, V = np.linalg.eigh(C); lam, V = lam[::-1], V[:, ::-1]
Vk = V[:, :k]
def desequilibrio(D, E):
return float(np.linalg.norm(D.T @ D - E @ E.T)) # se conserva bajo el flujo de gradiente
def entrenar(seed, escala=0.3, pasos=6000, lr=0.02):
r = np.random.default_rng(seed)
D, E = escala * r.normal(size=(d, k)), escala * r.normal(size=(k, d))
entrenar.deseq0 = desequilibrio(D, E)
for _ in range(pasos):
G = 2 * (D @ E - np.eye(d)) @ C # dL/dM, con M = D E
D, E = D - lr * G @ E.T, E - lr * D.T @ G
return D, E
def perdida(D, E):
A = np.eye(d) - D @ E
return float(np.trace(A @ C @ A.T))
print("óptimo de Eckart-Young, suma de los autovalores restantes:", round(float(lam[k:].sum()), 5))
for seed in (0, 1, 2):
D, E = entrenar(seed)
Qd, _ = np.linalg.qr(D)
ang = np.degrees(np.arccos(np.clip(np.linalg.svd(Vk.T @ Qd, compute_uv=False).min(), -1, 1)))
c1 = abs(D[:, 0] @ Vk[:, 0]) / np.linalg.norm(D[:, 0])
Gm = E @ Vk # los códigos son Gm @ (puntuaciones de PCA)
sv = np.linalg.svd(Gm, compute_uv=False)
print(f"semilla {seed}: pérdida = {perdida(D, E):.5f} | ángulo entre col(D) y el subespacio principal = {ang:.3f} grados | "
f"ángulo de la 1ª columna de D con v1 = {np.degrees(np.arccos(min(1.0, c1))):.1f} grados | valores singulares de E V_k = {np.round(sv, 2)}")
print(f" ||D^T D - E E^T|| al inicio = {entrenar.deseq0:.3f}, al final = {desequilibrio(D, E):.3f}")
D, E = entrenar(0, escala=0.01)
print(f"inicialización pequeña (escala 0.01): pérdida = {perdida(D, E):.5f} | desequilibrio final = {desequilibrio(D, E):.4f} | "
f"valores singulares de E V_k = {np.round(np.linalg.svd(E @ Vk, compute_uv=False), 3)}")For all three initializations loss reaches the Eckart-Young optimum (, sum of remaining eigenvalues), and the subspace matches the principal one (angle degrees), but the first column of forms , and degrees with depending on seed, and singular values of are , , in the first. Since codes are (at the minimum, vanishes on the subspace complement), maps PCA scores to codes. If a rotation, its singular values would all be 1; they are not, so codes are a general linear transformation of scores, stretching some directions and shrinking others, with compensating oppositely.
What determines which of infinitely many minima gradient descent chooses? A conserved quantity. With , gradient flow is and , so
and imbalance remains unchanged throughout training (the automatic layer-balancing phenomenon studied by Du, Hu and Lee, 2018, for linear and homogeneous networks). At a minimum, and with invertible, and imbalance is : zero if and only if is orthogonal. The cell confirms this: imbalance norm is the same initially and finally up to finite-step error ( versus for the first seed), and with small initialization (scale ) final imbalance is and singular values of are : codes are then a rotation of PCA scores. Even then the axes are not recovered because any rotation inside the subspace remains a balanced minimum; but initialization, not loss, determines the minimum found.
With libraries: a leakage-free workflow
The previous sections give the recipe for PCA in a real project: standardize if appropriate, fit PCA only on training data, transform test data with the fitted transformation, and choose using the appropriate criterion. In scikit-learn a Pipeline is natural: it ensures nothing is fitted on validation data within cross-validation.
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
Wx, Wy = wine.data, wine.target # vinos, de la celda anterior
for etiqueta, pasos in [
("sin escalar + PCA(2)", [PCA(n_components=2), LogisticRegression(max_iter=2000)]),
("escalado + PCA(2) ", [StandardScaler(), PCA(n_components=2), LogisticRegression(max_iter=2000)]),
("escalado + PCA(90 %)", [StandardScaler(), PCA(n_components=0.90), LogisticRegression(max_iter=2000)]),
]:
pipe = make_pipeline(*pasos)
acc = cross_val_score(pipe, Wx, Wy, cv=5)
print(f"{etiqueta}: exactitud en validación cruzada de 5 particiones = {acc.mean():.3f}")
pipe = make_pipeline(StandardScaler(), PCA(n_components=0.90)).fit(Wx)
pca = pipe.named_steps["pca"]
print("componentes retenidas para el 90 % de la varianza:", pca.n_components_, "| varianza explicada acumulada:", np.round(np.cumsum(pca.explained_variance_ratio_), 3))
Zs = pipe.named_steps["standardscaler"].transform(Wx)
Zrec = pca.inverse_transform(pca.transform(Zs))
print("error medio de reconstrucción (variables estandarizadas):", round(float(np.mean(np.sum((Zs - Zrec) ** 2, axis=1))), 3),
"| d (1 - R_k) =", round(float(Zs.shape[1] * (1 - np.sum(pca.explained_variance_ratio_))), 3))The experiment repeats the units lesson on a real task: with covariance, two components dominated by proline give cross-validation accuracy; with standardized variables the same two components give , and the 8 needed for 90% variance give . Inside the Pipeline, scaler and PCA are fitted in each fold only on its training portion. The last line checks the lesson’s identity in practice: mean reconstruction error in standardized variables is , with .
Common mistakes
Exercises
Step 1 of 4. What problem and Lagrangian do you write?
Step 1 of 4. How do you decompose each ?
Step 1 of 4. How do you write the equation in coordinates ?
float32 with . Estimate relative error of the smallest eigenvalue of as . What value results? (Two decimals; a value above 1 means no correct digits.)pca_svd(X, k) returning (componentes, puntuaciones, varianza_explicada): componentes of shape (k, d) with a deterministic sign (each row’s largest absolute entry is positive), puntuaciones of shape (n, k) (projected centered data), and varianza_explicada of shape (k,) with divisor n - 1 (as in scikit-learn). Center the data and use SVD, not covariance. Tests compare with scikit-learn.import numpy as np
def pca_svd(X, k):
X = np.asarray(X, dtype=float)
# tu código: centrar, SVD, quedarte con k componentes, fijar signos
return X[:k], X[:, :k], np.zeros(k)More than one answer may be correct.
More than one answer may be correct.
More than one answer may be correct.
More than one answer may be correct.
Summary
PCA has two equivalent faces: maximum-variance direction and minimum-reconstruction-error subspace, united by Pythagoras (). It is computed with centered-matrix SVD, not covariance, and depends on units: choose covariance or correlation according to what scales mean. Component count cannot be chosen by test reconstruction error (which always decreases), but by a criterion with a minimum, such as predicting hidden variables, or by the final task. For large data, use randomized SVD (with power iterations) or block incremental PCA; for streams, Oja’s rule, whose speed is set by the spectral gap. A linear autoencoder learns exactly the principal subspace, not the axes within it.