"""Lecture 9: PCA really is an eigenvalue problem (full-data check). Recomputes the L9 digits PCA (all 1,797 rows, standardized) from first principles: eigendecompose the covariance matrix with np.linalg.eigh and check that sklearn's PCA finds the same directions (up to sign), the same eigenvalues, and the same explained-variance ratios -- and that the variance of the data projected onto the first component equals the top eigenvalue. """ import numpy as np from sklearn.datasets import load_digits from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler X, _ = load_digits(return_X_y=True) X_s = StandardScaler().fit_transform(X) n = X_s.shape[0] # the long way: covariance matrix, eigendecomposition, sort descending cov = X_s.T @ X_s / (n - 1) eigvals, eigvecs = np.linalg.eigh(cov) order = np.argsort(eigvals)[::-1] eigvals, eigvecs = eigvals[order], eigvecs[:, order] # the sklearn way pca = PCA(n_components=10).fit(X_s) # same eigenvalues gap = np.abs(pca.explained_variance_ - eigvals[:10]).max() print(f"top-10 eigenvalue gap (sklearn vs eigh): {gap:.2e}") # same directions, up to sign dots = np.abs(np.sum(pca.components_ * eigvecs[:, :10].T, axis=1)) print(f"|cos angle| between matched directions: {dots.min():.6f}") # explained variance ratio = eigenvalue share ratio_gap = np.abs( pca.explained_variance_ratio_ - eigvals[:10] / eigvals.sum() ).max() print(f"explained-variance-ratio gap: {ratio_gap:.2e}") # variance along the first component IS the top eigenvalue var_pc1 = (X_s @ eigvecs[:, 0]).var(ddof=1) print(f"Var(X w1) = {var_pc1:.4f} lambda_1 = {eigvals[0]:.4f}") assert gap < 1e-8 and dots.min() > 1 - 1e-8 and ratio_gap < 1e-10 assert np.isclose(var_pc1, eigvals[0]) print("PCA = eigendecomposition of the covariance matrix. OK")