2.5.9Unsupervised Learning

PCA via eigendecomposition and SVD

2,471 words11 min readdifficulty · medium

Why PCA Matters

The Problem: Real data lives in high dimensions (thousands of features), but most variation happens in a lower-dimensional subspace. We want to:

  • Compress data (fewer dimensions → less storage, faster computation)
  • Visualize high-D data in 2D/3D
  • Denoise by keeping signal, dropping noise dimensions
  • Decorelate features for downstream algorithms

The Solution: Find orthogonal directions (principal components) ordered by how much variance they capture.

Method 1: Eigendecomposition of Covariance Matrix

Step 1: Center the Data

Start with data matrix XRn×d\mathbf{X} \in \mathbb{R}^{n \times d} (n samples, d features).

Xcentered=X1nμT\mathbf{X}_{\text{centered}} = \mathbf{X} - \mathbf{1}_n \boldsymbol{\mu}^T

where μ=1ni=1nxi\boldsymbol{\mu} = \frac{1}{n}\sum_{i=1}^n \mathbf{x}_i is the mean vector.

WHY? PCA finds directions of variance. Variance is measured from the mean, so we must center first. Without centering, the first PC would just point toward the mean from the origin—useless.

Step 2: Compute Covariance Matrix

C=1n1XcenteredTXcentered\mathbf{C} = \frac{1}{n-1}\mathbf{X}_{\text{centered}}^T \mathbf{X}_{\text{centered}}

WHY divide by n1n-1? Bessel's correction for unbiased variance estimation (1 degree of freedom lost to the mean).

Step 3: Eigendecomposition

Solve the eigenvalue problem:

Cvi=λivi\mathbf{C}\mathbf{v}_i = \lambda_i \mathbf{v}_i

This gives dd eigenvectors v1,,vd\mathbf{v}_1, \ldots, \mathbf{v}_d and eigenvalues λ1λ2λd0\lambda_1 \geq \lambda_2 \geq \ldots \geq \lambda_d \geq 0.

WHY eigenvalues = variance? Consider projecting centered data onto unit vector w\mathbf{w}:

Var(Xcenteredw)=1n1Xcenteredw2=wTCw\text{Var}(\mathbf{X}_{\text{centered}}\mathbf{w}) = \frac{1}{n-1}\|\mathbf{X}_{\text{centered}}\mathbf{w}\|^2 = \mathbf{w}^T\mathbf{C}\mathbf{w}

We want to maximize this subject to w=1\|\mathbf{w}\|=1. Using Lagrange multipliers:

L=wTCwλ(wTw1)\mathcal{L} = \mathbf{w}^T\mathbf{C}\mathbf{w} - \lambda(\mathbf{w}^T\mathbf{w} - 1)

Taking derivative w.r.t. w\mathbf{w} and setting to zero:

Lw=2Cw2λw=0    Cw=λw\frac{\partial \mathcal{L}}{\partial \mathbf{w}} = 2\mathbf{C}\mathbf{w} - 2\lambda\mathbf{w} = 0 \implies \mathbf{C}\mathbf{w} = \lambda\mathbf{w}

So w\mathbf{w} must be an eigenvector! Substituting back: Var=wTCw=λwTw=λ\text{Var} = \mathbf{w}^T\mathbf{C}\mathbf{w} = \lambda\mathbf{w}^T\mathbf{w} = \lambda. The eigenvalue is the variance along that direction.

Step 4: Project Data

To reduce to kk dimensions, project onto the top kk eigenvectors:

Z=XcenteredVk\mathbf{Z} = \mathbf{X}_{\text{centered}}\mathbf{V}_k

where Vk=[v1v2vk]Rd×k\mathbf{V}_k = [\mathbf{v}_1 \mid \mathbf{v}_2 \mid \ldots \mid \mathbf{v}_k] \in \mathbb{R}^{d \times k}.

Result: ZRn×k\mathbf{Z} \in \mathbb{R}^{n \times k} is the low-dimensional representation.

Method 2: Singular Value Decomposition (SVD)

Any matrix can be decomposed as:

Xcentered=UΣVT\mathbf{X}_{\text{centered}} = \mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^T

where:

  • URn×n\mathbf{U} \in \mathbb{R}^{n \times n} is orthogonal (left singular vectors)
  • ΣRn×d\boldsymbol{\Sigma} \in \mathbb{R}^{n \times d} is diagonal with singular values σ1σ20\sigma_1 \geq \sigma_2 \geq \ldots \geq 0
  • VRd×d\mathbf{V} \in \mathbb{R}^{d \times d} is orthogonal (right singular vectors)

Connection to Eigendecomposition

Start with the covariance matrix:

C=1n1XcenteredTXcentered\mathbf{C} = \frac{1}{n-1}\mathbf{X}_{\text{centered}}^T\mathbf{X}_{\text{centered}}

Substitute Xcentered=UΣVT\mathbf{X}_{\text{centered}} = \mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^T:

C=1n1(UΣVT)T(UΣVT)=1n1VΣTUTUΣVT\mathbf{C} = \frac{1}{n-1}(\mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^T)^T(\mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^T) = \frac{1}{n-1}\mathbf{V}\boldsymbol{\Sigma}^T\mathbf{U}^T\mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^T

Since UTU=I\mathbf{U}^T\mathbf{U} = \mathbf{I}:

C=1n1VΣTΣVT=V(ΣTΣn1)VT\mathbf{C} = \frac{1}{n-1}\mathbf{V}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\mathbf{V}^T = \mathbf{V}\left(\frac{\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}}{n-1}\right)\mathbf{V}^T

This is the eigendecomposition of C\mathbf{C}! The eigenvectors are the columns of V\mathbf{V}, and:

The singular values squared (divided by n1n-1) give the eigenvalues.

WHY use SVD?

  1. Numerical stability: Covariance matrix can be ill-conditioned; SVD avoids forming it
  2. Efficiency: For ndn \ll d (many features, few samples), SVD is faster
  3. Direct interpretation: U\mathbf{U} gives sample projections, V\mathbf{V} gives feature loadings

SVD-Based PCA Algorithm

1. Center the data: X_centered = X - mean(X, axis=0)
2. Compute SVD: U, Σ, V^T = SVD(X_centered)
3. Principal components: V (columns are PCs)
4. Eigenvalues: λ_i = σ_i² / (n-1)
5. Project to k dimensions: Z = X_centered @ V[:, :k]

Alternatively, use UΣ\mathbf{U}\boldsymbol{\Sigma}: the first kk columns of UΣ\mathbf{U}\boldsymbol{\Sigma} give the same projection.

Step 1: Center Mean: μ=[3,5.2]T\boldsymbol{\mu} = [3, 5.2]^T

Xcentered=[23.211.200.211.822.8]\mathbf{X}_{\text{centered}} = \begin{bmatrix} -2 & -3.2 \\ -1 & -1.2 \\ 0 & -0.2 \\ 1 & 1.8 \\ 2 & 2.8 \end{bmatrix}

Step 2: Covariance C=14XcenteredTXcentered=[2.53.753.755.7]\mathbf{C} = \frac{1}{4}\mathbf{X}_{\text{centered}}^T\mathbf{X}_{\text{centered}} = \begin{bmatrix} 2.5 & 3.75 \\ 3.75 & 5.7 \end{bmatrix}

Why this step? We're computing how much each feature varies and co-varies.

Step 3: Eigendecomposition Solve det(CλI)=0\det(\mathbf{C} - \lambda\mathbf{I}) = 0:

(2.5λ)(5.7λ)3.752=0(2.5-\lambda)(5.7-\lambda) - 3.75^2 = 0 λ28.2λ+0.1875=0\lambda^2 - 8.2\lambda + 0.1875 = 0

Using quadratic formula: λ18.18,λ20.02\lambda_1 \approx 8.18, \quad \lambda_2 \approx 0.02

Why this step? We're finding which directions capture the most variance. λ1\lambda_1 captures 99.8% of variance!

Eigenvector for λ1\lambda_1: v1[0.56,0.83]T\mathbf{v}_1 \approx [0.56, 0.83]^T (points along the elongated direction).

Step 4: Project to 1D Z=Xcenteredv1[3.8,1.6,0.2,2.1,3.5]T\mathbf{Z} = \mathbf{X}_{\text{centered}}\mathbf{v}_1 \approx [-3.8, -1.6, -0.2, 2.1, 3.5]^T

Interpretation: These 5 values summarize the original 2D data with minimal information loss (99.8% variance retained).

Xcentered=UΣVT\mathbf{X}_{\text{centered}} = \mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^T

Singular values: σ15.72\sigma_1 \approx 5.72, σ20.28\sigma_2 \approx 0.28

Check eigenvalue connection: λ1=σ12n1=32.724=8.18\lambda_1 = \frac{\sigma_1^2}{n-1} = \frac{32.72}{4} = 8.18 \quad \checkmark

Right singular vectors (columns of V\mathbf{V}) are the principal components: v1[0.56,0.83]T\mathbf{v}_1 \approx [0.56, 0.83]^T — same as eigendecomposition!

Why this works? SVD factors the data matrix itself; the right singular vectors automatically point in the maximum-variance directions.

Variance Explained

EVRk=i=1kλii=1dλi\text{EVR}_k = \frac{\sum_{i=1}^k \lambda_i}{\sum_{i=1}^d \lambda_i}

Practical use: Choose kk such that EVRk0.95\text{EVR}_k \geq 0.95 (retain 95% of information).

Total variance: 10.5+3.2+0.8+0.3+0.2=1510.5 + 3.2 + 0.8 + 0.3 + 0.2 = 15

kk Cumulative variance EVR
1 10.5 70%
2 13.7 91%
3 14.5 97%

Decision: Use k=3k=3 to retain 97% of variance (compress from 5D to 3D).

Common Mistakes

Why it feels right: "PCA is just eigendecomposition of the covariance matrix—why preprocess?"

The problem: Without centering, the first PC points from the origin to the data cloud's center (capturing location, not spread). You want variance around the mean, not from the origin.

The fix: Always center: X_centered = X - X.mean(axis=0). Standardizing (dividing by std) is optional but recommended if features have different units.


Why it feels right: "Bigger singular value = more important dimension."

The problem: Singular values scale with data magnitude and sample size. Eigenvalues have a specific interpretation as variance.

The fix: Convert correctly: λi=σi2n1\lambda_i = \frac{\sigma_i^2}{n-1}. Or use explained variance ratio: σi2jσj2\frac{\sigma_i^2}{\sum_j \sigma_j^2}.


Why it feels right: "PCA is dimensionality reduction—should work on any data."

The problem: PCA finds the best linear subspace. For non-linear structure (Swiss roll, circular clusters), linear projections destroy the geometry.

The fix: Use kernel PCA (implicitly maps to higher-D where structure is linear) or manifold learning methods (t-SNE, UMAP, Isomap).

Computational Complexity

| Method | Time Complexity | Space | Best When | |--------|-------------|--------| | Eigendecomposition of C\mathbf{C} | O(d2n+d3)O(d^2 n + d^3) | O(d2)O(d^2) | dnd \ll n (few features) | | SVD of X\mathbf{X} | O(min(nd2,n2d))O(\min(nd^2, n^2 d)) | O(nd)O(nd) | ndn \ll d (few samples) | | Randomized SVD | O(ndk)O(nd k) | O(nk)O(nk) | kdk \ll d, very large dd |

Practical tip: For d>10,000d >10{,}000, use randomized/truncated SVD (e.g., sklearn.decomposition.PCA with svd_solver='randomized').

Recall Explain to a12-Year-Old

Imagine you're taking photos of a pancake-shaped cloud of fireflies. From one angle (say, looking down), you see the whole cloud spread out—lots of variation. From another angle (edge-on), it looks thin—little variation. PCA is like finding the best camera angles automatically.

Here's how: You have a big spreadsheet of firefly positions (maybe 1000 dimensions—each firefly's brightness, position, speed etc.). PCA finds the "most interesting" directions—the ones where the data spreads out the most. Then you throw away the boring directions (where everything looks the same) and keep only 2-3 important ones. Now you can draw the cloud on paper!

The eigendecomposition way asks: "Which direction has the biggest variance?" It looks at how data points differ from the average and finds that direction mathematically (eigenvector of the covariance matrix).

The SVD way asks: "How can I break down the data itself into simple pieces?" It factors the data like 2×3=62 \times 3 = 6—but for giant matrices. Turns out, the pieces tell you the same important directions!

Both methods give you the same answer: here are your 2-3 magic camera angles. Compress your data, visualize it, and you're done!

SVP for SVD PCA:

  • SVD decomposition of centered X
  • V matrix = principal components
  • Variance = sigma² / (n-1)
  • Project: Z = XV_k

Connections

  • 2.5.07-K-Means-Clustering - PCA often used as preprocessing to speed up clustering
  • 2.5.01-Introduction-to-Unsupervised-Learning - PCA is a foundational unsupervised technique
  • 2.4.03-Feature-Scalingand-Normalization - Standardization before PCA equalizes feature importance
  • 3.2.05-Autoencoders - Non-linear generalization of PCA using neural networks
  • Linear-Algebra-Eigenvalues-and-Eigenvectors - Mathematical foundation of eigendecomposition
  • Linear-Algebra-SVD - SVD theory and applications beyond PCA
  • 2.6.04-Kernel-PCA - PCA extended to non-linear data

#flashcards/ai-ml

What does PCA stand for and what does it do? :: Principal Component Analysis finds orthogonal directions in data ordered by variance, enabling dimensionality reduction while preserving maximum information.

Why must data be centered before PCA?
PCA finds directions of maximum variance. Variance is measured from the mean, not the origin. Without centering, the first PC would point toward the mean from the origin, capturing location instead of spread.
What is the covariance matrix in PCA?
A symmetric matrix C=1n1XcenteredTXcentered\mathbf{C} = \frac{1}{n-1}\mathbf{X}_{\text{centered}}^T\mathbf{X}_{\text{centered}} where CijC_{ij} measures how features ii and jj co-vary. Diagonal entries are variances.
Why are eigenvectors of the covariance matrix the principal components?
Maximizing variance of projected data wTCw\mathbf{w}^T\mathbf{C}\mathbf{w} subject to w=1\|\mathbf{w}\|=1 leads to Cw=λw\mathbf{C}\mathbf{w} = \lambda\mathbf{w}. The eigenvector w\mathbf{w} is the direction of maximum variance, and λ\lambda is the variance along that direction.
What does an eigenvalue represent in PCA?
The variance captured along the corresponding principal component direction. Larger eigenvalues indicate directions with more data spread.
How do you compute explained variance ratio?
EVRk=i=1kλii=1dλi\text{EVR}_k = \frac{\sum_{i=1}^k \lambda_i}{\sum_{i=1}^d \lambda_i}, the fraction of total variance captured by the first kk components.
What is the SVD decomposition?
X=UΣVT\mathbf{X} = \mathbf{U}\boldsymbol{\Sigma}\mathbf{V}^T where U\mathbf{U} and V\mathbf{V} are orthogonal matrices and Σ\boldsymbol{\Sigma} is diagonal with non-negative singular values.
How do singular values relate to eigenvalues in PCA?
λi=σi2n1\lambda_i = \frac{\sigma_i^2}{n-1}. The eigenvalues are the squared singular values divided by n1n-1.
In SVD-based PCA, which matrix contains the principal components?
The matrix V\mathbf{V} (right singular vectors). Its columns are the principal components.
When should you use SVD instead of eigendecomposition for PCA?
When ndn \ll d (many features, few samples) for efficiency, or when numerical stability is a concern (eigendecomposition of C\mathbf{C} can be ill-conditioned).
How do you project data onto the first kk principal components?
Z=XcenteredVk\mathbf{Z} = \mathbf{X}_{\text{centered}}\mathbf{V}_k where Vk\mathbf{V}_k contains the first kk eigenvectors (columns of V\mathbf{V}).
What happens if you don't center data before PCA?
The first PC captures the location of the data cloud relative to the origin instead of the direction of maximum variance, making PCA meaningless.
Why doesn't PCA work well on non-linear data?
PCA finds the best linear subspace. Non-linear structures (spirals, curved manifolds) require non-linear methods like kernel PCA or manifold learning.
What is the time complexity of eigendecomposition-based PCA?
O(d2n+d3)O(d^2 n + d^3)—forming covariance matrix is O(d2n)O(d^2 n), eigendecomposition is O(d3)O(d^3). Best when dnd \ll n.
What is the time complexity of SVD-based PCA?
O(min(nd2,n2d))O(\min(nd^2, n^2 d)). Best when ndn \ll d (few samples, many features).

Concept Map

most variance in subspace

enables

center by mean

Method 1

eigendecomposition

eigenvectors are

eigenvalues equal

maximize w'Cw

Method 2

same result as

project data onto top-k

High-D data

Find principal components

Compress Visualize Denoise Decorrelate

Data matrix X

Centered data

Covariance matrix C

Eigenvectors and eigenvalues

Principal components

Variance explained

SVD of X

Hinglish (regional understanding)

Intuition Hinglish mein samjho

PCA ka matlab kya hai? Socho tumhare pas bahut sare features hain (matlab bahut dimensions mein data hai), lekin sabhi features equally important nahi hote. Kuch directions mein data bahut spread out hai, kuch mein bilkul tight. PCA ka kaam hai woh "most important" directions dhoondhna jahan pe maximum variation hai. Yeh do tareekon se ho sakta hai: eigendecomposition (covariance matrix ke eigenvectors nikalke) ya SVD (data matrix ko directly factor karke). Dono ka result same hota hai—PCA bata hai ki konse directions sabse zyada information capture karte hain.

Kyon zaroori hai? Real-world mein data kafi high-dimensional hota hai (jaise image = 1000s of pixels, text = 1000s of words). Lekin sach yeh hai ki zyada-tar variance sirf kuch hi directions mein hota hai. PCA un important directions ko pakad leta hai aur baki "noise" wale dimensions ko drop kar deta hai. Result: kam storage, faster computation, aur visualization bhi asaan (2D/3D plot bana sakte ho). Bonus: algorithms bhi fast chalte hain kyunki dimensions kam ho gaye!

Eigendecomposition method: Pehle data ko center karo (mean subtract karo). Phir covariance matrix banao—yeh bata hai features kaise co-vary karte hain. Iska eigendecomposition karo: eigenvectors woh directions hain jahan maximum variance hai, aur eigenvalues bate hain kitna variance hai. Top-k eigenvectors le lo = tumhare principal

Go deeper — visual, from zero

Test yourself — Unsupervised Learning

Connections