LINEAR ALGEBRA / 9. PCA FROM SCRATCH
PCA — Linear Algebra Perspective
Putting it all together: eigenvectors, SVD, projections
EXPLANATION
PCA (Principal Component Analysis) is one of the most important algorithms in data science, and it is pure linear algebra. Goal: find the orthogonal directions of maximum variance in high-dimensional data, and project data onto the top-k of these directions. Algorithm: 1. Center data: X_c = X - mean(X) 2. Compute covariance matrix: Σ = X_cᵀ X_c / (n-1) 3. Eigendecompose: Σ = Q Λ Qᵀ 4. Sort eigenvectors by eigenvalue (descending) 5. Project: X_pca = X_c @ Q_k (keep top k eigenvectors) Alternatively via SVD (more stable): 1. Center data 2. SVD: X_c = U Σ Vᵀ 3. Principal components = columns of V 4. Projected data = U Σ (or equivalently X_c @ V) Why it works: The eigenvectors of the covariance matrix are exactly the directions that capture the most variance. This is the "directions where the data spreads out most." In ML use cases: • Dimensionality reduction before training • Noise reduction • Data visualization (2D/3D projection) • Removing multicollinearity before linear models • Feature compression for memory-constrained settings
DIAGRAM
PCA on 2D data (correlated):
Original space: PCA space:
↑ y ↑ PC2
● | ● (noise)
● | ● ─────────→ PC1
| (main direction) (signal)
────────→ x
PC1 = eigenvector with largest eigenvalue
= direction of maximum variance
PC2 = perpendicular to PC1 (second most variance)
Eigenvalues tell you variance:
λ₁=8.2 (82%), λ₂=1.8 (18%)
Keep PC1 only → 82% of variance retained
Project from 2D → 1D
Scree plot:
λ │●
│ ●
│ ● ● ● ─── (elbow here)
└──────────── componentsCODE