Machine Learning

PCA as Optimization and Eigenspace Projection

PCA turns a centered data cloud into orthonormal directions that keep variance and minimize squared reconstruction error.

status: publishedimportance: criticaldifficulty 3/5math: undergraduateread: 20mlive demo

Concept Structure

PCA as Optimization and Eigenspace Projection

01Intuition

Start with the picture, metaphor, or geometric mechanism.

02Math

Make the objects explicit and connect them with notation.

03Code

Mirror the equations with runnable implementation details.

04Interactive Demo

Manipulate the mechanism and watch the idea respond.

2prerequisites
1next concepts
3related links

Learning map

PCA as Optimization and Eigenspace Projection
BeforeMatrix Decompositions: Eigendecomposition, SVD, and Spectral StructureNow4/4 sections readyTryManipulate one control and predict the visible change.NextAutoencoders and Denoising Autoencoders

Object flow

4/4 sections readyAsk about thisResearch room
ConceptPCA as Optimization and Eigenspace ProjectionMachine Learning
3 sources attachedLocal snapshot ready
concept:machine-learning/pca-optimization-eigenspace

Conceptual Bridge

What should feel connected as you move through this page.

Carry inMatrix Decompositions: Eigendecomposition, SVD, and Spectral Structure

Bring the mental model from Matrix Decompositions: Eigendecomposition, SVD, and Spectral Structure; this page will reuse it instead of restarting from zero.

Work herePCA as Optimization and Eigenspace Projection

PCA turns a centered data cloud into orthonormal directions that keep variance and minimize squared reconstruction error.

Carry outAutoencoders and Denoising Autoencoders

The next edge should feel earned: use the demo prediction here before following Autoencoders and Denoising Autoencoders.

Test the linkManipulate one control and predict the visible change.Then continue to Autoencoders and Denoising Autoencoders
01

01

Intuition

Build the mental picture first so the rest of the page has something to attach to.

Section prompt

Imagine a cloud of centered data points. You are allowed to replace each point by its shadow on a line, a plane, or some other low-dimensional flat subspace.

The honest question is:

Which subspace keeps the most of the cloud without pretending the missing directions are still there?

PCA gives one precise answer. It chooses directions where the centered cloud spreads out the most. If the first direction is wrong, the shadows collapse toward the origin and the representation loses information. If the first direction is right, the shadows still separate the points in a way that preserves much of the cloud's geometry.

The same answer appears from a second question:

Which subspace makes the squared reconstruction error as small as possible?

For centered data, these two questions are the same. Every point has a fixed squared distance from the origin. A projection splits that distance into retained length along the chosen subspace and lost perpendicular length. Making the retained part large makes the lost part small.

That is the reason PCA is more than a plotting button. It is a solved optimization problem:

choose an orthonormal subspace that maximizes retained variance, equivalently minimizes squared reconstruction error.

But it is not a magic detector of important features. PCA is unsupervised. It never sees labels, goals, causal structure, or semantic meaning. A high-variance direction can be useful, or it can be a unit-of-measure artifact, an outlier direction, or something unrelated to the downstream task.

02

02

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

Section prompt

Let

XRn×dX\in\mathbb R^{n\times d}

be a data matrix with nn observations as rows and dd features as columns. Define the feature mean

μ=1nXT1Rd,\mu = \frac1n X^{\mathsf T}\mathbf 1 \in\mathbb R^d,

and center the data:

Xc=X1μT.X_c = X - \mathbf 1\mu^{\mathsf T}.

The sample covariance matrix is

S=1n1XcTXcRd×d.S = \frac{1}{n-1}X_c^{\mathsf T}X_c \in\mathbb R^{d\times d}.

Some sources use 1/n1/n instead of 1/(n1)1/(n-1). That changes the eigenvalues by a constant factor, but it does not change the eigenvectors or explained-variance ratios.

The first principal direction solves

v1=argmaxv2=1vTSv.v_1 = \arg\max_{\|v\|_2=1} v^{\mathsf T}Sv.

The objective is the sample variance of the one-dimensional scores

z1=Xcv1.z_1 = X_cv_1.

Using a Lagrange multiplier for the constraint v2=1\|v\|_2=1 gives

Sv=λv.Sv = \lambda v.

So the maximizer is an eigenvector of SS. The best first direction is the eigenvector with the largest eigenvalue.

For kk components, collect the top orthonormal eigenvectors as columns of

Vk=[v1,,vk]Rd×k,VkTVk=Ik.V_k = [v_1,\ldots,v_k]\in\mathbb R^{d\times k}, \qquad V_k^{\mathsf T}V_k=I_k.

The loading directions viv_i are orthonormal. The score columns

Zk=XcVkRn×kZ_k = X_cV_k\in\mathbb R^{n\times k}

are uncorrelated because

1n1ZkTZk=VkTSVk=diag(λ1,,λk).\frac{1}{n-1}Z_k^{\mathsf T}Z_k = V_k^{\mathsf T}SV_k = \operatorname{diag}(\lambda_1,\ldots,\lambda_k).

The centered rank-kk reconstruction is

X^c,k=ZkVkT=XcVkVkT.\widehat X_{c,k} = Z_kV_k^{\mathsf T} = X_cV_kV_k^{\mathsf T}.

Then add the mean back:

X^k=X^c,k+1μT.\widehat X_k = \widehat X_{c,k} + \mathbf 1\mu^{\mathsf T}.

The retained variance is

tr(VkTSVk)=i=1kλi.\operatorname{tr}(V_k^{\mathsf T}SV_k) = \sum_{i=1}^{k}\lambda_i.

The lost squared reconstruction energy is

XcXcVkVkTF2.\|X_c - X_cV_kV_k^{\mathsf T}\|_F^2.

PCA chooses the same VkV_k for both objectives: it maximizes retained variance and minimizes this squared reconstruction error among rank-kk orthogonal projections.

The SVD makes the computation and reconstruction formula explicit. If

Xc=UΣVT,X_c = U\Sigma V^{\mathsf T},

then the principal directions are the right singular vectors in VV. The rank-kk centered reconstruction is

X^c,k=UkΣkVkT,\widehat X_{c,k} = U_k\Sigma_kV_k^{\mathsf T},

and the exact Frobenius reconstruction loss is

XcX^c,kF2=i>kσi2.\|X_c-\widehat X_{c,k}\|_F^2 = \sum_{i>k}\sigma_i^2.

The explained variance for component ii is

λi=σi2n1,\lambda_i = \frac{\sigma_i^2}{n-1},

and the explained-variance ratio is

σi2jσj2.\frac{\sigma_i^2}{\sum_j \sigma_j^2}.

Three caveats keep the geometry honest.

First, signs are arbitrary. If viv_i is a principal direction, then vi-v_i describes the same undirected line. Second, tied eigenvalues make the basis inside the tied subspace non-unique. Third, PCA is sensitive to scaling and outliers. Standardizing features can be essential when units differ, but it is not automatic truth; if scale itself carries meaning, standardizing may erase useful structure.

When PCA is used before a supervised model, it must also obey the split discipline: fit centering, scaling, and PCA on the training split only, then transform development and test data with that fitted preprocessing.

03

03

Code

Keep the implementation aligned with the notation so the algorithm is legible.

Section prompt
import numpy as np

X = np.array([[2.5, 2.4, 0.2],
              [0.5, 0.7, 0.1],
              [2.2, 2.9, 0.3],
              [1.9, 2.2, 0.2],
              [3.1, 3.0, 0.4],
              [2.3, 2.7, 0.3],
              [2.0, 1.6, 0.2],
              [1.0, 1.1, 0.1],
              [1.5, 1.6, 0.2],
              [1.1, 0.9, 0.1]])

mu = X.mean(axis=0)
Xc = X - mu
U, s, Vt = np.linalg.svd(Xc, full_matrices=False)
energy = s ** 2

print("explained variance ratio:", np.round(energy / energy.sum(), 3))

for k in [1, 2, 3]:
    Vk = Vt[:k].T
    Xhat = (Xc @ Vk) @ Vk.T + mu
    rel_fro = np.linalg.norm(X - Xhat, "fro") / np.linalg.norm(Xc, "fro")
    print(f"rank-{k} relative reconstruction error:", round(rel_fro, 4))

S = Xc.T @ Xc / (len(X) - 1)
eigvals, eigvecs = np.linalg.eigh(S)
order = eigvals.argsort()[::-1]
v_cov = eigvecs[:, order[0]]
v_svd = Vt[0]

print("top eigenvalue:", round(eigvals[order[0]], 4))
print("sign-invariant direction agreement:", round(abs(v_cov @ v_svd), 6))
print("top loading vector:", np.round(v_svd, 3))

The code centers the data before doing anything else. The SVD gives the principal directions, the explained-variance ratio shows how much squared energy each component carries, and the reconstruction loop shows how the relative Frobenius error drops as kk grows. The final dot product is absolute because the covariance eigenvector and SVD direction may point in opposite signs while representing the same PCA line.

04

04

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

Section prompt

The demo below hides the PCA answer until you commit.

Pick a dataset, inspect the centered scatter, and choose which undirected candidate line should be the first principal direction. Before reveal, the candidate lines are neutral labels, not hints. After reveal, the demo shows retained variance, reconstruction loss, projected shadow points, the true PCA line, and how the error changes when the reconstruction rank moves from k=1k=1 to k=2k=2.

The claim to test is simple:

the line that keeps the most variance is also the line with the smallest perpendicular reconstruction loss.

Live Concept Demo

Explore PCA as Optimization and Eigenspace Projection

The stage is code-native and interactive. Use it to test the explanation against the mechanism.

difficulty 3/5undergraduatecode-aligned
Demo Prediction Checkpoint

Manipulate one control and predict the visible change.

Commit to what PCA as Optimization and Eigenspace Projection should make visible before reading the result.

After The First Pass

Turn the concept into an inspected object.

Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.

Mechanism Storyboard

See the idea move before the page explains it

PCA turns a centered data cloud into orthonormal directions that keep variance and minimize squared reconstruction error.

Prediction open01 / Intuition
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change PCA as Optimization and Eigenspace Projection should make visible.

Visual Inquiry

Make the image answer a mathematical question

PCA turns a centered data cloud into orthonormal directions that keep variance and minimize squared reconstruction error.

4/4 stages readyLive demo connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make PCA as Optimization and Eigenspace Projection easier to reason about before the page gives the answer.

Source Grounding

Canonical references for the mechanism on this page.

course-notes · 2020CS229 Lecture Notes: Principal Components AnalysisStanford CS229

Source for PCA preprocessing, projected-variance maximization, covariance eigenvectors, top-k eigenvectors, and dimensionality-reduction framing.

Open source
book · 2020Mathematics for Machine LearningDeisenroth, Faisal, and Ong

Source for maximum-variance constrained optimization, projection/reconstruction error, covariance eigenspaces, and low-rank/SVD PCA perspectives.

Open source
book · 2021An Introduction to Statistical Learning, Second EditionJames, Witten, Hastie, and Tibshirani

Source for PCA as unsupervised learning, loadings and scores, centering, standardization, best low-dimensional approximation, and PCR caveats; using the official corrected June 2023 PDF of the 2nd edition.

Open source

Claim Review

PCA turns a centered data cloud into orthonormal directions that keep variance and minimize squared reconstruction error.

Status1 substantive review recorded

Claims without a substantive review badge still need exact source-support review.

Sources3 references

cs229-pca-notes, deisenroth-2020-mml-pca, islr2-pca-unsupervised

Witnesses4 local objects

Use equation, code, and demo objects to check whether the source support is operational.

Substantively reviewedFor centered data X_c, PCA chooses the top eigenspace of S = X_c^T X_c/(n-1), equivalently the top right-singular-vector subspace of X_c, maximizing retained projected variance and minimizing squared reconstruction error among rank-k orthogonal projections.Claim metadata: source checked

CS229 supports the projected-variance and covariance-eigenvector construction; MML supports the reconstruction-error and SVD equivalence; ISLR supports the scores/loadings, standardization, unsupervised use, best low-dimensional approximation, and predictive-caveat framing.

Sources: CS229 Lecture Notes: Principal Components Analysis, Mathematics for Machine Learning, An Introduction to Statistical Learning, Second EditionSigns are arbitrary; tied eigenspaces are basis-non-unique; scaling and outliers can dominate; PCA is linear/unsupervised, not causal importance or feature selection; high variance may miss labels; supervised pipelines fit PCA on train only.A bounded review summary is present; still check caveats and exact source scope.

Checked CS229 for centering, projected variance, covariance eigenvectors, and top-k PCA; MML for constrained optimization, reconstruction equivalence, and SVD/low-rank view; ISLR2 for scores/loadings, unsupervised framing, standardization, and PCR caveats. GPT Pro pre-draft review required exact centered reconstruction, orthonormal-directions versus uncorrelated-scores wording, undirected axes, no CS229 reconstruction overclaim, and train-only PCA caveat.

Reviewer: codex-source-scope+gpt-pro-brief; reviewed 2026-06-28

Practice Loop

Try the idea before it explains itself

PCA turns a centered data cloud into orthonormal directions that keep variance and minimize squared reconstruction error.

Readiness0/3 checks ready
Predict

Before touching the demo, predict one visible change that should happen in PCA as Optimization and Eigenspace Projection.

Hint 1

Reveal when your model needs a nudge.

Hint 2

Reveal when your model needs a nudge.

Hint 3

Reveal when your model needs a nudge.

Object research drawerClose
ConceptPCA as Optimization and Eigenspace ProjectionMachine Learning

Research Room

Attach the question to an exact object

Pick the concept, equation, source, code witness, claim, misconception, or demo state before asking for help. The handoff stays grounded to that object.
Next local actionNo local draft saved yet

Open the draft below to save one note and next action in this browser.

conceptMachine Learning

PCA as Optimization and Eigenspace Projection

Anchored question

What is the smallest example that makes PCA as Optimization and Eigenspace Projection click without losing the math?

Local action draftNo local draft saved yetExpand only when ready to capture one local next action
Local action draft

This draft stays locally in this browser for concept:machine-learning/pca-optimization-eigenspace.

No local draft saved.
Evidence to inspect
  • Source ids to inspect: cs229-pca-notes, deisenroth-2020-mml-pca, islr2-pca-unsupervised
  • Definition, prerequisite, and contrast concept links
  • The equation or code witness that makes the concept operational
  • One demo state that shows the invariant instead of a slogan
What would resolve this
  • The learner can state the mechanism in their own words
  • The learner can name the prerequisite that would repair confusion
  • The learner can predict how the mechanism changes under one perturbation
Grounded AI handoff

I am working in Continuous Function's research reading room. Object: concept - PCA as Optimization and Eigenspace Projection Object key: concept:machine-learning/pca-optimization-eigenspace Context: Machine Learning Anchor id: concept/concept-notebook/machine-learning/pca-optimization-eigenspace Open question: What is the smallest example that makes PCA as Optimization and Eigenspace Projection click without losing the math? Evidence to inspect: - Source ids to inspect: cs229-pca-notes, deisenroth-2020-mml-pca, islr2-pca-unsupervised - Definition, prerequisite, and contrast concept links - The equation or code witness that makes the concept operational - One demo state that shows the invariant instead of a slogan What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action.

Open source object
concept/concept-notebook/machine-learning/pca-optimization-eigenspace concept:machine-learning/pca-optimization-eigenspace