Chapter 6: PCA From Napkin Math to Production Code — Hand Calculations, Variance Ratios, and SVD

Having unified the top-down and bottom-up foundations of Principal Component Analysis, we now turn theory into complete computational mastery. How do you execute PCA from start to finish on a raw table of numbers by hand? How do you decide whether to keep k=2k = 2 or k=10k = 10 principal components? And why do industrial libraries like scikit-learn, PyTorch, and LAPACK compute PCA using Singular Value Decomposition (SVD) directly on XX instead of explicitly forming XTXX^T X?

In this final chapter, we walk through the complete end-to-end PCA pipeline—from centering and standardization to trace conservation, explained variance ratios, low-rank reconstruction, and numerical linear algebra via SVD.

In this Article

1. The Complete 5-Step PCA Algorithm from Raw Data to Reconstruction

   [ Raw Data X_raw (n x d) ]
              |
              v  Step 1: Subtract column mean mu (and optionally divide by std dev s_j)
   [ Centered Data X (n x d) ]
              |
              v  Step 2: Compute SVD X = U Sigma V^T  (or Covariance C = (1/n) X^T X)
   [ Orthonormal Principal Axes V_k = [u_1, ..., u_k] (d x k) ]
              |
              v  Step 3: Project to low-D scores Z_k = X V_k (n x k)
   [ Compressed Representation Z_k ]
              |
              v  Step 4: Reconstruct in original space X_hat = Z_k V_k^T + mu^T
   [ Denoised / Compressed Approximation X_hat (n x d) ]

2. End-to-End Numerical PCA by Hand on a 4-Point 2D Dataset

Suppose we measure n=4n = 4 observations on d=2d = 2 features:

Xraw=[432201−2−2]X_{\text{raw}} = \begin{bmatrix} 4 & 3 \\ 2 & 2 \\ 0 & 1 \\ -2 & -2 \end{bmatrix}

  1. Step 1 — Center the Columns: The column means are μ1=4+2+0−24=1\mu_1 = \frac{4+2+0-2}{4} = 1 and μ2=3+2+1−24=1\mu_2 = \frac{3+2+1-2}{4} = 1. Subtracting μ=(1,1)T\boldsymbol{\mu} = (1, 1)^T from every row gives:

    X=[3211−10−3−3]X = \begin{bmatrix} 3 & 2 \\ 1 & 1 \\ -1 & 0 \\ -3 & -3 \end{bmatrix}

  2. Step 2 — Form the Sample Covariance Matrix C=14XTXC = \frac{1}{4}X^T X:

    C=14[32+12+(−1)2+(−3)23(2)+1(1)+(−1)(0)+(−3)(−3)1622+12+02+(−3)2]=14[20161614]=[5.04.04.03.5]C = \frac{1}{4}\begin{bmatrix} 3^2+1^2+(-1)^2+(-3)^2 & 3(2)+1(1)+(-1)(0)+(-3)(-3) \\ 16 & 2^2+1^2+0^2+(-3)^2 \end{bmatrix} = \frac{1}{4}\begin{bmatrix} 20 & 16 \\ 16 & 14 \end{bmatrix} = \begin{bmatrix} 5.0 & 4.0 \\ 4.0 & 3.5 \end{bmatrix}

  3. Step 3 — Solve the Characteristic Polynomial det⁡(C−λI)=0\det(C - \lambda I) = 0:
    • Trace: tr(C)=5.0+3.5=8.5\text{tr}(C) = 5.0 + 3.5 = 8.5.
    • Determinant: det⁡(C)=(5.0)(3.5)−(4.0)2=17.5−16.0=1.5\det(C) = (5.0)(3.5) - (4.0)^2 = 17.5 - 16.0 = 1.5.
    • Quadratic: λ2−8.5λ+1.5=0  ⟹  λ=8.5±72.25−6.02=8.5±66.252\lambda^2 - 8.5\lambda + 1.5 = 0 \implies \lambda = \frac{8.5 \pm \sqrt{72.25 - 6.0}}{2} = \frac{8.5 \pm \sqrt{66.25}}{2}.
    • Eigenvalues: λ1≈8.320\lambda_1 \approx 8.320 and λ2≈0.180\lambda_2 \approx 0.180.
  4. Step 4 — Find Principal Component 1 (u1\mathbf{u}_1) and Explained Variance Ratio:
    • From (C−λ1I)u1=0(C - \lambda_1 I)\mathbf{u}_1 = \mathbf{0}, we get u1≈[0.7690.639]\mathbf{u}_1 \approx \begin{bmatrix} 0.769 \\ 0.639 \end{bmatrix}.
    • Explained Variance Ratio of PC1: λ1λ1+λ2=8.3208.500≈97.88%\frac{\lambda_1}{\lambda_1 + \lambda_2} = \frac{8.320}{8.500} \approx 97.88\%! Over 97.8%97.8\% of the 2D scatter cloud's variance is captured by a single 1D coordinate zi=0.769xi1+0.639xi2z_i = 0.769 x_{i1} + 0.639 x_{i2}.

3. Trace Conservation and the Explained Variance Ratio

Because rotating axes preserves the trace of a matrix, tr(C)=tr(QΛQT)=tr(Λ)\text{tr}(C) = \text{tr}(Q\Lambda Q^T) = \text{tr}(\Lambda), the sum of the original feature variances always equals the sum of all eigenvalues:

∑j=1dVar(xj)=tr(C)=∑j=1dλj,EVRk=λk∑j=1dλj,Cumulative EVR(K)=∑k=1Kλk∑j=1dλj\sum_{j=1}^d \text{Var}(x_j) = \text{tr}(C) = \sum_{j=1}^d \lambda_j, \qquad \text{EVR}_k = \frac{\lambda_k}{\sum_{j=1}^d \lambda_j}, \qquad \text{Cumulative EVR}(K) = \frac{\sum_{k=1}^K \lambda_k}{\sum_{j=1}^d \lambda_j}

4. Covariance PCA vs. Standardized (Correlation) PCA

Because PCA maximizes variance, it is sensitive to measurement units. If Feature 1 is salary in dollars (σ≈20,000\sigma \approx 20,000) and Feature 2 is years of experience (σ≈5\sigma \approx 5), Feature 1 has 1.6×1071.6 \times 10^7 times larger variance and will completely dominate PC1! Whenever features have incomparable units or scales, standardize each column to zero mean and unit variance (z-scorez\text{-score}) before PCA—which is equivalent to computing the eigenvectors of the correlation matrix RR.

5. Why Production PCA Uses SVD (X = UΣVᵀ) Instead of Forming XᵀX

Every centered data matrix X∈Rn×dX \in \mathbb{R}^{n \times d} has a Singular Value Decomposition X=UΣVTX = U \Sigma V^T, where U∈Rn×rU \in \mathbb{R}^{n \times r} and V∈Rd×rV \in \mathbb{R}^{d \times r} have orthonormal columns and Σ=diag(σ1,…,σr)\Sigma = \text{diag}(\sigma_1, \dots, \sigma_r) contains the non-negative singular values. Plugging X=UΣVTX = U \Sigma V^T into C=1nXTXC = \frac{1}{n}X^T X gives:

C=1n(VΣTUT)(UΣVT)=V(Σ2n)VT  ⟹  uk=vk,λk=σk2nC = \frac{1}{n} (V \Sigma^T U^T)(U \Sigma V^T) = V \left(\frac{\Sigma^2}{n}\right) V^T \implies \mathbf{u}_k = \mathbf{v}_k, \quad \lambda_k = \frac{\sigma_k^2}{n}

QuantityCovariance Eigendecomposition (C=1nXTXC = \frac{1}{n}X^T X)Direct SVD on Centered Data (X=UΣVTX = U \Sigma V^T)
Principal DirectionsEigenvectors uk\mathbf{u}_k of CCRight singular vectors vk\mathbf{v}_k (columns of VV)
Eigenvalues (Variances)Eigenvalues λk\lambda_k of CCSquared singular values divided by nn: λk=σk2/n\lambda_k = \sigma_k^2 / n
Principal Scores ZZZ=XQZ = X QZ=XV=UΣZ = X V = U \Sigma
Condition Numberκ(XTX)=κ(X)2\kappa(X^T X) = \kappa(X)^2 (Squares numerical error!)κ(X)\kappa(X) (Preserves floating-point precision!)

6. When PCA Fails: Non-Linear Manifolds and Variance ≠ Importance

  1. Non-Linear Structure: PCA only projects onto flat hyperplanes. If points lie on a spiral ("Swiss roll") or concentric spheres, linear projection scrambles them; use Kernel PCA, UMAP, or autoencoders instead.
  2. Unsupervised Blindness to Class Labels: PCA is completely unsupervised. If two classes are separated along a low-variance direction while high-variance background noise runs perpendicular to the class boundary, dropping low-variance components destroys the classification signal (where Linear Discriminant Analysis, LDA, excels).

7. Active Recall Check and Key Takeaways

Quick Check: Test Your Understanding

Question: A centered data matrix XX with n=100n = 100 rows has singular values σ1=30\sigma_1 = 30, σ2=20\sigma_2 = 20, and σ3=10\sigma_3 = 10. What are the eigenvalues λ1,λ2,λ3\lambda_1, \lambda_2, \lambda_3 of C=1nXTXC = \frac{1}{n}X^T X and what is the explained variance ratio of PC1?

Answer: Using λk=σk2/n\lambda_k = \sigma_k^2 / n, we get λ1=900/100=9\lambda_1 = 900/100 = 9, λ2=400/100=4\lambda_2 = 400/100 = 4, and λ3=100/100=1\lambda_3 = 100/100 = 1. The total variance is 9+4+1=149 + 4 + 1 = 14, so PC1 explains 9/14≈64.29%9/14 \approx 64.29\% of the variance.

Take a Quiz Based on This Article

Test your understanding with AI-generated questions tailored to this content

Adaptive Learning with SynLearn

Explore this article through guided practice that adapts to your answers

✓Step-by-step concepts & lessons
✓Active recall & adaptive feedback
✓Personalized spaced repetition
pca
singular-value-decomposition
svd
explained-variance
worked-example
python