Probabilistic PCA, EM-PCA, Bayesian PCA, Factor Analysis

Probabilistic PCA, EM-PCA, Bayesian PCA, Factor Analysis

Backer ●1 ●6 ●22
calendar_today ago • schedule16 min read
— Originally published at sesen.ai

You're reducing a table of correlated measurements to a few components, but some values are missing and you also want to assess the uncertainty in the fit. Standard PCA gives you a compact representation without describing how the observations were generated. Probabilistic PCA adds a model of the observations and their noise, giving those further questions a place in the calculation.

Shrinkage priors let the Bayesian extension select components within the fit. Our Bayesian extension prunes six of nine, keeping three without a validation sweep. We implement Tipping and Bishop's (1999) model and Roweis's (1998) EM route in NumPy, then extend the noise assumptions to Factor Analysis and check missing values.

A working example: PPCA on a 2D blob

import numpy as np

def ppca_closed_form(X, M):
    """Maximum-likelihood PPCA via Tipping & Bishop 1999b."""
    N, D = X.shape
    mu = X.mean(axis=0)
    S = ((X - mu).T @ (X - mu)) / N
    eigvals, eigvecs = np.linalg.eigh(S)
    eigvals, eigvecs = eigvals[::-1], eigvecs[:, ::-1]  # descending
    sigma2 = float(np.mean(eigvals[M:])) if M < D else 0.0
    W = eigvecs[:, :M] @ np.diag(np.sqrt(np.maximum(eigvals[:M] - sigma2, 0)))
    return mu, W, sigma2

rng = np.random.default_rng(0)
theta = np.deg2rad(20.0)
R = np.array([[np.cos(theta), -np.sin(theta)],
              [np.sin(theta),  np.cos(theta)]])
X = (rng.standard_normal((120, 2)) * np.array([1.6, 0.35])) @ R.T

mu, W, sigma2 = ppca_closed_form(X, M=1)
print(f"W = {W.ravel()},  sigma^2 = {sigma2:.4f}")

Open In Colab

If you also run the EM version (later in the post) on the same data, both solutions land on the same 1D subspace and the same noise variance σ² ≈ 0.125.

Closed-form ML-PCA and EM-PCA recover the same subspace on a 2D tilted blob

That's the headline: PPCA gives you back standard PCA when you do the maximum likelihood by hand, but as a probabilistic model that you can extend in ways standard PCA cannot.

The latent variable picture

Standard PCA is a recipe: centre the data, eigendecompose the covariance, keep the top M eigenvectors. PPCA is a model. The two views describe the same algorithm, but the model view is what unlocks EM, Bayesian inference, missing data, and Factor Analysis.

The generative story is the linear-Gaussian model:

equation

Each data point starts life as an M-dimensional latent code z drawn from a standard Gaussian. The D × M matrix W lifts it into data space, you add the mean μ, and you sprinkle isotropic Gaussian noise. Picture an isotropic Gaussian spray-can moving across the principal subspace.

Marginalising out z gives a Gaussian in the data space:

equation

The covariance has a special structure: a low-rank piece WWᵀ (the signal) plus an isotropic noise floor σ² I. That low-rank-plus-isotropic shape is the entire content of PPCA. A standard D × D covariance matrix needs D(D + 1)/2 parameters, which gets unwieldy fast. PPCA needs just DM + 1 - M(M-1)/2, growing linearly with D. This is an elegant compromise between modelling all correlations (full covariance) and ignoring them (diagonal covariance).

The maximum-likelihood solution has a closed form that Tipping and Bishop derived analytically:

equation

The columns of U_M are the top-M eigenvectors of the data covariance, Λ_M holds the corresponding eigenvalues on the diagonal, R is an arbitrary M × M rotation that the model can't pin down (rotations in latent space leave WWᵀ unchanged), and σ²_ML is the average variance in the discarded directions, the noise floor. Read that last bit carefully. Standard PCA throws away D - M eigenvalues. PPCA keeps them around as a single number that quantifies how much variance the model attributes to noise.

EM-PCA: the iterative view

The closed-form solution requires forming and eigendecomposing the D × D data covariance, which is O(D³). For modest D that's fine, but in high dimensions it becomes expensive. EM-PCA gives you an iterative algorithm whose per-iteration cost is O(NDM), dominated by sums over data points rather than the full covariance.

The EM equations are short enough to write out in full:

E step: compute the sufficient statistics of the posterior p(zₙ | xₙ):

equation

M step: re-estimate W and σ² using those statistics:

equation

There's a beautiful physical analogy for what this is doing on a 2D dataset with a 1D latent space. Imagine the principal subspace as a rigid rod through the data, with each data point attached to it by a spring obeying Hooke's law. In the E step you fix the rod and let each point's projection slide along it to minimise spring energy (orthogonal projection). In the M step you fix the projections and let the rod rotate to its lowest-energy orientation. Alternate until convergence.

EM-PCA as a rod and springs. Starting from a near-perpendicular initialisation, the rod rotates step-by-step into the data direction while the springs (projection error) shorten

The EM implementation in NumPy is a direct transcription of those equations:

def ppca_em(X, M, n_iter=50, seed=0):
    rng = np.random.default_rng(seed)
    N, D = X.shape
    mu = X.mean(axis=0)
    Xc = X - mu
    W = rng.standard_normal((D, M)) * 0.1
    sigma2 = 1.0
    for _ in range(n_iter):
        M_mat = W.T @ W + sigma2 * np.eye(M)
        M_inv = np.linalg.inv(M_mat)
        Ez = Xc @ W @ M_inv                       # (N, M)
        Ezz_sum = N * sigma2 * M_inv + Ez.T @ Ez  # (M, M)
        W = (Xc.T @ Ez) @ np.linalg.inv(Ezz_sum)
        sigma2 = (np.sum(Xc**2)
                  - 2 * np.sum((Ez @ W.T) * Xc)
                  + np.trace(Ezz_sum @ (W.T @ W))) / (N * D)
    return mu, W, max(sigma2, 1e-10)

On the 2D blob from the quick-win, this lands on the same subspace as the closed form: cosine similarity between the two W vectors is 1.0 to six decimal places, and the two σ² estimates differ by less than 2 × 10⁻⁶. That's not a coincidence. The likelihood has a unique maximum (up to the rotation R and column permutations), and EM finds it.

EM-PCA also handles missing data transparently. Treat the missing entries as additional latent variables, infer them in the E step, and let the M step update W and σ² as if you had the full data. Drop 30% of entries at random from a 3D dataset and EM still recovers the underlying 2D structure:

EM-PCA reconstructs missing entries by treating them as extra latents

The middle panel shows only the points whose x₁ and x₂ were both observed (the rest have a NaN in one coordinate, so they don't show). The right panel shows EM's reconstruction, which recovers the full scatter pattern from the observed entries alone. No special pre-imputation, no row dropping, no IterativeImputer wrapper. The probabilistic model does it for free.

Bayesian PCA: choosing M automatically

Both ML-PCA and EM-PCA assume you already know M. In practice you don't. Cross-validation works but is expensive. Eigenvalue scree plots work when there's a clear gap, but the gap is often absent. Bayesian PCA gives you a principled answer by placing a prior on W that lets the data switch off unused dimensions.

The trick is Automatic Relevance Determination (ARD), the same mechanism behind Relevance Vector Machines. Place an independent Gaussian prior on each column wᵢ of W with its own precision αᵢ:

equation

If a particular αᵢ grows large during fitting, the corresponding column wᵢ is squeezed to zero, effectively switching off latent dimension i. Maximising the marginal likelihood with respect to αᵢ under the Laplace approximation gives the elegant re-estimation rule:

equation

So columns with small norm get a huge precision, which makes them shrink further on the next M step, which pushes the precision higher still. Surplus columns spiral to zero; columns that explain real variance escape this trap. The M step for W picks up an extra term:

equation

where A = diag(α₁, …, α_M).

Here it is in code, building straight on the EM-PCA skeleton:

def bayesian_pca_ard(X, M, n_iter=200, seed=0, eps=1e-8):
    rng = np.random.default_rng(seed)
    N, D = X.shape
    mu = X.mean(axis=0); Xc = X - mu
    W = rng.standard_normal((D, M)) * 0.1
    sigma2, alpha = 1.0, np.ones(M)
    for _ in range(n_iter):
        M_mat = W.T @ W + sigma2 * np.eye(M)
        M_inv = np.linalg.inv(M_mat)
        Ez = Xc @ W @ M_inv
        Ezz_sum = N * sigma2 * M_inv + Ez.T @ Ez
        W = (Xc.T @ Ez) @ np.linalg.inv(Ezz_sum + sigma2 * np.diag(alpha))
        sigma2 = max((np.sum(Xc**2) - 2*np.sum((Ez @ W.T) * Xc)
                      + np.trace(Ezz_sum @ (W.T @ W))) / (N * D), 1e-10)
        alpha = D / (np.sum(W**2, axis=0) + eps)
    return mu, W, sigma2, alpha

To see ARD in action, generate N = 300 samples in D = 10 dimensions with three high-variance latent directions and seven low-variance noise directions, then rotate. Fit Bayesian PCA with M = 9 (deliberately over-specified). The Hinton diagrams of W tell the story:

Bayesian PCA prunes surplus columns to zero. ML-PPCA on the left uses all 9 columns; ARD on the right keeps only 3

The left panel is unconstrained ML-PPCA: every cell of the 10 × 9 matrix has some weight, even though we know only three latent directions are real. The right panel is Bayesian PCA: six of the nine columns are visibly empty, and three remain populated. Bayesian PCA has discovered the true rank from the data alone.

Column norms make the pruning explicit: 6 of 9 ARD columns are at zero

This is the answer to "how many components should I keep?" that PCA practitioners have been improvising forever. You don't need a scree plot, a parallel analysis, or a cross-validation sweep. You let the prior arbitrate.

Factor Analysis: when noise isn't isotropic

PPCA assumes the residual noise has the same variance in every direction: Cov(ε) = σ² I. That's a strong assumption. Real data often has features measured at wildly different scales, with very different noise floors. A temperature sensor and a pressure sensor on the same machine produce numbers with utterly different noise characteristics.

Factor Analysis (Rubin and Thayer, 1982) relaxes the isotropy assumption by allowing a diagonal noise covariance:

equation

where Ψ is D × D and diagonal. Each feature gets its own noise variance. The model marginal becomes p(x) = N(x | μ, WWᵀ + Ψ). Compare to PPCA's WWᵀ + σ²I: only the noise covariance changes.

In factor-analysis terminology the columns of W are called factor loadings (they capture cross-feature correlations), and the diagonal entries of Ψ are called uniquenesses (variance unique to each feature). The intuition is the same: split the data into shared structure and feature-specific noise. The shift to diagonal noise is principled when features are measured on different scales or have different signal-to-noise ratios, which is most of the time.

There's no closed-form maximum likelihood for FA. The EM equations look almost identical to PPCA's:

def factor_analysis_em(X, M, n_iter=200, seed=0):
    rng = np.random.default_rng(seed)
    N, D = X.shape
    mu = X.mean(axis=0); Xc = X - mu
    W = rng.standard_normal((D, M)) * 0.1
    Psi = np.var(Xc, axis=0) + 1e-3
    for _ in range(n_iter):
        Psi_inv_W = W / Psi[:, None]
        G = np.linalg.inv(np.eye(M) + W.T @ Psi_inv_W)
        Ez = Xc @ Psi_inv_W @ G
        Ezz_sum = N * G + Ez.T @ Ez
        W = (Xc.T @ Ez) @ np.linalg.inv(Ezz_sum)
        cross = np.sum(W * ((Xc.T @ Ez) / N), axis=1)
        Psi = np.maximum(np.mean(Xc**2, axis=0) - cross, 1e-6)
    return mu, W, Psi

To see why FA matters, generate data with two true latent factors and per-feature noise that's tiny on half the features and large on the other half. Fit PPCA and FA on a training set, then compare held-out log-likelihood on a test set:

Factor Analysis recovers per-feature noise variance; PPCA averages them. Held-out log-likelihood improves by 2.7 nats per sample

The left panel says the story plainly. The true noise variances on features 0-2 are near zero; on features 3-5 they're around 2.25. FA's diagonal Ψ recovers both groups almost perfectly. PPCA's isotropic σ² is stuck averaging them at σ² ≈ 1.26, simultaneously overstating the noise on the clean features and understating it on the noisy ones. The right panel shows the consequence: 2.7 extra nats per sample of held-out log-likelihood (roughly a factor of 15 in probability density).

That's the whole point of Factor Analysis: when your features don't all have the same noise floor, modelling that explicitly beats forcing one number. PPCA wins on the symmetric synthetic 2D blob from the quick-win. FA wins everywhere else.

The bigger picture: when to use which

Now you have four algorithms; here's how to choose:

You have... Reach for... Because...
A modest-D dataset, want a fast deterministic answer ML-PCA closed-form One eigendecomposition, done
Very high D, want only a few components EM-PCA O(NDM) per iteration vs O(D³) eigendecomp
Missing entries, can't afford to row-drop EM-PCA Treats missingness as extra latents, no preprocessing
Unknown latent dimensionality Bayesian PCA (ARD) Prior prunes surplus columns, no CV sweep
Features measured on very different scales Factor Analysis Diagonal Ψ models heteroscedastic noise
You want to generate samples or do model comparison Any of the above They're all proper likelihood models, unlike standard PCA

Two more things you get for free with any of these probabilistic flavours: classification under different class-conditional density models, and a generative procedure (sample z, project, add noise). Standard PCA gives you neither.

Foundations: Tipping & Bishop, Roweis, and the chain back to Factor Analysis

The probabilistic reformulation of PCA was put forward independently in two papers in 1998-1999. Tipping and Bishop (1999b), "Probabilistic Principal Component Analysis", Journal of the Royal Statistical Society B, derived the closed-form maximum likelihood solution and proved that the columns of W_ML span the principal subspace of the sample covariance (with a free rotation R). They wrote:

The maximum of the likelihood function is obtained when the M eigenvectors are chosen to be those whose eigenvalues are the M largest (all other solutions being saddle points).

That's the key technical result behind everything in this post: PPCA's maximum-likelihood solution and standard PCA agree on the subspace they recover, but PPCA also gives you σ², a likelihood, and a generative model.

Roweis (1998), "EM Algorithms for PCA and SPCA", NeurIPS 1997, derived the EM algorithm independently and noted that it's "computationally much more efficient than conventional PCA in spaces of high dimensionality" because the per-iteration cost grows as NDM rather than D³. Roweis also showed how to take the limit σ² → 0 to recover standard PCA exactly via an EM-like iteration, removing the iso-noise assumption when you don't want it.

The link to Factor Analysis goes back much further. Spearman's 1904 paper on "general intelligence" is the seminal application of what we'd now call Factor Analysis. The modern EM treatment is Rubin and Thayer (1982). What's striking is how close FA and PPCA are: the only difference is σ² I versus diagonal Ψ. PPCA is rotationally invariant in data space (rotating the data rotates W accordingly). FA is not: re-scaling individual features re-scales the corresponding Ψⱼⱼ entries. That's a feature, not a bug, when features are measured on different scales.

These variants form a single derivation chain: standard PCA → PPCA closed form → EM-PCA → Bayesian PCA (ARD) → Factor Analysis. Working through that chain is the best way to internalise why each variant exists and when to deploy it.

Interactive Tools

  • PCA Visualizer: Drag a point cloud and watch the principal components, scree plot and explained variance follow, then project onto one component to see what the reduction discards.
  • Eigenvalue and SVD Visualizer: PPCA recovers the same principal axes that eigendecomposition finds. Enter a covariance matrix to see its principal components, explained variance and singular values directly, the geometry the maximum-likelihood W reconstructs up to a rotation.
  • Distribution Explorer: Visualise the multivariate Gaussian (and 15 other distributions) that sits at the heart of PPCA's generative story.
  • Regression Playground: Compare regularisation strategies for linear models. PPCA's projection (WᵀW + σ² I)⁻¹Wᵀ(x - overlinex) has exactly the form of ridge regression for a reason.
  • Convolution Visualiser: See how a linear operator (here W) acts on its input; useful intuition for the projection Wz + μ.

Frequently Asked Questions

What is probabilistic PCA and how does it differ from standard PCA?

Probabilistic PCA (PPCA) is a generative latent variable model x = Wz + μ + ε whose maximum-likelihood solution recovers the same principal subspace as standard PCA. The two algorithms produce the same components, but PPCA additionally gives you a noise variance σ², a likelihood, a generative procedure for sampling new data points, and a clean way to extend the model with priors or missing data.

When should I use EM-PCA instead of the closed-form solution?

Use EM-PCA when D is very large and you only need a handful of components (its per-iteration cost is O(NDM) rather than O(D³)), or when you have missing entries that you don't want to drop or impute beforehand. The closed form is faster for modest D and is exact, so stick with it when your covariance matrix fits comfortably in memory.

How does Bayesian PCA choose the number of latent dimensions automatically?

Bayesian PCA places an Automatic Relevance Determination (ARD) prior on the columns of W, with a separate precision hyperparameter αᵢ per column. The re-estimation rule αᵢ^(new) = D / ‖wᵢ‖² drives the precision of columns with small norm to infinity, which in turn shrinks those columns to zero on the next M step. Surplus dimensions get switched off; useful ones survive. You over-specify M and let the data decide.

What is the difference between Factor Analysis and PPCA?

The two models are identical except for the noise covariance. PPCA assumes isotropic noise σ² I (one number for all features); Factor Analysis allows diagonal noise Ψ (one number per feature). FA is the right choice when your features have different noise floors or are measured on different scales, which is most real-world datasets. PPCA is rotationally invariant in data space; FA is invariant under per-feature re-scaling instead.

Can probabilistic PCA handle missing data without pre-imputation?

Yes. Treat the missing entries of xₙ as additional latent variables alongside zₙ. In the E step, infer both the latent code and the missing entries from the observed ones using the current model. In the M step, update W and σ² as if you had the full data. No pre-imputation, no row dropping, no separate imputer.

Does PPCA recover standard PCA exactly in some limit?

Yes. As σ² → 0, the posterior p(z | x) collapses onto the orthogonal projection of x - μ onto the principal subspace, which is exactly standard PCA. Roweis (1998) used this limit to derive an EM-like algorithm that produces standard PCA components iteratively, which is useful in very high dimensions where eigendecomposition is impractical.

Want more #probabilistic & #probabilistic deep dives?

Join 6,133+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

More Posts

Truth Is Dead. Long Live Probabilistic Fact-Checking.

PrabashanaDev - Jun 27

Verse as a program code: contemporary experience and analysis methods

nevmenandr - Nov 30

Separating Kernel Commits From Single-Source Model Leaks: Lessons From Qwen4-27B and Gemini 4 Tritiu

Mara Hollis - Nov 28

Thomas Bayes: The Reverend Who Taught Us to Update Our Beliefs with Data

Datalaria - Jul 18

Minha Experiência com o uso do SpecKit no desenvolvimento em Infra/Cloud

Marcos Vilela - Jul 2
chevron_left
1.9k Points • 29 Badges
London • sesen.ai
48Posts
0Comments
42Connections
AI Researcher, Consultant, Entrepreneur.

Related Jobs

View all jobs →

Commenters (This Week)

4 comments
2 comments
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!