🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Principal Component Analysis (PCA) — Dimensionality Reduction

Foundations of StatisticsAdvanced Topics🟢 Free Lesson

Principal Component Analysis (PCA)

Foundations of Statistics

Reducing Dimensionality While Preserving Variance

PCA finds orthogonal directions of maximum variance in high-dimensional data. By projecting onto principal components, you reduce complexity while retaining the most informative structure in the data.

  • Genomics — Visualize thousands of gene expressions in 2D plots
  • Image Processing — Compress facial recognition features while preserving identity information
  • Finance — Extract key risk factors from correlated asset returns

The first few components often capture the essence that hundreds of variables conceal.


What You'll Learn

  • 1Derive the first principal component as the direction of maximum projected variance
  • 2Explain why principal components are eigenvectors of the covariance matrix
  • 3Decide between standardizing and using raw covariance, with a worked unit-mismatch example
  • 4Choose the number of components using scree, cumulative variance and parallel analysis

PCA finds orthogonal directions (principal components) of maximum variance in the data. Used for dimensionality reduction, visualization, and feature extraction. Its central claim is that most of the information in a correlated table of variables can be compressed into a handful of new variables without losing the structure that matters.

What the Algorithm Is Actually Optimising

Suppose each observation is a point in p-dimensional space and you want to describe the cloud with a single new variable. Restrict yourself to directions: pick a unit vector and project every observation onto it, giving scores . The variance of those scores is

Because must stay unit length, this is a constrained optimisation. The Lagrangian condition shows that the optimum is an eigenvector of the covariance matrix, and the achieved variance equals its eigenvalue. Maximising variance therefore means picking the eigenvector with the largest eigenvalue. Repeat on the residual space and you obtain the remaining components in descending order of eigenvalue.

Two consequences follow immediately. First, components are uncorrelated by construction, because eigenvectors of a symmetric matrix are mutually orthogonal, so replacing correlated inputs with components removes redundancy. Second, the sum of all eigenvalues equals the total variance of the original variables:

Compression never creates information; it repartitions the variance you already had.

Standardise, or Use the Raw Covariance?

This single decision changes the answer more than any other. PCA applied to a covariance matrix is dominated by variables measured on large scales, because variance grows with the square of the unit.

Consider two features of a house: floor area in square metres (mean 120, standard deviation 25) and price in thousands of currency units (mean 400, standard deviation 150). Their variances are 625 and 22,500. Even if price carried no more information than area, price alone would account for percent of total variance, so the first component would point almost entirely along the price axis and area would be discarded. Standardising both variables to unit variance makes each contribute 1, and the components then reflect correlation structure rather than measurement units.

SituationUseReason
All variables share units and similar spreadsCovariance matrix, no scalingScaling would destroy meaningful magnitude differences
Variables measured in different unitsCorrelation matrix, i.e. standardisePrevents the largest-variance variable from owning PC1
Features already normalized by a pipelineEither, but verify the variance ratiosRe-standardizing can quietly flatten real signal
Count data with wildly different meansStandardise, then consider a transformSkew and mean-variance coupling distort covariance

Standardising converts into the correlation matrix, whose diagonal entries are all 1. The practical rule is to standardise whenever you cannot defend leaving the variables on their original scales.

A Two-Variable Example, Worked by Hand

Two instruments measure the same latent quantity with independent noise, producing variables with covariance matrix

The characteristic equation gives and . Eigenvectors follow by substitution:

  • For : , so
  • For : , so

Total variance is , which matches . PC1 therefore explains percent of the variance and PC2 the remaining 25 percent. The interpretation is physical: PC1 is the shared signal, since both instruments load positively, and PC2 is the disagreement between them, since the loadings have opposite signs and equal magnitude. Dropping PC2 removes instrument noise while keeping the underlying measurement.

Note that the sign of an eigenvector is arbitrary. Flipping to yields the same variance and the same subspace; only the direction of the arrow on a biplot changes.

Choosing How Many Components to Keep

No single rule is decisive, so serious analyses use several at once. For six standardized variables the eigenvalues might come out as follows:

ComponentEigenvalueVariance explainedCumulative
PC13.6060.0%60.0%
PC21.5025.0%85.0%
PC30.6010.0%95.0%
PC40.203.3%98.3%
PC50.071.2%99.5%
PC60.030.5%100.0%
  • Scree plot. Look for the elbow where the curve flattens. Here the drop from 3.60 to 1.50 is steep and the drop from 1.50 to 0.60 is modest, placing the elbow after PC2.
  • Cumulative variance. Fix a budget, often 80 or 90 percent, and take enough components to reach it. This example needs two components for 85 percent and three for 95 percent.
  • Kaiser criterion. Retain components with eigenvalue greater than 1, which means the component explains more than one original standardized variable. Here PC1 and PC2 qualify.
  • Parallel analysis. Generate random data with the same n and p, compute their eigenvalues, and keep only components whose eigenvalue exceeds the 95th percentile of the random eigenvalues. This is the most defensible of the four because it compares against an explicit no-signal baseline.

Retaining too few components throws away structure; retaining too many reintroduces the noise you were trying to remove. When the downstream task is prediction, prefer cross-validated performance over any variance threshold.

Interpreting Loadings and Score Plots

The matrix of eigenvectors is usually called the loading matrix. Each entry is the weight of an original variable inside a component, and reading a component as a weighted sum of interpretable variables is what turns numbers into insight. Rules of thumb for reading a loading table:

  1. A component dominated by one or two large loadings is easy to name; a component with many moderate loadings of mixed sign is a contrast between variable groups and is often harder to interpret.
  2. Variables with near-zero loading on the components you keep contribute little and are candidates for removal.
  3. Cosine similarity between a variable's loading vector and a component axis gives how well that component represents the variable.

The score plot projects observations onto two components. Clusters, gradients, and outliers visible there are real geometric features of the projection, but they are only guaranteed to be preserved along the directions shown. A configuration that looks separated in PC1 and PC2 can overlap along PC3.

Computing PCA Two Ways in Python

python
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA

rng = np.random.default_rng(42)
n = 400
latent = rng.standard_normal((n, 2))
X = np.column_stack([
    3 * latent[:, 0] + rng.standard_normal(n),
    2 * latent[:, 0] + 0.5 * latent[:, 1] + rng.standard_normal(n),
    latent[:, 1] + rng.standard_normal(n),
    0.2 * latent[:, 0] + rng.standard_normal(n),
])
X = pd.DataFrame(X, columns=["area", "rooms", "age", "score"])

scaler = StandardScaler().fit(X)
Z = scaler.transform(X)

pca = PCA().fit(Z)
ev = pca.explained_variance_ratio_
print("eigenvalues:", np.round(pca.explained_variance_, 4))
print("variance %  :", np.round(ev * 100, 2))
print("cumulative %:", np.round(np.cumsum(ev) * 100, 2))
print("components for 80%:", int(np.searchsorted(np.cumsum(ev), 0.80) + 1))

loadings = pd.DataFrame(
    pca.components_.T,
    index=X.columns,
    columns=[f"PC{i+1}" for i in range(X.shape[1])],
)
print(loadings.round(3))
python
# Same result from first principles: SVD of the centred matrix
Zc = Z - Z.mean(axis=0)
U, s, Vt = np.linalg.svd(Zc, full_matrices=False)

eigenvalues = s ** 2 / (n - 1)
scores = U * s                       # identical to pca.transform(Z)
assert np.allclose(np.sort(eigenvalues)[::-1],
                   np.sort(pca.explained_variance_)[::-1], atol=1e-8)
assert np.allclose(np.abs(scores[:, 0]), np.abs(pca.transform(Z)[:, 0]), atol=1e-6)

# Variance explained is eigenvalue over total variance
ratios = eigenvalues / eigenvalues.sum()
print("PC1 share from SVD:", round(ratios[0], 4))

💡SVD beats the covariance eigendecomposition numerically

Forming squares the condition number, so for wide tables or near-collinear variables use the singular value decomposition of the centred matrix. That is what scikit-learn does internally, and it stays accurate where an explicit covariance matrix would lose precision.

PCA and Its Neighbours

MethodGoalPreservesCost
PCALinear compression of varianceGlobal variance, distances along kept axesEigendecomposition, cheap
Factor analysisInfer latent causes of covarianceCommon-factor structureRequires a factor model and rotation
t-SNEVisualise local neighbourhoodsLocal distances, clustersSlow on large n, distances not comparable across runs
UMAPVisualise local and some global structureNeighbourhood graphScales better than t-SNE
Linear discriminant analysisMaximise class separationBetween-class varianceNeeds class labels

PCA is unsupervised and linear. When classes are known and separation is the goal, LDA is the right tool; when the manifold is curved, no rotation of a linear subspace will unfold it and t-SNE or UMAP should be used for exploration rather than PCA.

Common Mistakes

Running PCA on unscaled features with different units

Fix: Standardize to unit variance, or justify the covariance matrix explicitly when all variables share units.

Choosing the component count from the 95 percent rule alone

Fix: Cross the scree elbow, cumulative variance and parallel analysis; for prediction, let cross-validation decide.

Reading component signs as meaningful

Fix: An eigenvector may be flipped without changing anything, so interpret the magnitude and pattern of loadings, not their overall sign.

Assuming PC1 and PC2 show the whole structure

Fix: Two components can hold a small share of total variance, and separation visible in 2D may not survive inspection of later components.

Best Practices

  • Report the eigenvalue spectrum and the cumulative variance alongside any PCA result
  • Standardize inside the cross-validation fold to avoid leaking information from the test set
  • Inspect the loading matrix before naming a component; a name without loadings is a guess
  • Keep the fitted scaler and PCA object together so new data is transformed identically

Key Takeaways

  • Principal components are eigenvectors of the covariance matrix, ordered by eigenvalue, and the eigenvalues sum to the total variance
  • Standardizing changes PCA from a scale-driven rotation to a correlation-driven one, which is usually what heterogeneous feature tables need
  • Cumulative variance, the scree elbow, the Kaiser rule and parallel analysis give four overlapping but not identical answers on component count
  • The hand-worked 2x2 example shows the mechanics: eigenvalues 3 and 1 mean PC1 holds 75 percent of the variance
  • PCA is linear and unsupervised; nonlinear manifolds need UMAP or t-SNE, and labelled problems need LDA

Interview Questions

Q1: Why do principal components come out uncorrelated?

They are eigenvectors of a symmetric matrix, and eigenvectors belonging to distinct eigenvalues are orthogonal. Orthogonal linear combinations of variables have zero covariance, so the components are mutually uncorrelated by construction.

Q2: When would you standardize before PCA and when would you not?

Standardize when variables have different units or wildly different spreads, because covariance-based PCA then follows whichever variable has the largest variance. Skip it when all variables share units and the magnitude of spread is itself meaningful.

Q3: How do you decide how many components to keep?

Look for the elbow in the scree plot, check how many components reach the variance budget you need, apply the Kaiser rule of eigenvalue above 1, and confirm with parallel analysis against random data. For a predictive pipeline, cross-validated accuracy overrides all of them.

Q4: What is the relationship between PCA and the singular value decomposition?

PCA of the centred data matrix is exactly the SVD of that matrix: singular values squared divided by n minus 1 give the eigenvalues, the right singular vectors give the loadings, and U times S gives the scores. SVD avoids forming the covariance matrix and is numerically safer.

Frequently Asked Questions

Does PCA require the variables to be normally distributed?

No. PCA is a geometric procedure built from means, variances and covariances, and it is defined for any data matrix. Normality only matters when you want inference on the components, such as confidence ellipses or hypothesis tests about eigenvalues. With heavily skewed variables a transform before PCA usually improves the interpretability of the resulting components.

What happens to missing values?

A covariance matrix cannot be computed from incomplete rows, so standard implementations either drop every row containing a gap or fail outright. Options are mean imputation, multiple imputation with pooling of the covariance matrix, or an expectation-maximisation PCA that estimates the covariance directly. Silent row deletion is the most common cause of a PCA that mysteriously loses hundreds of observations.

Is PCA a valid filter before supervised learning?

Yes, with one caveat: fit the scaler and the PCA inside each cross-validation fold. Fitting PCA on the full dataset first leaks information from the held-out fold into the features, inflating accuracy. With high-dimensional low-sample data the leak can be large enough to change model selection entirely.

How does sparse PCA differ?

Sparse PCA adds a penalty on the loadings so that each component uses only a few original variables. The price is that components no longer come from an eigendecomposition and variance explained is no longer guaranteed to be maximal. The benefit is interpretability, which is usually the deciding factor in genomics and text analysis where thousands of features are available.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Statistics Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement