Principal Component Analysis
Imagine a dataset with 10,000 gene-expression measurements per patient. Only a few hundred patients are available, though. Most of that variation is redundant. Genes co-express in pathways. The "true" degrees of freedom are far fewer than 10,000. Principal Component Analysis (PCA) finds the small set of directions in feature space. These directions capture as much of this variation as possible. This lets you compress, visualize, and denoise high-dimensional data without a label in sight. PCA is the oldest and most widely deployed method in unsupervised learning. It is embedded quietly inside preprocessing pipelines, compression codecs, finance risk models, and computer vision systems. It answers a deceptively simple question. If you are allowed only numbers to summarize each data point, which linear combinations of the original features preserve the most information? Information here is measured by variance. The answer turns out to be exactly computable. There is no iterative optimization, no local minima, no hyperparameter search. It works via an eigendecomposition of the covariance matrix. The big picture is that data with correlated features lives, approximately, on a lower-dimensional linear subspace. This subspace is embedded in the ambient space. PCA discovers this subspace by rotating the coordinate system. The rotation aligns it with the axes of maximal spread. These are the principal axes of the data's covariance ellipsoid. PCA then truncates to the top few axes. This single geometric idea supports dimensionality reduction and noise filtering. It also enables visualization of high-dimensional data in 2D or 3D. Additionally, it supports feature decorrelation before other algorithms, and compression. This article develops PCA from its variance-maximization objective. It derives the eigenvector solution rigorously. It gives working pseudocode and traces a full numerical example. It also situates PCA relative to its generalization, the Singular Value Decomposition. Finally, it connects PCA to its nonlinear successors in Manifold Learning and Nonlinear Dimensionality Reduction.
- PCA finds orthogonal directions (principal components) that successively maximize the variance of projected data.
- The solution is the eigenvectors of the empirical covariance matrix, ordered by eigenvalue (explained variance).
- Projecting onto the top eigenvectors gives the best rank- linear approximation in squared-error sense.
- Complexity is for points in dimensions; the eigendecomposition dominates when is large.
- PCA requires centering (and often scaling) data first; it is sensitive to feature scale and outliers.
- It is equivalent to the Singular Value Decomposition of the centered data matrix, which is the numerically preferred way to compute it.
PCA rotates coordinates to the eigenvectors of the covariance matrix, ranking directions by variance so that keeping the top gives the best possible rank- linear summary of the data.
The idea
Let be a data matrix of observations in dimensions, with rows . Assume the data is centered, meaning the column means have been subtracted so . The empirical covariance matrix is
is symmetric and positive semi-definite. PCA seeks a unit vector , , such that projecting each data point onto — computing the scalar score — maximizes the variance of the resulting scores . This is the first principal component direction. Subsequent components are chosen the same way, subject to being orthogonal to all previous directions, so that each new component captures the maximal remaining variance. The key terminology: is the -th principal component (also called a loading vector or eigenvector); the projected value is the score; the variance captured, , is the eigenvalue associated with ; and is the fraction of explained variance. Collecting the top components as columns of a matrix , the transformation maps each observation to a -dimensional code, and reconstructs an approximation back in the original -dimensional space. Crucially, PCA is a linear, unsupervised, variance-based method — related to but distinct from methods built on Distance Metrics and Similarity Measures like multidimensional scaling, and it makes no use of labels, unlike supervised dimensionality reduction such as linear discriminant analysis. It assumes that variance is a good proxy for "information" and that the interesting structure is linear; when that assumption fails, nonlinear techniques discussed under Manifold Learning and Nonlinear Dimensionality Reduction become necessary.
How it works
Step 1 — Center (and optionally standardize) the data. Subtract the mean of each feature so the cloud of points is centered at the origin. If features are on very different scales (e.g., income in dollars vs. age in years), divide each feature by its standard deviation as well; this variant is PCA on the correlation matrix rather than the covariance matrix.
Step 2 — Compute the covariance matrix. , a symmetric matrix whose entry is the sample covariance between feature and feature .
Step 3 — Eigendecompose . Since is symmetric positive semi-definite, the spectral theorem guarantees a full set of real, non-negative eigenvalues with a corresponding orthonormal set of eigenvectors . These eigenvectors are exactly the principal component directions, and the eigenvalue equals the variance of the data when projected onto .
Step 4 — Truncate. Keep the top eigenvectors (largest eigenvalues) forming , chosen either as a fixed number or by requiring cumulative explained variance to exceed a threshold (e.g., 95%).
Step 5 — Project / reconstruct. Compute scores for compression or visualization, and reconstruct as a denoised low-rank approximation. Why does maximizing variance under orthogonality yield eigenvectors of ? Consider the first component: maximize subject to . Using a Lagrange multiplier ,
and setting the gradient to zero gives
So any stationary point must be an eigenvector of , and the variance achieved there is . To maximize variance, pick the eigenvector with the largest eigenvalue. For the second component, maximize subject to and ; the same Lagrangian argument (with an added orthogonality multiplier) shows the optimum is the eigenvector with the next-largest eigenvalue, and inductively for all . This is precisely why the eigenvectors of , sorted by eigenvalue, solve the sequential variance-maximization problem exactly — no iterative search is needed in principle, though in practice numerical eigensolvers are themselves iterative. ``` ALGORITHM PCA(X, k) Input: X, an n × p data matrix (n samples, p features) k, target number of components (k <= p) Output: W_k (p × k matrix of principal directions) Z (n × k matrix of projected scores) explained_variance_ratio (length-k vector) // Step 1: center the data (mean-subtraction is mandatory) mu <- column_mean(X) // length-p vector Xc <- X - broadcast(mu) // n × p, mean-zero columns // (optional) standardize if feature scales differ wildly if standardize: sigma <- column_std(Xc) Xc <- Xc / broadcast(sigma) // Step 2: covariance matrix S <- (1 / (n - 1)) transpose(Xc) @ Xc // p × p, symmetric PSD // Step 3: eigendecomposition S = V diag(lambda) * V^T (lambda, V) <- eigendecompose(S) // lambda: length-p, V: p × p sort (lambda, V) by lambda descending // lambda_1 >= lambda_2 >= ... // Step 4: truncate to top k eigenvectors W_k <- V[:, 1..k] // p × k // Step 5: project Z <- Xc @ W_k // n × k total_var <- sum(lambda) explained_variance_ratio <- lambda[1..k] / total_var return W_k, Z, explained_variance_ratio
ALGORITHM RECONSTRUCT(Z, W_k, mu) // approximate original data from k-dimensional codes Xhat <- Z @ transpose(W_k) + broadcast(mu) return Xhat ```
Complexity & correctness
Time complexity. Forming the covariance matrix costs (a times matrix product). Eigendecomposing the resulting symmetric matrix costs using standard dense methods (e.g., the symmetric QR algorithm after tridiagonalization). Total time is
When (many samples, few features), the term dominates and PCA scales linearly in . When is very large (e.g., features, moderate), the eigendecomposition becomes the bottleneck, and it is standard to instead perform the Singular Value Decomposition of the centered data matrix directly, , which costs and avoids explicitly forming (better numerically conditioned, since squaring to get squares its condition number). The right singular vectors equal the PCA loadings , and singular values relate to eigenvalues via . If only the top components are needed, randomized or Lanczos-based iterative methods compute them in roughly time, avoiding the full or cost entirely.
Space complexity. Storing costs ; storing costs ; the output and cost and . Total space is , dominated by the covariance matrix when is large relative to .
Correctness (why top- eigenvectors are optimal, not just a heuristic). Two equivalent formal justifications exist: Variance-maximization view. As derived above, the sequential constrained-optimization argument shows each successive principal direction is exactly the eigenvector of the covariance matrix with the next-largest eigenvalue — this is not approximate, it follows directly from setting the Lagrangian gradient to zero and using the spectral theorem's guarantee of an orthonormal eigenbasis for any real symmetric matrix. Best low-rank approximation view (Eckart–Young). PCA is equivalent to finding the rank- subspace minimizing reconstruction error:
Expanding this objective and using (Pythagoras, since is an orthogonal projection), minimizing reconstruction error is equivalent to maximizing , the total projected variance. So variance-maximization and squared-error-minimization are the same objective viewed from two sides — this is why PCA is simultaneously "the projection that preserves the most variance" and "the best possible linear compression under squared error," a fact formalized generally by the Eckart–Young theorem for the Singular Value Decomposition.
Honest tradeoffs.
- PCA only captures linear structure; data on a curved manifold (e.g., a Swiss roll) will not be well summarized by a few linear directions, motivating Manifold Learning and Nonlinear Dimensionality Reduction.
- PCA is sensitive to the scale of features — a feature measured in millimeters will dominate variance over one measured in kilometers unless standardized.
- PCA is sensitive to outliers, since variance (a squared quantity) is heavily influenced by extreme points; robust variants (e.g., PCA on ranks, or robust covariance estimators) exist for contaminated data.
- Interpretability of components can be poor: each principal component is a linear combination of all original features, unlike sparse or interpretable feature-selection methods.
Worked example
Consider two-dimensional points measuring (hours studied, exam score deviation from mean), already roughly linearly related:
| Point | (hours) | (score) |
|---|---|---|
| A | 1 | 2 |
| B | 3 | 4 |
| C | 5 | 5 |
| D | 7 | 8 |
| E | 9 | 9 |
Step 1 — center. Column means: , .
| Point | ||
|---|---|---|
| A | -4 | -3.6 |
| B | -2 | -1.6 |
| C | 0 | -0.6 |
| D | 2 | 2.4 |
| E | 4 | 3.4 |
Step 2 — covariance matrix. Compute entries with :
So
Step 3 — eigendecomposition. Solve :
Quadratic formula: .
Total variance (matches trace of , confirming the computation). Component 1 explains of the variance — expected, since the data lies almost exactly on a line. For : solve :
Normalizing to unit length ():
The second eigenvector is orthogonal: .
Step 4/5 — project. Score for point A, centered :
| Point | centered | score on PC1 |
|---|---|---|
| A | (-4, -3.6) | -5.40 |
| B | (-2, -1.6) | -2.57 |
| C | (0, -0.6) | -0.41 |
| D | (2, 2.4) | 3.10 |
| E | (4, 3.4) | 5.27 |
A single number per point (the PC1 score) now nearly reproduces the full 2D dataset, since PC1 captures 99.4% of the variance — exactly the compression PCA promises when features are strongly correlated.
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| Forgetting to center the data | Uncentered PCA conflates the mean with variance direction, giving a first "component" that mostly points toward the centroid | Always subtract column means before computing covariance |
| Ignoring feature scale | A feature in different units dominates variance trivially | Standardize (z-score) features when units differ, i.e., use the correlation matrix |
| Treating PCA as feature selection | Components are linear combinations of all features, not a subset | Use sparse PCA or explicit feature-selection methods if interpretability of individual features matters |
| Choosing arbitrarily | Too small discards signal; too large keeps noise | Use a scree plot / cumulative explained-variance threshold (e.g., 90–95%) |
| Assuming PCA finds "the" true underlying factors | PCA components are defined only up to sign and, for tied eigenvalues, rotation within the tied subspace; they need not align with causal or semantically meaningful axes | Interpret components with domain knowledge, not blind trust in axis meaning |
| Applying PCA blindly to nonlinear data | Curved manifolds are not well approximated by a linear subspace | Consider kernel PCA or methods under Manifold Learning and Nonlinear Dimensionality Reduction |
| Computing then eigendecomposing on very high-dimensional data | Forming squares the condition number and costs unnecessarily | Use the Singular Value Decomposition of directly, or randomized/truncated SVD for top- only |
Pioneers & history
Origins · 1 minKarl Pearson and how this was discovered
Pearson introduced the geometric idea behind PCA in 1901, framing it as finding "lines and planes of closest fit" to a system of points — the same reconstruction-error minimization later formalized rigorously via the Eckart–Young theorem.
Where this matters
PCA underlies preprocessing in nearly every machine learning pipeline that touches high-dimensional numeric data. In computer vision, Eigenfaces and related PCA-based methods compressed face images for recognition before deep learning dominated the field. In genomics, PCA reduces gene-expression or SNP data with tens of thousands of dimensions to a handful of components used for visualization and population-structure detection. In finance, PCA on asset return covariance matrices extracts common risk factors (level, slope, and curvature of yield curves are classic PCA-derived factors). In signal processing and sensor networks, PCA denoises data by discarding low-variance components assumed to be noise. Recommendation systems and NLP pipelines use PCA (or its close relative, Singular Value Decomposition, applied directly as in latent semantic analysis) to compress sparse high-dimensional representations before feeding them to downstream models. Almost every exploratory-data-analysis workflow begins with a PCA scatterplot to visually inspect clusters in two or three dimensions before deploying more expensive supervised or clustering methods.
Ask the tutor: How does PCA change if I compute it via the SVD of the data matrix instead of eigendecomposing the covariance matrix directly, and why is that usually the better choice numerically?
Is PCA the same as the Singular Value Decomposition?
They are closely related but not identical. PCA is the statistical problem of finding variance-maximizing directions; SVD is the linear-algebra tool commonly used to solve it. Applying SVD to the centered data matrix gives the PCA loadings directly as the columns of , and the eigenvalues of the covariance matrix relate to singular values via . Computing PCA via SVD directly on , rather than explicitly forming and eigendecomposing it, is numerically preferred because it avoids squaring the condition number of the data. See Singular Value Decomposition for the general matrix factorization this relies on.
How do I choose the number of components k?
Common approaches include: plotting cumulative explained variance and picking the smallest that exceeds a threshold like 90–95%; inspecting a "scree plot" of eigenvalues for an "elbow" where marginal variance gain drops sharply; and, when PCA is a preprocessing step for a supervised model, choosing by cross-validated downstream performance rather than variance alone. There is no universally correct — it depends on whether you prioritize compression, visualization (often ), or preserving signal for a later model.
Does PCA assume the data is Gaussian?
No distributional assumption is required for PCA to be well-defined — it is purely a statement about second moments (variances and covariances) of the data, valid for any distribution. However, PCA's optimality as a summary of all the information in the data is strongest when the data truly is close to Gaussian, since a Gaussian distribution is fully characterized by its mean and covariance. For strongly non-Gaussian data (e.g., heavy-tailed or multimodal clusters), variance may not capture the most meaningful structure, and other unsupervised methods may be more appropriate.
Can PCA handle nonlinear structure, like data lying on a curved surface?
Not directly — PCA only finds linear subspaces, so data on a curved manifold (a classic example is the "Swiss roll") will be poorly summarized by a few principal components even though its intrinsic dimensionality is low. Kernel PCA extends the idea by implicitly mapping data into a higher-dimensional feature space via a kernel function before finding linear components there, capturing some nonlinear structure. For genuinely nonlinear manifolds, dedicated techniques described under Manifold Learning and Nonlinear Dimensionality Reduction, such as Isomap or t-SNE, are typically more effective.
What happens if two eigenvalues of the covariance matrix are equal?
When , the corresponding eigenvectors are not uniquely determined — any orthonormal basis of the two-dimensional eigenspace they span is an equally valid choice of principal components, since all directions in that subspace yield the same projected variance. This is a genuine, not pathological, indeterminacy: it reflects true rotational symmetry in the data's covariance structure along those axes. Numerically, eigensolvers will still return some valid orthonormal basis, but it may vary slightly between runs or implementations, so components in a near-tied eigenvalue regime should not be over-interpreted individually.
Why do principal components come out with an arbitrary sign?
If is a unit eigenvector of with eigenvalue , then is also a unit eigenvector with the same eigenvalue, since . Both directions capture identical variance, so the eigendecomposition is only defined up to sign. This means the sign of any PCA component (and hence whether its scores are positive or negative for a given cluster) is an artifact of the numerical solver and carries no meaning — always check sign conventions before interpreting "high" versus "low" scores across different runs or software libraries.
Is PCA useful as a preprocessing step even if I plan to use a nonlinear model later?
Yes, commonly for two reasons: reducing dimensionality can mitigate the curse of dimensionality and overfitting when the number of features is comparable to or exceeds the number of samples, and decorrelating features can improve numerical stability and convergence speed for many downstream algorithms. However, if the discriminative signal for a supervised task lies in a low-variance direction (which PCA would discard), unsupervised variance-based reduction can hurt performance — in such cases, supervised dimensionality reduction or careful cross-validated selection of is safer than applying PCA blindly.