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

Probabilistic PCA as a latent variable model. EM-PCA, Bayesian PCA with ARD that picks dimensionality automatically, and Factor Analysis. From scratch in NumPy.

Cover Image for Probabilistic PCA, EM-PCA, Bayesian PCA, Factor Analysis

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 σ2≈0.125\sigma^2 \approx 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 MM 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:

z∼N(0,IM),x∣z∼N(Wz+μ,σ2ID)\mathbf{z} \sim \mathcal{N}(\mathbf{0}, \mathbf{I}_M), \qquad \mathbf{x} \mid \mathbf{z} \sim \mathcal{N}(\mathbf{W}\mathbf{z} + \boldsymbol{\mu}, \sigma^2 \mathbf{I}_D)

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

Marginalising out z\mathbf{z} gives a Gaussian in the data space:

p(x)=N(x∣μ, WW⊤+σ2I)p(\mathbf{x}) = \mathcal{N}(\mathbf{x} \mid \boldsymbol{\mu},\, \mathbf{W}\mathbf{W}^{\top} + \sigma^2 \mathbf{I})

The covariance has a special structure: a low-rank piece WW⊤\mathbf{W}\mathbf{W}^{\top} (the signal) plus an isotropic noise floor σ2I\sigma^2 \mathbf{I}. That low-rank-plus-isotropic shape is the entire content of PPCA. A standard D×DD \times D covariance matrix needs D(D+1)/2D(D+1)/2 parameters, which gets unwieldy fast. PPCA needs just DM+1−M(M−1)/2DM + 1 - M(M-1)/2, growing linearly with DD. 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:

WML=UM(ΛM−σ2I)1/2R,σML2=1D−M∑i=M+1Dλi\mathbf{W}_{\text{ML}} = \mathbf{U}_M (\boldsymbol{\Lambda}_M - \sigma^2 \mathbf{I})^{1/2} \mathbf{R}, \qquad \sigma^2_{\text{ML}} = \frac{1}{D - M} \sum_{i=M+1}^{D} \lambda_i

The columns of UM\mathbf{U}_M are the top-MM eigenvectors of the data covariance, ΛM\boldsymbol{\Lambda}_M holds the corresponding eigenvalues on the diagonal, R\mathbf{R} is an arbitrary M×MM \times M rotation that the model can't pin down (rotations in latent space leave WW⊤\mathbf{W}\mathbf{W}^{\top} unchanged), and σML2\sigma^2_{\text{ML}} is the average variance in the discarded directions, the noise floor. Read that last bit carefully. Standard PCA throws away D−MD - 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×DD \times D data covariance, which is O(D3)O(D^3). For modest DD that's fine, but in high dimensions it becomes expensive. EM-PCA gives you an iterative algorithm whose per-iteration cost is O(NDM)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(zn∣xn)p(\mathbf{z}_n \mid \mathbf{x}_n):

M=W⊤W+σ2I,E[zn]=M−1W⊤(xn−x‾)\mathbf{M} = \mathbf{W}^{\top}\mathbf{W} + \sigma^2 \mathbf{I}, \qquad \mathbb{E}[\mathbf{z}_n] = \mathbf{M}^{-1}\mathbf{W}^{\top}(\mathbf{x}_n - \overline{\mathbf{x}})

M step: re-estimate W\mathbf{W} and σ2\sigma^2 using those statistics:

Wnew=[∑n(xn−x‾)E[zn]⊤][∑nE[znzn⊤]]−1\mathbf{W}_{\text{new}} = \left[\sum_n (\mathbf{x}_n - \overline{\mathbf{x}})\mathbb{E}[\mathbf{z}_n]^{\top}\right] \left[\sum_n \mathbb{E}[\mathbf{z}_n \mathbf{z}_n^{\top}]\right]^{-1}

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\mathbf{W} vectors is 1.0 to six decimal places, and the two σ2\sigma^2 estimates differ by less than 2×10−62 \times 10^{-6}. That's not a coincidence. The likelihood has a unique maximum (up to the rotation R\mathbf{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\mathbf{W} and σ2\sigma^2 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 x1x_1 and x2x_2 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 MM. 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\mathbf{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 wi\mathbf{w}_i of W\mathbf{W} with its own precision αi\alpha_i:

p(W∣α)=∏i=1M(αi2π)D/2exp⁡ ⁣(−12αiwi⊤wi)p(\mathbf{W} \mid \boldsymbol{\alpha}) = \prod_{i=1}^{M} \left(\frac{\alpha_i}{2\pi}\right)^{D/2} \exp\!\left(-\tfrac{1}{2}\alpha_i \mathbf{w}_i^{\top} \mathbf{w}_i\right)

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

αinew=Dwi⊤wi\alpha_i^{\text{new}} = \frac{D}{\mathbf{w}_i^{\top} \mathbf{w}_i}

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\mathbf{W} picks up an extra term:

Wnew=[∑n(xn−x‾)E[zn]⊤][∑nE[znzn⊤]+σ2A]−1\mathbf{W}_{\text{new}} = \left[\sum_n (\mathbf{x}_n - \overline{\mathbf{x}})\mathbb{E}[\mathbf{z}_n]^{\top}\right] \left[\sum_n \mathbb{E}[\mathbf{z}_n \mathbf{z}_n^{\top}] + \sigma^2 \mathbf{A}\right]^{-1}

where A=diag(α1,…,αM)\mathbf{A} = \text{diag}(\alpha_1, \ldots, \alpha_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=300N = 300 samples in D=10D = 10 dimensions with three high-variance latent directions and seven low-variance noise directions, then rotate. Fit Bayesian PCA with M=9M = 9 (deliberately over-specified). The Hinton diagrams of W\mathbf{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×910 \times 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(ϵ)=σ2I\text{Cov}(\boldsymbol{\epsilon}) = \sigma^2 \mathbf{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:

x∣z∼N(Wz+μ, Ψ)\mathbf{x} \mid \mathbf{z} \sim \mathcal{N}(\mathbf{W}\mathbf{z} + \boldsymbol{\mu},\, \boldsymbol{\Psi})

where Ψ\boldsymbol{\Psi} is D×DD \times D and diagonal. Each feature gets its own noise variance. The model marginal becomes p(x)=N(x∣μ,WW⊤+Ψ)p(\mathbf{x}) = \mathcal{N}(\mathbf{x} \mid \boldsymbol{\mu}, \mathbf{W}\mathbf{W}^{\top} + \boldsymbol{\Psi}). Compare to PPCA's WW⊤+σ2I\mathbf{W}\mathbf{W}^{\top} + \sigma^2\mathbf{I}: only the noise covariance changes.

In factor-analysis terminology the columns of W\mathbf{W} are called factor loadings (they capture cross-feature correlations), and the diagonal entries of Ψ\boldsymbol{\Psi} 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 Ψ\boldsymbol{\Psi} recovers both groups almost perfectly. PPCA's isotropic σ2\sigma^2 is stuck averaging them at σ2≈1.26\sigma^2 \approx 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-DD dataset, want a fast deterministic answerML-PCA closed-formOne eigendecomposition, done
Very high DD, want only a few componentsEM-PCAO(NDM)O(NDM) per iteration vs O(D3)O(D^3) eigendecomp
Missing entries, can't afford to row-dropEM-PCATreats missingness as extra latents, no preprocessing
Unknown latent dimensionalityBayesian PCA (ARD)Prior prunes surplus columns, no CV sweep
Features measured on very different scalesFactor AnalysisDiagonal Ψ\boldsymbol{\Psi} models heteroscedastic noise
You want to generate samples or do model comparisonAny of the aboveThey'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\mathbf{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 WML\mathbf{W}_{\text{ML}} span the principal subspace of the sample covariance (with a free rotation R\mathbf{R}). They wrote:

The maximum of the likelihood function is obtained when the MM eigenvectors are chosen to be those whose eigenvalues are the MM 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 σ2\sigma^2, 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 NDMNDM rather than D3D^3. Roweis also showed how to take the limit σ2→0\sigma^2 \to 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 σ2I\sigma^2 \mathbf{I} versus diagonal Ψ\boldsymbol{\Psi}. PPCA is rotationally invariant in data space (rotating the data rotates W\mathbf{W} accordingly). FA is not: re-scaling individual features re-scales the corresponding Ψjj\Psi_{jj} 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\mathbf{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+σ2I)−1W⊤(x−x‾)(\mathbf{W}^{\top}\mathbf{W} + \sigma^2 \mathbf{I})^{-1}\mathbf{W}^{\top}(\mathbf{x} - \overline{\mathbf{x}}) has exactly the form of ridge regression for a reason.
  • Convolution Visualiser: See how a linear operator (here W\mathbf{W}) acts on its input; useful intuition for the projection Wz+μ\mathbf{W}\mathbf{z} + \boldsymbol{\mu}.

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions