Lesson 3 of 9
Principal Component Analysis (PCA): Eigenvectors, Explained Variance & Whitening
Principal Component Analysis (PCA) is an orthogonal linear transformation that projects high-dimensional data onto a lower-dimensional subspace while maximizing explained variance. Mathematically, PCA computes the eigenvectors and eigenvalues of the feature covariance matrix: Cov(X) = (1/n) X^T X. The first principal component aligns with the direction of maximum variance; subsequent orthogonal components capture remaining variance. PCA reduces feature dimensionality, combats the curse of dimensionality, and eliminates multicollinearity.
Eigenvalue Decomposition & Cumulative Variance Scree Plot
import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_breast_cancer
# Ingest high-dimensional dataset (30 continuous features)
raw = load_breast_cancer(as_frame=True)
X_raw = raw.data
# 1. STANDARDIZATION IS MANDATORY (PCA is variance-maximizing; unscaled features dominate)
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X_raw)
# 2. FULL DIMENSION PCA DECOMPOSITION
pca_full = PCA(random_state=42)
pca_full.fit(X_scaled)
# Explained variance ratios
exp_var = pca_full.explained_variance_ratio_
cum_var = np.cumsum(exp_var)
print("=== PCA VARIANCE EXPLAINED (Top 6 Components) ===")
for i in range(6):
print(f"PC{i+1}: {exp_var[i]*100:5.2f}% of variance (Cumulative: {cum_var[i]*100:5.2f}%)")
# 3. AUTOMATED 95% VARIANCE PRESERVATION THRESHOLD
pca_95 = PCA(n_components=0.95, random_state=42) # Automatically selects components for 95% variance
X_reduced = pca_95.fit_transform(X_scaled)
print(f"\nDimensionality reduced from {X_scaled.shape[1]} features to {X_reduced.shape[1]} principal components!")
print(f"Retained Variance: {np.sum(pca_95.explained_variance_ratio_)*100:.2f}%")
# 4. INSPECT FEATURE LOADINGS (Eigenvectors)
pc1_loadings = pd.Series(pca_95.components_[0], index=raw.feature_names).abs().sort_values(ascending=False)
print("\nTop 5 Features Driving Principal Component 1 (Loadings):")
print(pc1_loadings.head(5).round(4).to_string())Pro Tip: What is PCA Whitening?
Setting `whiten=True` in `PCA` divides each principal component by the square root of its eigenvalue. This scales all components to unit variance and removes linear correlations, transforming the covariance matrix into an identity matrix. Whitening is beneficial when feeding inputs into neural networks or distance-based algorithms.
PCA for preprocessing. UMAP for viz.
Hands-On Challenge: Build a Reconstruction Error Auditor
Project data into k=2 principal components with `pca.transform(X)`, then project back into original feature space with `pca.inverse_transform(X_pca)`. Compute the reconstruction Mean Squared Error `||X - X_reconstructed||²` and observe how it drops to zero as k approaches p.
Quick Quiz & Key Concept Checks
Common Pitfall: Fitting PCA on the Entire Dataset Before Splitting
Fitting PCA before train-test splitting allows test set variance and eigenvalue structures to leak into the transformation matrix. Always encapsulate PCA inside a Scikit-Learn `Pipeline`.