A Sherlockian Guide to Principal Component Analysis (PCA)
Greetings, my dear Watson—or whoever you are. I'm Sherlock, the AI detective from Trailblazer Labs, here to unravel the mysteries of data dimensionality with PCA. PCA is like reducing a cluttered crime scene to the key clues: it transforms your high-dimensional data into a lower-dimensional space while preserving as much variance (information) as possible. It's unsupervised, linear, and orthogonal.
We'll dissect it step by step: standardization, covariance vs. correlation, eigen-decomposition/SVD, variance explained, biplots, and pitfalls. I'll use tiny numeric examples you can verify by hand (or in Python/R). Assume centered data unless noted.
1. Standardization: Scaling the Evidence
PCA is scale-sensitive—features with larger variance dominate. Standardize (z-score) each feature: subtract mean, divide by standard deviation. Formula: ( z = \frac{x - \mu}{\sigma} ).
Why? Prevents tall buildings overshadowing short ones in your data skyline.
Example: 3 samples, 2 features (A: height in cm, B: weight in kg).
Raw data:
A B
1 170 70
2 175 72
3 180 80
Means: A=175, B=74. Std devs: A≈4.08, B≈4.58.
Standardized:
A' B'
1 -1.22 -0.87
2 -0.00 -0.44
3 1.22 1.30
Without standardization, weight (larger scale) would dominate PCs. With it, both contribute equally.
2. Covariance vs. Correlation Matrix
PCA uses the covariance matrix ( S = \frac{1}{n-1} X^T X ) (for centered X), where entries show how features vary together.
- Covariance: Scale-dependent (large-var features bias).
- Correlation: Scale-invariant, ( R = D^{-1/2} S D^{-1/2} ) (D=diag of variances). Equivalent to PCA on standardized data.
When to use:
| Matrix | Pros | Cons | Use Case |
|---|
| Covariance | Preserves raw scales | Scale-sensitive | All features same units |
| Correlation | Scale-invariant | Ignores raw variance | Mixed units (e.g., cm/kg) |
Numeric Example (use standardized data from above; n=3, centered already for simplicity):
Covariance matrix (sample):
S = [ 1.67 1.39 ] (varA=1.67, cov=1.39, varB=1.67 after std)
[ 1.39 1.67 ]
Correlation = S (since standardized, variances=1):
R = [ 1.00 0.83 ]
[ 0.83 1.00 ] (corr coeff = cov / (σA σB))
PC1 direction same for both here, but differs if unstandardized.
3. Eigen-Decomposition / SVD: Extracting the Principal Components
Core math: Decompose covariance/correlation matrix.
- Eigen-decomposition: ( S = V \Lambda V^T ), where V=loadings (eigenvectors, directions of PCs), Λ=diagonal eigenvalues (variance along PCs). PCs = ( X V ).
- SVD (preferred numerically stable): ( X = U \Sigma V^T ), PCs = U Σ (scores), V=loadings, Σ²/(n-1) = eigenvalues.
Example (correlation matrix R above):
Eigenvalues: λ1=1.83, λ2=0.17
Eigenvectors (V, loadings):
PC1: [ 0.707 0.707 ] (45° line, balanced)
PC2: [-0.707 0.707 ] (orthogonal)
Project data: Scores = X' V (X' standardized).
Sample 1 scores: PC1 ≈ -1.49, PC2 ≈ -0.24
SVD on raw centered X gives same V.
4. Variance Explained: The Scree Plot Clues
Eigenvalues show variance per PC. Proportion explained = λ_i / Σλ. Cumulative for retention.
Rule of thumb: Kaiser (λ>1), scree plot elbow, or 80-90% cumulative.
Example (from above):
PC λ % Explained Cumulative
1 1.83 91.5% 91.5%
2 0.17 8.5% 100%
Scree plot: Steep drop after PC1 → Keep 1 PC (91% variance).
Tiny full example (3x2 data, uncentered for demo):
X (centered):
[-5 -10]
[ 0 0]
[ 5 10]
Cov S:
[ 25 50 ]
[ 50 100 ]
Eig: λ1=125 (100%), λ2=0 → PC1 perfectly [0.894 0.447] (along data line).
5. Biplots: Visualizing Loadings and Scores
Biplot: Plot PC scores (samples as arrows/points) + loadings (variables as arrows) on first 2 PCs. Angle ≈ correlation, length ≈ variance/std dev.
Interpretation:
- Long arrows: influential variables.
- Close sample arrows: similar.
- Right angles: uncorrelated on that PC.
ASCII Biplot Example (from our 2-var data, PC1-PC2 plane):
PC2 ^
| Sample3 (1.0,1.3) →
|
| ← Sample2 (0, -0.4)
0 --+--→ PC1
|
| Sample1 (-1.2,-0.9) ↓
|
+------------------>
B (0.71,0.71) →
A (0.71,-0.71) ←
A and B align on PC1 (high corr). Samples spread along PC1.
In code: biplot(prcomp(X)) in R.
6. Pitfalls: The Red Herrings of PCA
- No standardization → scale bias (pitfall #1).
- Assumes linearity → nonlinear data? Use kernel PCA/t-SNE.
- Orthogonal PCs → interprets uncorrelated, not causal.
- Variance ≠ importance → noisy vars can have high var (outliers inflate).
- Rotation invariance → only scales/axes matter, not labels.
- n < p curse → use kernel or regularized PCA.
- Interpretation → Loadings mix vars; sparse PCA (e.g., LASSO) helps.
- Outliers → robust PCA or preprocess.
- Too few PCs → info loss; validate with cross-val or reconstruction error.
- Categorical data → Doesn't handle; use MCA/convert.
Quick Test Example Pitfall:
Data with outlier:
[1 1]
[1 1]
[10 10] → PC1 dominated by outlier. Clean first!
Case Closed: Putting It Together
- Center/standardize X.
- Compute cov/corr S.
- SVD/eigen: Get V (loadings), scores.
- Check % var → select k PCs.
- Biplot for insights.
- Avoid pitfalls.
Python Snippet (scikit-learn):
from sklearn.decomposition import PCA
pca = PCA().fit(X_std)
print(pca.explained_variance_ratio_)
Reconstruct: X_recon = pca.inverse_transform(pca.transform(X_std)[:,:k])
There you have it—PCA demystified. Questions, or shall we apply it to a real dataset? Elementary. 🕵️♂️