7 routes42 sections324 units

Unit 4.3 · about 5 h

154 / 324

PCA via SVD: directions, explained variance and sign ambiguity

PCA is the baseline representation for wide tabular data and the preprocessing step inside the clustering and anomaly cards. Its signs are arbitrary, so any test that hard-codes them is wrong.

  • derive
  • implement

You can now

  • Derive PCA projection, explained variance and reconstruction error from the SVD of the centered matrix.
  • Implement PCA from a blank file and match scikit-learn up to sign flips and component order.
  • Choose the component count from cumulative explained variance and reconstruction cost, and write tests invariant to sign.

Covers

  • Centered PCA, SVD and principal directions
  • Explained variance, reconstruction error and component choice
  • PCA sign ambiguity and invariant tests

Study, in this order

3 steps

  1. PCA from SVD to model selection
    Hands-On Machine Learning with Scikit-Learn and PyTorch - dimensionality reduction and unsupervised learning

    Book Chapter 7: PCA, from Preserving the Variance through Incremental PCA (printed pp. 227-236). Notebook 07 cells: PCA through Choosing the Right Number of Dimensions: manual SVD of X_centered as U S Vt, Using Scikit-Learn, Explained Variance Ratio, the cumsum rule for the component count; PCA for Compression; Randomized PCA with svd_solver and Incremental PCA

    Depth · Skip Random Projection, LLE and Extra Material Kernel PCA. They return in the visualization unit or later work.

  2. PCA orientation and solvers
    scikit-learn - decomposition, clustering and outlier detection

    2.5.1 PCA: centering without scaling, components_ orientation and the whiten option; 2.5.1.3 randomized SVD cost and the inexact inverse_transform note; 2.5.1.2 IncrementalPCA partial_fit behavior

  3. PCA lab with scaling and sign
    ISLP - Unsupervised Learning

    Principal Components Analysis on USArrests: scaling before PCA, scores via transform, the biplot with its y-axis reflection note, standard deviations and PVE with the scree plot

Focus on

  • PCA centers but does not scale. Features in larger units dominate the first components; standardize first when units differ.
  • Component variance is \(s_j^2/(n-1)\); the ratio divides by the total. Randomized solvers approximate both.
  • Component signs are arbitrary: flipping a component with its scores leaves every reconstruction unchanged. Tests must use absolute values or reconstruction error.
  • The cumsum rule at 0.95 is a budget, not an optimum. Downstream error and cost decide the count.

Reproduce closed-book

Closed-book, center \(\left[\begin{smallmatrix}1&2\\3&4\\5&6\end{smallmatrix}\right]\), run the SVD, and report first component \(\left[\begin{smallmatrix}0.7071&0.7071\end{smallmatrix}\right]\), singular value 4 and explained ratio 1.0. Then state the sign-flip invariant and the reconstruction from one component.

Traps

  • Hard-coding component signs from one run. Sign conventions differ across libraries, solvers and versions; assert with abs or compare reconstructions.
  • Calling PCA(n_components=0.95) a fixed dimension. It selects whatever count reaches 95 percent on the fitted data; refitting on new data can change the width.
  • Using randomized-solver inverse_transform as exact. The docs note it is not the exact inverse of transform even with whiten=False.

Practice

Deep-ML 19: Principal Component Analysis Implementation

Problem 19: implement pca(X, k) with standardization, covariance, eigh and the stated sign rule

The two tests check \(k=1\) components \(\left[\begin{smallmatrix}0.7071\\0.7071\end{smallmatrix}\right]\) and \(\left[\begin{smallmatrix}0.7071\\-0.7071\end{smallmatrix}\right]\) on small matrices. Match the sign rule exactly: the first element with absolute value above 1e-10 is made positive.

Self-test

  1. Why do \(\left[\begin{smallmatrix}1&2\\3&4\\5&6\end{smallmatrix}\right]\) yield ratio 1.0 on one component?

  2. Two runs give components \(\left[\begin{smallmatrix}0.7&0.7\end{smallmatrix}\right]\) and \(\left[\begin{smallmatrix}-0.7&-0.7\end{smallmatrix}\right]\) with mirrored scores. Which one is wrong?

  3. Two features have variances 1 and 10000. What happens without scaling, and what changes with it?

  4. Randomized PCA reports slightly different ratios on each seed. Is that a bug?

Completion criterion

Stop when

Your blank-file PCA matches sklearn components up to sign and explained variance to 1e-6 on two datasets, and your tests still pass after negating any component.

Mark passed, then open 4.4 Only mark this when you can do it without notes.

Leads to

Comes after

Resources for this unit

Also in this section

  • Deep-ML - unsupervised problems
    Deep-MLsupportpractice
    Use 17 K-Means Clustering, 19 PCA, 341 Gaussian Mixture Model with EM, 259 DBSCAN and 367 Isolation Forest as unit checks after the local implementation passes. Their tests were read in review; each card states what they pin, including the 367 path-length convention.
  • scikit-learn - preprocessing data
    scikit-learnreferencereference
    Read 8.3.1 standardization with the sparse with_mean=False rule, 8.3.1.3 scaling data with outliers, and 8.3.4 categorical encoding with handle_unknown, infrequent and sparse_output behavior. Apply after the HOML notebook build works.
  • scikit-learn - pipelines and composite estimators
    scikit-learnreferencereference
    Read 8.1.1 Pipeline chaining with the no-leakage rule and transformer caching, and 8.1.4 ColumnTransformer for heterogeneous columns with remainder and fitted-state behavior. Use it to assemble and serialize the feature-selection pipeline.
  • scikit-learn - imputation of missing values
    scikit-learnreferencereference
    Read 8.4.2 univariate median and most_frequent strategies, 8.4.6 Marking imputed values with MissingIndicator or add_indicator=True for missingness flags, and 8.4.7 estimators that accept NaN directly. Decide impute-only versus impute-plus-indicator per column.
  • UMAP - basic usage and parameters
    McInnes, Healy and the UMAP contributorsreferencereference
    Work the Penguin scaling and fit_transform section and the Digits fit and transform section, then read the parameters page for the n_neighbors local-global tradeoff and min_dist packing. Stay in 2D exploratory views with fixed seeds.

Quick find

Search Michi

Type to search every route, section, unit, topic and resource.

Enter opens the first result Esc closes

Reference

Keyboard shortcuts

n
Continue to the first unit not passed
j / k
Next / previous unit
1 2 3
Toggle learned, practised, passed
/
Open search
?
Show this help
Esc
Close open panels