Module contents
Lesson 10 of 24Core 110 min

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

Motivation: compress, visualize, denoise and decorrelate

An 8×88 \times 8-pixel image of a handwritten digit is a point in R64\R^{64}. 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 k≪dk \ll d numbers per example instead of dd, with measurable, bounded error. You will see with digits that a few numbers suffice to recognize the digit.
  • Visualize. With k=2k = 2 or 33 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:

  1. Maximum variance: the direction in which projected data are most spread out.
  2. 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 nn examples xi∈Rd\vb{x}_i \in \R^d (rows of X∈Rn×d\mat{X} \in \R^{n \times d}), with mean μ=1n∑ixi\vb{\mu} = \frac1n \sum_i \vb{x}_i and centered matrix Xc=X−1μ⊤\mat{X}_c = \mat{X} - \vb{1}\vb{\mu}\T. Call C=1nXc⊤Xc∈Rd×d\mat{C} = \frac1n \mat{X}_c\T \mat{X}_c \in \R^{d \times d} the empirical covariance. Divide by nn so “variance” and “mean error” are actual averages and Pythagoras’ theorem has no extra factors; scikit-learn divides by n−1n - 1, multiplying all eigenvalues by n/(n−1)n/(n-1) without changing directions or variance fractions. The eigenvalues of C\mat{C} are λ1≥⋯≥λd≥0\lambda_1 \ge \dots \ge \lambda_d \ge 0 with orthonormal eigenvectors v1,…,vd\vb{v}_1, \dots, \vb{v}_d, and tr⁡C=∑jλj=1n∑i∥xi−μ∥2\tr \mat{C} = \sum_j \lambda_j = \frac1n \sum_i \norm{\vb{x}_i - \vb{\mu}}^2 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 C∈Rd×d\mat{C} \in \R^{d \times d} is symmetric, there is an orthonormal basis of eigenvectors and all eigenvalues are real: C=VΛV⊤=∑jλjvjvj⊤\mat{C} = \mat{V} \mat{\Lambda} \mat{V}\T = \sum_j \lambda_j \vb{v}_j \vb{v}_j\T. The C\mat{C} above is also positive semidefinite because u⊤Cu=1n∑i(u⊤(xi−μ))2≥0\vb{u}\T\mat{C}\vb{u} = \frac1n\sum_i (\vb{u}\T(\vb{x}_i - \vb{\mu}))^2 \ge 0.
  • Rayleigh quotient (Rayleigh quotient). For symmetric C\mat{C}, R(u)=u⊤Cu/u⊤uR(\vb{u}) = \vb{u}\T\mat{C}\vb{u} / \vb{u}\T\vb{u} takes values in [λd,λ1][\lambda_d, \lambda_1] and attains the extremes at corresponding eigenvectors. In the eigenbasis, u⊤Cu=∑jλj(vj⊤u)2\vb{u}\T\mat{C}\vb{u} = \sum_j \lambda_j (\vb{v}_j\T\vb{u})^2 is an average of eigenvalues with weights (vj⊤u)2(\vb{v}_j\T\vb{u})^2 summing to ∥u∥2\norm{\vb{u}}^2.
  • SVD (singular value decomposition). Every A∈Rn×d\mat{A} \in \R^{n \times d} can be written A=UΣV⊤\mat{A} = \mat{U}\mat{\Sigma}\mat{V}\T with U,V\mat{U}, \mat{V} having orthonormal columns and Σ=diag⁡(σ1≥σ2≥⋯≥0)\mat{\Sigma} = \diag(\sigma_1 \ge \sigma_2 \ge \dots \ge 0).
  • Eckart-Young theorem (Eckart-Young). Among matrices of rank at most kk, the truncated matrix Ak=∑j≤kσjujvj⊤\mat{A}_k = \sum_{j \le k} \sigma_j \vb{u}_j \vb{v}_j\T minimizes ∥A−B∥F\norm{\mat{A} - \mat{B}}_F, with error ∥A−Ak∥F2=∑j>kσj2\norm{\mat{A} - \mat{A}_k}_F^2 = \sum_{j > k} \sigma_j^2. If σk>σk+1\sigma_k > \sigma_{k+1} the minimizer is unique.

Maximum variance

Projecting onto unit direction u\vb{u} gives one number per example, zi=u⊤(xi−μ)z_i = \vb{u}\T(\vb{x}_i - \vb{\mu}), whose mean is zero. Its variance is

1n∑izi2=1n∑iu⊤(xi−μ)(xi−μ)⊤u=u⊤C u.\frac1n \sum_i z_i^2 = \frac1n \sum_i \vb{u}\T (\vb{x}_i - \vb{\mu})(\vb{x}_i - \vb{\mu})\T \vb{u} = \vb{u}\T \mat{C}\, \vb{u}.

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.

InteractiveRotate the line: variance and residual
  • data
  • projection onto the line
  • residual
Breakdown of total variance tr⁡C\operatorname{tr}\mathbf{C}
  • projected variance 2.97
  • reconstruction error 1.91
v(θ)v(\theta) and e(θ)e(\theta) as the line rotates
  • v(θ)v(\theta)
  • e(θ)e(\theta)
  • first component angle
65.0°
Projected variance v(θ)v(\theta)2.967
Reconstruction error e(θ)e(\theta)1.908
Sum v+ev + e4.875
Total variance tr⁡C\operatorname{tr}\mathbf{C}4.875
Eigenvalues λ1, λ2\lambda_1,\ \lambda_2 de C\mathbf{C}4.499, 0.376
The line retains 61 % of total variance. Each unit increase in vv decreases ee by exactly one unit.
Drag the orange handle (or use the slider) to rotate a line through the centroid of 60 points. The bar divides total variance between what the line projects (orange) and what is lost in residuals (magenta). Find the angle where the orange bar is longest and check what happens to error at that same angle. Then move to the perpendicular direction: what is the projected variance? The two curves on the right are v(θ)v(\theta) and e(θ)e(\theta): what geometric relationship do they have?

Three facts are no coincidence and are proved in this lesson: the sum v+ev + e never changes; maximum vv and minimum ee occur at the same angle; and the extremes of vv are the two eigenvalues of C\mat{C}, in perpendicular directions. First, the maximum.

Proof

Part 1 (Lagrange multipliers). The set {∥u∥=1}\{\norm{\vb{u}} = 1\} is compact, so the maximum exists. With g(u)=u⊤u−1g(\vb{u}) = \vb{u}\T\vb{u} - 1, ∇g=2u≠0\grad g = 2\vb{u} \ne \vb{0} on the sphere: the constraint is regular and at a maximum there is a ν\nu with ∇(u⊤Cu)=ν∇g\grad(\vb{u}\T\mat{C}\vb{u}) = \nu \grad g, that is, 2Cu=2νu2\mat{C}\vb{u} = 2\nu\vb{u} (using symmetry of C\mat{C}). A critical point is therefore an eigenvector, and its value is u⊤Cu=ν u⊤u=ν\vb{u}\T\mat{C}\vb{u} = \nu\,\vb{u}\T\vb{u} = \nu, its eigenvalue. The maximum is the largest critical value, λ1\lambda_1. If u\vb{u} attains it, ∑jλj(vj⊤u)2=λ1\sum_j \lambda_j (\vb{v}_j\T\vb{u})^2 = \lambda_1 with weights summing to 1 forces weights of λj<λ1\lambda_j < \lambda_1 to zero: u\vb{u} lies in the eigenspace of λ1\lambda_1.

Part 2 (without induction). Let P=WW⊤\mat{P} = \mat{W}\mat{W}\T be the rank-kk orthogonal projector onto the subspace of W\mat{W}. Then tr⁡(W⊤CW)=tr⁡(CP)=∑jλjpj\tr(\mat{W}\T\mat{C}\mat{W}) = \tr(\mat{C}\mat{P}) = \sum_j \lambda_j p_j with pj=vj⊤Pvj=∥Pvj∥2∈[0,1]p_j = \vb{v}_j\T\mat{P}\vb{v}_j = \norm{\mat{P}\vb{v}_j}^2 \in [0, 1] and ∑jpj=tr⁡P=k\sum_j p_j = \tr\mat{P} = k. Thus

∑jλjpj−∑j≤kλj=∑j≤kλj(pj−1)+∑j>kλjpj≤λk∑j≤k(pj−1)+λk∑j>kpj=λk(∑jpj−k)=0,\sum_j \lambda_j p_j - \sum_{j \le k} \lambda_j = \sum_{j \le k} \lambda_j (p_j - 1) + \sum_{j > k} \lambda_j p_j \le \lambda_k \sum_{j \le k}(p_j - 1) + \lambda_k \sum_{j > k} p_j = \lambda_k\Big(\sum_j p_j - k\Big) = 0,

because pj−1≤0p_j - 1 \le 0 and λj≥λk\lambda_j \ge \lambda_k for j≤kj \le k, while pj≥0p_j \ge 0 and λj≤λk\lambda_j \le \lambda_k for j>kj > k. The bound is attained with W=[v1⋯vk]\mat{W} = [\vb{v}_1 \cdots \vb{v}_k] (pj=1p_j = 1 for j≤kj \le k and 00 otherwise). If λk>λk+1\lambda_k > \lambda_{k+1}, equality requires pj=1p_j = 1 for j≤kj \le k and pj=0p_j = 0 for j>kj > k, that is, P=∑j≤kvjvj⊤\mat{P} = \sum_{j \le k}\vb{v}_j\vb{v}_j\T.

∎

Two consequences you will use constantly. First, the greedy algorithm (keep the best direction, remove it, repeat) and joint optimization of kk directions give the same subspace. Second, scores are decorrelated: their covariance is W⊤CW=diag⁡(λ1,…,λk)\mat{W}\T\mat{C}\mat{W} = \diag(\lambda_1, \dots, \lambda_k), and the variance of the jj-th score is λj\lambda_j.

Minimum reconstruction error

The other perspective: if you summarize each point by its projection onto a kk-dimensional subspace SS, how wrong is its reconstruction? With W∈Rd×k\mat{W} \in \R^{d \times k} having orthonormal columns spanning SS, the orthogonal projector is P=WW⊤\mat{P} = \mat{W}\mat{W}\T, reconstruction of xi\vb{x}_i is x^i=μ+P(xi−μ)\hat{\vb{x}}_i = \vb{\mu} + \mat{P}(\vb{x}_i - \vb{\mu}), and mean squared error is

E(W)=1n∑i∥xi−x^i∥2=1n∑i∥(I−P)(xi−μ)∥2.E(\mat{W}) = \frac1n \sum_i \norm{\vb{x}_i - \hat{\vb{x}}_i}^2 = \frac1n \sum_i \norm{(\mat{I} - \mat{P})(\vb{x}_i - \vb{\mu})}^2 .
Proof

With yi=xi−μ\vb{y}_i = \vb{x}_i - \vb{\mu} and projector P\mat{P} (P=P⊤=P2\mat{P} = \mat{P}\T = \mat{P}^2), yi=Pyi+(I−P)yi\vb{y}_i = \mat{P}\vb{y}_i + (\mat{I} - \mat{P})\vb{y}_i and the summands are orthogonal because ⟨Py,(I−P)y⟩=y⊤P(I−P)y=0\inner{\mat{P}\vb{y}}{(\mat{I} - \mat{P})\vb{y}} = \vb{y}\T\mat{P}(\mat{I} - \mat{P})\vb{y} = 0 (P2=P\mat{P}^2 = \mat{P}). By Pythagoras, ∥yi∥2=∥Pyi∥2+∥(I−P)yi∥2\norm{\vb{y}_i}^2 = \norm{\mat{P}\vb{y}_i}^2 + \norm{(\mat{I} - \mat{P})\vb{y}_i}^2. Average over ii: the left gives tr⁡C\tr\mat{C}, the last term gives E(W)E(\mat{W}), and averaging ∥Py∥2=∥W⊤y∥2=tr⁡(W⊤yy⊤W)\norm{\mat{P}\vb{y}}^2 = \norm{\mat{W}\T\vb{y}}^2 = \tr(\mat{W}\T\vb{y}\vb{y}\T\mat{W}) gives tr⁡(W⊤CW)\tr(\mat{W}\T\mat{C}\mat{W}). Since tr⁡C\tr\mat{C} does not depend on W\mat{W}, minimizing EE and maximizing projected variance are equivalent, and by the previous theorem the minimum is tr⁡C−∑j≤kλj\tr\mat{C} - \sum_{j \le k}\lambda_j.

For affine subspace m+S\vb{m} + S, error is 1n∑i∥(I−P)(xi−m)∥2\frac1n\sum_i\norm{(\mat{I} - \mat{P})(\vb{x}_i - \vb{m})}^2. Write xi−m=yi+(μ−m)\vb{x}_i - \vb{m} = \vb{y}_i + (\vb{\mu} - \vb{m}) and expand: the cross term is 2n∑iyi⊤(I−P)(μ−m)=0\frac2n\sum_i \vb{y}_i\T(\mat{I} - \mat{P})(\vb{\mu} - \vb{m}) = 0 because ∑iyi=0\sum_i\vb{y}_i = \vb{0}. What remains is E(W)+∥(I−P)(μ−m)∥2≥E(W)E(\mat{W}) + \norm{(\mat{I} - \mat{P})(\vb{\mu} - \vb{m})}^2 \ge E(\mat{W}), with equality if μ−m∈S\vb{\mu} - \vb{m} \in S: 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 E(W)=1n∥Xc−XcWW⊤∥F2E(\mat{W}) = \frac1n \norm{\mat{X}_c - \mat{X}_c\mat{W}\mat{W}\T}_F^2 and XcWW⊤\mat{X}_c\mat{W}\mat{W}\T has rank ≤k\le k, Eckart-Young says the minimum is 1n∑j>kσj2\frac1n\sum_{j>k}\sigma_j^2, with σj\sigma_j the singular values of Xc\mat{X}_c. PCA is the truncated SVD of the centered matrix. Without centering, the same calculation describes the best rank-kk 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.

InteractivePrincipal axes in 3D
  • data
  • v1\mathbf{v}_1
  • v2\mathbf{v}_2
  • v3\mathbf{v}_3
Projected cloud: scores on (v1,v2)(\mathbf{v}_1, \mathbf{v}_2)
Variance explained by each component
  • 79.1 %
  • 18.0 %
  • 2.9 %
0.55
0.20
35°
−25°
20°
λ1\lambda_1 (first eigenvalue)6.95
λ2\lambda_21.58
λ3\lambda_30.26
Variance explained by 2 components97.1 %
Plane reconstruction error =λ3=\lambda_30.256
The plane spanned by v1\mathbf{v}_1 and v2\mathbf{v}_2 retains 97.1 % of variance; what is lost by flattening the cloud onto it is λ3/tr⁡C=2.9\lambda_3/\operatorname{tr}\mathbf{C} = 2.9 %.
A cloud of 150 points shaped like an ellipsoid, which you can deform and rotate with sliders (drag the scene to change viewpoint). The three drawn axes are sample covariance eigenvectors, with length 2λi2\sqrt{\lambda_i}; the orange plane is spanned by the first two and small orange points are projections onto it. At right, the cloud seen from the first two components. Rotate the cloud and check that explained variances do not change: they describe shape, not orientation. Bring σ2/σ1\sigma_2/\sigma_1 close to 1 and watch how axes v1\mathbf{v}_1 and v2\mathbf{v}_2 behave relative to their plane. Then raise σ3/σ1\sigma_3/\sigma_1 to match σ2/σ1\sigma_2/\sigma_1 and see how the plane itself is no longer well-defined.

When λ1≈λ2\lambda_1 \approx \lambda_2, a small data change rotates v1\vb{v}_1 and v2\vb{v}_2 almost arbitrarily within their plane, while the plane stays put; when λ2≈λ3\lambda_2 \approx \lambda_3, the plane itself is unstable. Subspace stability depends on the spectral gap λk−λk+1\lambda_k - \lambda_{k+1} (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 Xc=UΣV⊤\mat{X}_c = \mat{U}\mat{\Sigma}\mat{V}\T, covariance is C=1nVΣ2V⊤\mat{C} = \frac1n\mat{V}\mat{\Sigma}^2\mat{V}\T. Therefore:

  • components are columns of V\mat{V}: vj\vb{v}_j;
  • variances are λj=σj2/n\lambda_j = \sigma_j^2/n;
  • all data scores at once are Z=XcV=UΣ\mat{Z} = \mat{X}_c\mat{V} = \mat{U}\mat{\Sigma};
  • rank-kk reconstruction is XcVkVk⊤=UkΣkVk⊤\mat{X}_c\mat{V}_k\mat{V}_k\T = \mat{U}_k\mat{\Sigma}_k\mat{V}_k\T.

There are two ways to obtain V\mat{V} and λj\lambda_j: diagonalize C\mat{C} (eigenvectors of a symmetric d×dd \times d matrix) or compute the SVD of Xc\mat{X}_c. In exact arithmetic they agree; in floating-point arithmetic they do not. The reason is the condition number: κ(Xc⊤Xc)=κ(Xc)2\kappa(\mat{X}_c\T\mat{X}_c) = \kappa(\mat{X}_c)^2. Forming Xc⊤Xc\mat{X}_c\T\mat{X}_c already incurs, in every entry, relative error of order machine epsilon ε\varepsilon relative to ∥Xc∥2\norm{\mat{X}_c}^2, and a stable symmetric eigenvalue algorithm returns each λj\lambda_j with absolute error that in the worst case is order ελ1\varepsilon\lambda_1. A small eigenvalue can have relative error ≈ε λ1/λj\approx \varepsilon\,\lambda_1/\lambda_j. SVD (a backward-stable algorithm on Xc\mat{X}_c) returns each σj\sigma_j with worst-case absolute error ≈εσ1\approx \varepsilon\sigma_1, and thus relative error ≈ε σ1/σj=ελ1/λj\approx \varepsilon\,\sigma_1/\sigma_j = \varepsilon\sqrt{\lambda_1/\lambda_j} in σj\sigma_j: 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 Xc\mat{X}_c and the same problem with squared conditioning.

There are more practical reasons to prefer SVD: no need to form d×dd \times d when dd is huge and nn small, truncated and randomized SVDs in the large-scale section start from it, and scores come from the same factorization. A reason against: if n≫dn \gg d and the eigenvalues you care about are large, forming C\mat{C} costs O(nd2)\bigO(nd^2) once and diagonalization O(d3)\bigO(d^3). The thin SVD of Xc\mat{X}_c is also O(nd2)\bigO(nd^2), but with a several-times larger constant, while forming C\mat{C} 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: vj\vb{v}_j and −vj-\vb{v}_j 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.

[ ]PCA three ways: covariance, SVD and power iteration with deflationBrowser
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 10−1310^{-13} 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 λj+1/λj\lambda_{j+1}/\lambda_j: component 3, with ratio 0.670.67, converges in 72 iterations; component 9, with 0.900.90, needs 272. This matches theory because power-iteration error is multiplied by λj+1/λj\lambda_{j+1}/\lambda_j at each step. Printed timings depend on the machine and should not be overinterpreted: with 6464 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 11 to 10−610^{-6}, with orthogonal U\mat{U} and V\mat{V} and zero-mean columns) and converts it to float32, with ε=2−23≈1.2×10−7\varepsilon = 2^{-23} \approx 1.2 \times 10^{-7}.

[ ]Forming covariance in float32 loses small componentsBrowser
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 4×10−64 \times 10^{-6} at σ5≈5×10−2\sigma_5 \approx 5 \times 10^{-2} to 0.250.25 at σ13≈1.6×10−4\sigma_{13} \approx 1.6 \times 10^{-4}, 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 ≈ε σ1≈3.5×10−4\approx \sqrt{\varepsilon}\,\sigma_1 \approx 3.5 \times 10^{-4}, directions whose variance exceeds ελ1\varepsilon\lambda_1. Matrix SVD instead retains relative error 2×10−42 \times 10^{-4} even for the smallest, σ20=10−6\sigma_{20} = 10^{-6} (below the a priori bound there, ε σ1/σ20≈0.12\varepsilon\,\sigma_1/\sigma_{20} \approx 0.12: a worst-case bound).

Reconstructing with kk components: digits

Here is PCA’s most intuitive use. Each digit component is a vector in R64\R^{64}, an 8×88 \times 8 image; reconstruction with kk components is the mean digit plus a sum of kk images weighted by scores. The interactive uses PCA from the previous cell (training, even indices) and shows test digits PCA has never seen.

InteractiveReconstruct with k components
original
reconstruction, k=10k = 10
residual
The first 16 components as images (orange positive, blue negative). Components used in reconstruction are fully opaque.
Mean squared reconstruction error versus kk
  • training (where PCA is fit)
  • test (digits unseen by PCA)
The 360 example digits in the plane of the first two components
  • digits 3
  • other digits
  • digit above
10
5
Variance explained with kk (training)74.3 %
Error for this digit ∥x−x^∥2\lVert \mathbf{x} - \hat{\mathbf{x}} \rVert^2316.6
Mean test error with kk327.8
Mean training error with kk308.0
You store 10 numbers instead of 64 (16 %) plus components shared across all digits.
Choose a digit and move kk from 0 to 64: reconstruction is the mean plus the first kk components weighted by scores. Residuals (orange positive, blue negative) are unexplained. Bottom left: training and test mean squared error; bottom right: 360 test digits projected onto the first two components. Find the smallest kk at which the digit is readable. Then examine components: are they digits? What do they look like? See how much explained variance is needed to halve test error.

With k=0k = 0 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 k=10k = 10 it falls to about 308 (74% explained variance) and with k=20k = 20 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 k=10k = 10, 308.0 versus 327.8). Both decrease monotonically with kk, 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 Q\mat{Q}, 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 10610^6, dominates the trace and makes the first component point toward it regardless of its relationship to other variables. Only the units have changed.

InteractiveUnits control PCA
Centered data in chosen units (same scale on both axes)
  • person
  • 1st component
Horizontal axis: height. Vertical axis: mass.
First component angle versus mass unit
  • covariance
  • correlation
Matrix diagonalized by PCA
0.00
Mass measured inkilograms
Angle of first component to height axis52.6°
Weight of mass in first component ∣v1,2∣|v_{1,2}|0.794
Variance explained by first component88.3 %
Correlation of both variables0.754
With these units the first component combines both variables, but that combination depends on the chosen units rather than a property of the data.
80 people with correlated height (cm) and mass (kg) (in this sample, ρ=0.75\rho = 0.75). Change the mass unit from tonnes to grams with covariance: the first component (orange) rotates from one axis to the other. The right curve shows that angle for all units. Switch to correlation: the angle stays at 45 degrees for every unit. In which range does the first component seem to say something about the relationship between variables, and in which does it only say which variable has larger numbers?

The usual solution is to diagonalize the correlation matrix, the covariance of standardized variables x~ij=(xij−μj)/sj\tilde{x}_{ij} = (x_{ij} - \mu_j)/s_j with sjs_j the standard deviation of column jj (feature standardization). Each variable then contributes variance 1 and total variance is dd. 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):

[ ]Wine: PCA with covariance versus correlationBrowser
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 99.8 %99.8\,\% of variance and is essentially proline (weight 1.001.00), 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 (36.2 %36.2\,\%, 19.2 %19.2\,\%, 11.1 %11.1\,\% for the first three), and the first component mixes several chemical variables (flavanoids, total_phenols and od280/od315_of_diluted_wines with weights from 0.380.38 to 0.420.42). 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 kk has no single answer and common criteria are heuristics:

  1. Cumulative threshold: the smallest kk with Rk≥0.9R_k \ge 0.9 (or 0.950.95, 0.990.99). Simple, but the threshold is arbitrary.
  2. Scree plot elbow: where the curve stops falling quickly. Subjective, and sometimes there is no elbow.
  3. Kaiser rule: retain components with λj\lambda_j above the average eigenvalue (1 for the correlation matrix). Cheap, no guarantees.
  4. 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).
  5. Reconstruction validation, which deserves particular care.

There is a trap: test-set reconstruction error never increases as kk grows, so it cannot select kk on its own. This is elementary: subspaces are nested, Sk⊂Sk+1S_k \subset S_{k+1}, and for each point ∥(I−Pk+1)y∥≤∥(I−Pk)y∥\norm{(\mat{I} - \mat{P}_{k+1})\vb{y}} \le \norm{(\mat{I} - \mat{P}_k)\vb{y}} (projection onto a larger subspace does not move it farther away). “Cross-validation” that only projects and reconstructs always chooses k=dk = d. 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.

[ ]Digit component count: threshold, test error and Wold validationBrowser
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 k=12k = 12 (error 649.5, versus 1204.8 at k=0k = 0; between 10 and 15 the curve is nearly flat: 666.2 at k=10k = 10 and 680.1 at k=15k = 15). It then rises: at k=25k = 25 error returns to the k=0k = 0 level (1217.9) and at k=40k = 40 is 1.7×1051.7 \times 10^5, because least-squares fitting 40 scores with only 48 visible pixels is unstable. Test reconstruction error instead decreases continuously (1204.8 at k=0k = 0 to 135.3 at k=20k = 20 and 0 at k=64k = 64), and the scree curve has no clear elbow. Lesson: there is no “true” kk; there is an appropriate kk 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 z=Λk−1/2Vk⊤(x−μ)\vb{z} = \mat{\Lambda}_k^{-1/2}\mat{V}_k\T(\vb{x} - \vb{\mu}), and rotating back, VΛ−1/2V⊤(x−μ)\mat{V}\mat{\Lambda}^{-1/2}\mat{V}\T(\vb{x} - \vb{\mu}), 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 λj\sqrt{\lambda_j}: it amplifies the lowest-variance directions, which are most contaminated by noise. Therefore regularize with 1/λj+ϵ1/\sqrt{\lambda_j + \epsilon} or whiten only the first kk components’ subspace.

[ ]PCA and ZCA whiteningBrowser
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 k=40k = 40, the last retained component has λ40=2.418\lambda_{40} = 2.418 versus λ1=186.2\lambda_1 = 186.2, a ratio of 77, so whitening multiplies that direction by 77≈8.8\sqrt{77} \approx 8.8 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 kk and ϵ\epsilon by measuring the task, not by default.

Large-scale PCA

A full SVD of Xc∈Rn×d\mat{X}_c \in \R^{n \times d} costs O(ndmin⁡(n,d))\bigO(nd\min(n, d)) operations and requires the whole Xc\mat{X}_c in memory. With millions for nn or tens of thousands for dd 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 Xc\mat{X}_c by Gaussian matrix Ω∈Rd×(k+s)\mat{\Omega} \in \R^{d \times (k + s)} (ss is oversampling by a few units) to capture the important subspace with high probability; with orthonormal basis Q\mat{Q} of XcΩ\mat{X}_c\mat{\Omega}, the small SVD of Q⊤Xc\mat{Q}\T\mat{X}_c gives values and vectors. When the spectrum decays slowly, qq power iterations (Y←Xc(Xc⊤Y)\mat{Y} \leftarrow \mat{X}_c(\mat{X}_c\T\mat{Y}), orthonormalizing between steps) refine the basis. The paper’s theoretical bound (Theorem 1.2, eq. 1.10, spectral norm) for the algorithm with 2k2k test vectors, returning rank 2k2k, with 2≤k≤12min⁡{n,d}2 \le k \le \frac12\min\{n, d\}, is

E ∥Xc−UΣV⊤∥≤[1+42min⁡{n,d}k−1]1/(2q+1)σk+1,\E\,\norm{\mat{X}_c - \mat{U}\mat{\Sigma}\mat{V}\T} \le \Big[1 + 4\sqrt{\tfrac{2\min\{n, d\}}{k - 1}}\Big]^{1/(2q+1)} \sigma_{k+1},

Read it as follows: the factor before σk+1\sigma_{k+1} (optimal rank-kk error) approaches 1 exponentially as qq increases. Each data pass costs O(nd(k+s))\bigO(nd(k+s)).

Block incremental PCA. Process data in blocks of bb rows, keeping only μ\vb{\mu}, nseenn_{\text{seen}} and ΣkVk⊤\mat{\Sigma}_k\mat{V}_k\T (a k×dk \times d summary). When a block B\mat{B} with mean μB\vb{\mu}_B and nBn_B rows arrives, stack

M=[ΣkVk⊤B−1μB⊤nseen nB/(nseen+nB) (μ−μB)⊤]\mat{M} = \begin{bmatrix} \mat{\Sigma}_k\mat{V}_k\T \\ \mat{B} - \vb{1}\vb{\mu}_B\T \\ \sqrt{n_{\text{seen}}\,n_B/(n_{\text{seen}} + n_B)}\,(\vb{\mu} - \vb{\mu}_B)\T \end{bmatrix}

and compute its SVD, truncating to kk. The last row corrects the shift between means. Without truncation (k=dk = d) the result is exact; truncation is approximate (the idea implemented by IncrementalPCA, following Ross et al., 2008). Memory is O(bd)\bigO(bd) regardless of nn.

The next two cells implement both from scratch and compare them with scikit-learn.

[ ]Randomized and incremental SVD from scratch on digitsBrowser
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 q=0q = 0 the subspace is poor (maximum angle 43.5 degrees from exact) because digit eigenvalues decay slowly, with no clear gap around λ10\lambda_{10}, and each power iteration improves it: 15.0, 8.0 and 1.5 degrees at q=1,2,4q = 1, 2, 4. In the second half, without truncation (k=64k = 64) the result is exact (angle 10−610^{-6} degrees), but with truncation, the full subspace is poor on this dataset: 46.6 degrees at k=10k = 10 and 65.9 at k=30k = 30 (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 ΣkVk⊤\mat{\Sigma}_k\mat{V}_k\T passed between blocks discards the tail each time, here 26% of variance, while the cutoff gap is modest (λ10/λ11=1.30\lambda_{10}/\lambda_{11} = 1.30). 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 nn and dd grow, and the data memory each method needs.

[ ]Exact, randomized and incremental scikit-learn PCA: angle, time and memoryBrowser
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 dd is moderate, full SVD (or covariance when n≫dn \gg d and using double precision) gives everything needed and is the predictable choice. If they fit but k≪min⁡(n,d)k \ll \min(n, d), randomized SVD avoids computing unused components; with slow spectral decay (like digits), use q=2q = 2 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 λk\lambda_k: memory is O(bd)\bigO(bd) and O(dk)\bigO(dk) respectively, independent of nn, but error is not.

The memory column is the size of data the algorithm must see, calculated analytically (88 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 0.0010.001 degrees and incremental within 0.170.17 to 0.330.33 degrees at every tested size: contrast digits, where truncated incremental failed. Incremental error grows with dd (about 0.170.17 at d=50d = 50 to about 0.30.3 at d=150d = 150), 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 k≪dk \ll d 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 O(d)\bigO(d) memory and one computation per sample, originating as a neuron model.

Hebb’s rule (“neurons that fire together wire together”) is Δw=η y x\Delta\vb{w} = \eta\, y\,\vb{x} with y=w⊤xy = \vb{w}\T\vb{x} a linear neuron’s output: weight grows when input and output coincide. Its problem is obvious: w\vb{w}‘s norm grows without bound. Oja (1982) proposed normalization. If ∥w∥=1\norm{\vb{w}} = 1, update and normalize to obtain w′=(w+ηyx)/∥w+ηyx∥\vb{w}' = (\vb{w} + \eta y\vb{x})/\norm{\vb{w} + \eta y\vb{x}}, and since ∥w+ηyx∥2=1+2ηy2+O(η2)\norm{\vb{w} + \eta y\vb{x}}^2 = 1 + 2\eta y^2 + \bigO(\eta^2), the normalization factor is 1−ηy2+O(η2)1 - \eta y^2 + \bigO(\eta^2), yielding

w′=w+η y x∥w+η y x∥\vb{w}' = \dfrac{\vb{w} + \eta\, y\, \vb{x}}{\norm{\vb{w} + \eta\, y\, \vb{x}}}
Hebb's rule followed by normalization, starting with ∥w∥=1\norm{\vb{w}} = 1.
1/4

Oja’s rule is thus wt+1=wt+ηt yt(xt−ytwt)\vb{w}_{t+1} = \vb{w}_t + \eta_t\, y_t(\vb{x}_t - y_t\vb{w}_t) with yt=wt⊤xty_t = \vb{w}_t\T\vb{x}_t: Hebb with a forgetting term −y2w-y^2\vb{w} proportional to squared output. (The block version is the stochastic power method: W←orth⁡(W+η C^BW)\mat{W} \leftarrow \operatorname{orth}(\mat{W} + \eta\,\hat{\mat{C}}_B\mat{W}) with C^B\hat{\mat{C}}_B the block covariance and orth⁡\operatorname{orth} a QR factorization; for kk 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): wt+1=wt+ηt h(wt,xt)\vb{w}_{t+1} = \vb{w}_t + \eta_t\,\vb{h}(\vb{w}_t, \vb{x}_t) with mean field hˉ(w)=E[h(w,x)]=Cw−(w⊤Cw)w\bar{\vb{h}}(\vb{w}) = \E[\vb{h}(\vb{w}, \vb{x})] = \mat{C}\vb{w} - (\vb{w}\T\mat{C}\vb{w})\vb{w}. With rates satisfying ∑tηt=∞\sum_t\eta_t = \infty and ∑tηt2<∞\sum_t\eta_t^2 < \infty, sample noise averages out and the trajectory follows the mean differential equation

w˙=Cw−(w⊤Cw)w.\dot{\vb{w}} = \mat{C}\vb{w} - (\vb{w}\T\mat{C}\vb{w})\vb{w}.

Its fixed points are 0\vb{0} and ±vj\pm\vb{v}_j; only ±v1\pm\vb{v}_1 are stable (proof exercise), so under standard stochastic approximation assumptions the rule converges almost surely to ±v1\pm\vb{v}_1 (Oja and Karhunen, 1985, proved this for the rule). The mean equation gives more: in coordinates aj=vj⊤wa_j = \vb{v}_j\T\vb{w}, a˙j=(λj−w⊤Cw) aj\dot a_j = (\lambda_j - \vb{w}\T\mat{C}\vb{w})\,a_j, so ratio a2/a1a_2/a_1 satisfies  ⁣d ⁣dt(a2/a1)=(λ2−λ1)(a2/a1)\frac{\dd}{\dd t}(a_2/a_1) = (\lambda_2 - \lambda_1)(a_2/a_1) and

tan⁡∠(w(t),v1)≃tan⁡∠(w(0),v1)  e−(λ1−λ2) t,\tan\angle(\vb{w}(t), \vb{v}_1) \simeq \tan\angle(\vb{w}(0), \vb{v}_1)\; e^{-(\lambda_1 - \lambda_2)\,t},

with t=η⋅(number of samples)t = \eta\cdot(\text{number of samples}) for constant rate η\eta (the law is exact for the mean equation at d=2d = 2; in higher dimensions the tail is dominated by a2/a1a_2/a_1, decaying with λ1−λ2\lambda_1 - \lambda_2). Speed is set by spectral gap λ1−λ2\lambda_1 - \lambda_2: 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 v1\vb{v}_1 gives the fluctuation. In d=2d = 2, with w≈v1+a v2\vb{w} \approx \vb{v}_1 + a\,\vb{v}_2 and x1,x2x_1, x_2 the coordinates of x\vb{x} in the eigenbasis, one step gives, ignoring second-order terms in aa,

a′≈(1−η (x12−x22)) a+η x1x2.a' \approx \big(1 - \eta\,(x_1^2 - x_2^2)\big)\,a + \eta\,x_1 x_2 .

The factor has mean 1−η(λ1−λ2)1 - \eta(\lambda_1 - \lambda_2) and the forcing term has mean zero and variance η2λ1λ2\eta^2\lambda_1\lambda_2 (for Gaussian data, x1x_1 and x2x_2 are independent). Equating stationary variances on both sides to first order in η\eta,

E [tan⁡2∠(w,v1)]≈E [a2]≈η λ1λ22(λ1−λ2).\E\,[\tan^2\angle(\vb{w}, \vb{v}_1)] \approx \E\,[a^2] \approx \frac{\eta\,\lambda_1\lambda_2}{2(\lambda_1 - \lambda_2)} .

Amplitude increases with η\eta (as η\sqrt\eta) and explodes as the gap closes. The approximation requires that value to be small; otherwise the iterate wanders far from v1\vb{v}_1 and linearization fails. And if η\eta is so large that η∥x∥2\eta\norm{\vb{x}}^2 reaches order 1, the norm of w\vb{w} oscillates or diverges: the final common mistake.

InteractiveOja's rule finds the first component
  • v1\mathbf{v}_1 (principal direction)
  • last 60 samples
  • w\mathbf{w} trajectory
  • w\mathbf{w} now
Angular error log⁡10tan⁡∠(w,v1)\log_{10}\tan\angle(\mathbf{w}, \mathbf{v}_1) versus samples seen
  • learning rule
  • mean equation: tan⁡∠0 e−η(λ1−λ2)t\tan\angle_0\,e^{-\eta(\lambda_1 - \lambda_2)t}
  • predicted noise floor
Norm of w\mathbf{w}: log⁡10∥w∥\log_{10}\lVert\mathbf{w}\rVert (0 means norm 1)
1200
2.00
0.0200
∥w∥\lVert \mathbf{w} \rVert1.004
Angle to v1\mathbf{v}_13.02°
Theoretical rate η(λ1−λ2)\eta(\lambda_1 - \lambda_2) per sample0.0200
Samples to divide tan⁡∠\tan\angle by 10115
With constant η\eta, error stays above a floor. Measured (root mean of tan⁡2∠\tan^2\angle over the last 600 samples): 0.149. Predicted by linearization, ηλ1λ2/(2(λ1−λ2))\sqrt{\eta\lambda_1\lambda_2/(2(\lambda_1 - \lambda_2))}: 0.141 (purple line). It applies for a small floor; with a small gap or large η\eta it no longer holds.
3000 samples from a 2D Gaussian with λ1=2\lambda_1 = 2 arrive one at a time, with your chosen ratio λ1/λ2\lambda_1/\lambda_2. Press Play and watch w\mathbf{w} (orange) align with the principal direction (dashed), along with its trajectory. The upper plot compares angular error with the mean-equation prediction (gray dashed) and the noise floor predicted by linearization (purple): where does error stop falling? Move η\eta and watch the floor shift. Then set the ratio to 1.05 and raise η\eta to 0.3: compare speed and oscillation amplitude. Finally enable unnormalized Hebb and watch the norm: the direction still converges, the norm does not.

Before moving to decreasing rates, check the floor formula with the interactive’s model (λ1=2\lambda_1 = 2, Gaussian data in 2D). The cell starts at w=v1\vb{w} = \vb{v}_1, runs the rule at constant rate and averages tan⁡2∠\tan^2\angle over the last 45,000 of 60,000 samples.

[ ]Oja rule at constant rate: noise floor versus linearizationBrowser
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 (λ2=1\lambda_2 = 1), the formula works: measured-to-predicted ratio is 0.990.99 at η=0.005\eta = 0.005 and 1.031.03 at η=0.01\eta = 0.01, with fluctuation growing in proportion to η\eta. At η=0.03\eta = 0.03 the ratio is already 1.211.21: those are the η2\eta^2 terms ignored by linearization. With a small gap (λ2=1.6\lambda_2 = 1.6), the prediction, 0.080.08, is no longer small and the formula fails completely, with seed-dependent results (ratios of 1.741.74 and over 3000): the iterate no longer fluctuates near v1\vb{v}_1 but occasionally wanders almost perpendicular. This quantifies what the interactive shows as λ1/λ2\lambda_1/\lambda_2 approaches 1.

The next cell implements the rule with decreasing rate ηt=c/(t0+t)\eta_t = c/(t_0 + t) (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.

[ ]Oja rule with decreasing rate and its block versionBrowser
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 8.28.2, 3.93.9, 1.41.4 and 0.70.7 degrees with a large gap (λ1/λ2=4\lambda_1/\lambda_2 = 4), 23.523.5, 9.49.4, 4.54.5 and 2.32.3 with a medium gap (1.61.6), and 40.140.1, 20.020.0, 8.38.3 and 5.55.5 with a small gap (1.11.1): at the same sample count, small-gap error is 5 to 8 times greater. Final norm is 1.0001.000 or 1.0011.001 in all three: the forgetting term brings it to 1 without explicit normalization, as predicted by the mean equation. With blocks (k=3k = 3), the subspace reaches 2.12.1 degrees from population after 20000 samples, versus 1.11.1 for exact SVD on that same sample: the price of seeing data once with O(dk)\bigO(dk) memory.

Linear autoencoders and the principal subspace

A linear autoencoder compresses with one matrix and reconstructs with another: x^=DE x\hat{\vb{x}} = \mat{D}\mat{E}\,\vb{x} with E∈Rk×d\mat{E} \in \R^{k \times d} (encoder) and D∈Rd×k\mat{D} \in \R^{d \times k} (decoder), trained to minimize squared error L(D,E)=1n∑i∥xi−DExi∥2L(\mat{D}, \mat{E}) = \frac1n\sum_i\norm{\vb{x}_i - \mat{D}\mat{E}\vb{x}_i}^2 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 M=DE\mat{M} = \mat{D}\mat{E}, of rank at most kk. Then L=1n∥Xc−XcM⊤∥F2L = \frac1n\norm{\mat{X}_c - \mat{X}_c\mat{M}\T}_F^2 and B=XcM⊤\mat{B} = \mat{X}_c\mat{M}\T has rank ≤k\le k. By Eckart-Young, ∥Xc−B∥F2≥∑j>kσj2\norm{\mat{X}_c - \mat{B}}_F^2 \ge \sum_{j > k}\sigma_j^2, with equality if and only if B=(Xc)k=XcVkVk⊤\mat{B} = (\mat{X}_c)_k = \mat{X}_c\mat{V}_k\mat{V}_k\T (unique because σk>σk+1\sigma_k > \sigma_{k+1}). This value is attained with M=VkVk⊤\mat{M} = \mat{V}_k\mat{V}_k\T, for example D=Vk\mat{D} = \mat{V}_k and E=Vk⊤\mat{E} = \mat{V}_k\T: part 1. If M\mat{M} is a minimum, XcM⊤=XcVkVk⊤\mat{X}_c\mat{M}\T = \mat{X}_c\mat{V}_k\mat{V}_k\T, and since Xc\mat{X}_c has full column rank it is injective and M⊤=VkVk⊤\mat{M}\T = \mat{V}_k\mat{V}_k\T: part 2. For part 3, (DG−1)(GE)=DE(\mat{D}\mat{G}^{-1})(\mat{G}\mat{E}) = \mat{D}\mat{E}, so loss is unchanged.

∎

Part 3 answers “what does it learn?”: the subspace, not the axes. The k2k^2 degrees of freedom of G\mat{G} 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.)

InteractiveThe linear autoencoder learns the plane, not its axes
Loss gap and subspace distance (logarithmic scale)
  • L−L⋆L - L^\star
  • subspace distance
Autoencoder codes Ex\mathbf{E}\mathbf{x} versus PCA scores
  • PCA scores
  • autoencoder codes
  • radius-1.5 circle in scores
  • its image in the codes
5000
1
0.70
Loss LL (and optimum λ3\lambda_3)0.0930 (0.0930)
Distance between subspaces col⁡(D)\operatorname{col}(\mathbf{D}) and principal plane0.0000
Angle of first column of D\mathbf{D} to v1\mathbf{v}_136.9°
Angle of second column of D\mathbf{D} to v2\mathbf{v}_249.1°
Singular values of EV2\mathbf{E}\mathbf{V}_2 (1 and 1 for a rotation)0.90, 0.71
Imbalance ∥D⊤D−EE⊤∥F\lVert\mathbf{D}^\top\mathbf{D} - \mathbf{E}\mathbf{E}^\top\rVert_F1.560
Loss reaches the Eckart–Young optimum and the plane matches the principal plane, but columns of D\mathbf{D} are not v1\mathbf{v}_1 and v2\mathbf{v}_2. Imbalance barely changes during training (1.643 initially): lower initialization scale and the ellipse becomes a circle.
A 3→2→33 \to 2 \to 3 autoencoder trained by gradient descent on 300 3D points. Left: loss gap L−L⋆L - L^\star (red) and distance between the subspace of D\mathbf{D} and the principal plane (blue), on a logarithmic scale. Right: codes Ex\mathbf{E}\mathbf{x} (orange) versus PCA scores (gray). Press Train and watch loss reach the Eckart-Young optimum. Change the seed: what changes in angles between columns of D\mathbf{D} and v1\mathbf{v}_1 and v2\mathbf{v}_2, and what stays fixed? The purple curve is the image in code space of a circle of PCA scores. Is it a rotated circle or an ellipse? Reduce initialization scale to the minimum, retrain and compare: which quantity does not change during training?
[ ]Linear autoencoder by gradient descent: loss and PCA subspaceBrowser
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 (2.093332.09333, sum of remaining eigenvalues), and the subspace matches the principal one (angle 0.0000.000 degrees), but the first column of D\mat{D} forms 59.959.9, 85.585.5 and 43.343.3 degrees with v1\vb{v}_1 depending on seed, and singular values of EVk\mat{E}\mat{V}_k are 1.351.35, 1.081.08, 0.810.81 in the first. Since codes are Ex=(EVk) Vk⊤x\mat{E}\vb{x} = (\mat{E}\mat{V}_k)\,\mat{V}_k\T\vb{x} (at the minimum, E\mat{E} vanishes on the subspace complement), EVk\mat{E}\mat{V}_k 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 D\mat{D} compensating oppositely.

What determines which of infinitely many minima gradient descent chooses? A conserved quantity. With GM=∂L/∂M\mat{G}_M = \partial L/\partial\mat{M}, gradient flow is D˙=−GME⊤\dot{\mat{D}} = -\mat{G}_M\mat{E}\T and E˙=−D⊤GM\dot{\mat{E}} = -\mat{D}\T\mat{G}_M, so

 ⁣d ⁣dt(D⊤D)=−EGM⊤D−D⊤GME⊤= ⁣d ⁣dt(EE⊤),\tfrac{\dd}{\dd t}(\mat{D}\T\mat{D}) = -\mat{E}\mat{G}_M\T\mat{D} - \mat{D}\T\mat{G}_M\mat{E}\T = \tfrac{\dd}{\dd t}(\mat{E}\mat{E}\T),

and imbalance D⊤D−EE⊤\mat{D}\T\mat{D} - \mat{E}\mat{E}\T remains unchanged throughout training (the automatic layer-balancing phenomenon studied by Du, Hu and Lee, 2018, for linear and homogeneous networks). At a minimum, D=VkA\mat{D} = \mat{V}_k\mat{A} and E=A−1Vk⊤\mat{E} = \mat{A}^{-1}\mat{V}_k\T with A\mat{A} invertible, and imbalance is A⊤A−(A⊤A)−1\mat{A}\T\mat{A} - (\mat{A}\T\mat{A})^{-1}: zero if and only if A\mat{A} is orthogonal. The cell confirms this: imbalance norm is the same initially and finally up to finite-step error (1.5721.572 versus 1.5651.565 for the first seed), and with small initialization (scale 0.010.01) final imbalance is 0.00170.0017 and singular values of EVk\mat{E}\mat{V}_k are 1.0001.000: 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 kk using the appropriate criterion. In scikit-learn a Pipeline is natural: it ensures nothing is fitted on validation data within cross-validation.

[ ]PCA in a Pipeline: standardize, reduce and classify without leakageBrowser
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 0.6970.697 cross-validation accuracy; with standardized variables the same two components give 0.9550.955, and the 8 needed for 90% variance give 0.9780.978. 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 d(1−Rk)d(1 - R_k), with d=13d = 13.

Common mistakes

Exercises

ProofMaximum variance with Lagrange multipliers
Prove: The unit direction of maximum projected variance is an eigenvector of C\mat{C} associated with largest eigenvalue λ1\lambda_1; for kk orthonormal directions, the maximum of tr⁡(W⊤CW)\tr(\mat{W}\T\mat{C}\mat{W}) is given by the first kk eigenvectors.
0
Let C∈Rd×d\mat{C} \in \R^{d \times d} be symmetric positive semidefinite, with eigenvalues λ1≥⋯≥λd\lambda_1 \ge \dots \ge \lambda_d.

Step 1 of 4. What problem and Lagrangian do you write?

ProofProjected variance plus reconstruction error is constant
Prove: For any kk-dimensional subspace with orthonormal basis W\mat{W}, tr⁡(W⊤CW)+E(W)=tr⁡C\tr(\mat{W}\T\mat{C}\mat{W}) + E(\mat{W}) = \tr\mat{C}.
0
Let yi=xi−μ\vb{y}_i = \vb{x}_i - \vb{\mu} and let P=WW⊤\mat{P} = \mat{W}\mat{W}\T be the orthogonal projector onto the subspace.

Step 1 of 4. How do you decompose each yi\vb{y}_i?

ProofFixed points of Oja's mean equation
Prove: Let C\mat{C} be symmetric positive definite with distinct eigenvalues λ1>⋯>λd>0\lambda_1 > \dots > \lambda_d > 0. Fixed points of w˙=Cw−(w⊤Cw)w\dot{\vb{w}} = \mat{C}\vb{w} - (\vb{w}\T\mat{C}\vb{w})\vb{w} are 0\vb{0} and ±vj\pm\vb{v}_j; only ±v1\pm\vb{v}_1 are stable, and the other ±vj\pm\vb{v}_j (j≥2j \ge 2) are saddle points.
0
Let aj=vj⊤wa_j = \vb{v}_j\T\vb{w} and ρ(w)=w⊤Cw=∑jλjaj2\rho(\vb{w}) = \vb{w}\T\mat{C}\vb{w} = \sum_j\lambda_j a_j^2.

Step 1 of 4. How do you write the equation in coordinates aja_j?

NumericVariance of the first two components
A covariance has eigenvalues 5,3,1,15, 3, 1, 1. What fraction of variance do the first two components explain?
NumericFirst component of a 2x2 covariance
A covariance is C=(4223)\mat{C} = \begin{pmatrix} 4 & 2 \\ 2 & 3 \end{pmatrix}. What fraction of total variance is explained by the first component? (Three decimals.)
NumericDigits lost when forming covariance
A data matrix has condition number κ(Xc)=104\kappa(\mat{X}_c) = 10^4 and you work in float32 with ε=2−23\varepsilon = 2^{-23}. Estimate relative error of the smallest eigenvalue of Xc⊤Xc\mat{X}_c\T\mat{X}_c as ε κ(Xc⊤Xc)\varepsilon\,\kappa(\mat{X}_c\T\mat{X}_c). What value results? (Two decimals; a value above 1 means no correct digits.)
NumericSamples to one degree of error with Oja's rule
You use Oja's rule at constant rate η=0.01\eta = 0.01 on 2D data with eigenvalues λ1=3\lambda_1 = 3 and λ2=2.5\lambda_2 = 2.5, and the initial vector forms 6060 degrees with v1\vb{v}_1. According to the mean equation, how many samples reduce the angle to 11 degree? (Round to nearest integer; ignore the noise floor.)
CodeImplement pca_svd
Implement 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)
Shift+Enter to run
QuizWhat does a linear autoencoder learn?
You train a linear autoencoder x^=DEx\hat{\vb{x}} = \mat{D}\mat{E}\vb{x} with kk hidden units and squared loss on centered data with λk>λk+1\lambda_k > \lambda_{k+1}, to a global minimum. What is true?

More than one answer may be correct.

QuizChoosing k using test data
You want to select kk by validation. Fit PCA on training data and calculate test reconstruction error for each kk. What can you conclude?

More than one answer may be correct.

QuizWhich transformations preserve components?
You transform data before computing covariance PCA. In which cases do component directions remain essentially unchanged (undoing the transform if necessary)?

More than one answer may be correct.

QuizWhere is the leakage?
Which procedures for evaluating a classifier on PCA-reduced features leak information from test data?

More than one answer may be correct.

Summary

Key idea

PCA has two equivalent faces: maximum-variance direction and minimum-reconstruction-error subspace, united by Pythagoras (tr⁡C=v+e\tr\mat{C} = v + e). 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.