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}")
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 .

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 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:
Each data point starts life as an -dimensional latent code drawn from a standard Gaussian. The matrix 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 gives a Gaussian in the data space:
The covariance has a special structure: a low-rank piece (the signal) plus an isotropic noise floor . That low-rank-plus-isotropic shape is the entire content of PPCA. A standard covariance matrix needs parameters, which gets unwieldy fast. PPCA needs just , growing linearly with . 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:
The columns of are the top- eigenvectors of the data covariance, holds the corresponding eigenvalues on the diagonal, is an arbitrary rotation that the model can't pin down (rotations in latent space leave unchanged), and is the average variance in the discarded directions, the noise floor. Read that last bit carefully. Standard PCA throws away 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 data covariance, which is . For modest that's fine, but in high dimensions it becomes expensive. EM-PCA gives you an iterative algorithm whose per-iteration cost is , 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 :
M step: re-estimate and using those statistics:
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.

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 vectors is 1.0 to six decimal places, and the two estimates differ by less than . That's not a coincidence. The likelihood has a unique maximum (up to the rotation 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 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:

The middle panel shows only the points whose and 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 . 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 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 of with its own precision :
If a particular grows large during fitting, the corresponding column is squeezed to zero, effectively switching off latent dimension . Maximising the marginal likelihood with respect to under the Laplace approximation gives the elegant re-estimation rule:
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 picks up an extra term:
where .
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 samples in dimensions with three high-variance latent directions and seven low-variance noise directions, then rotate. Fit Bayesian PCA with (deliberately over-specified). The Hinton diagrams of tell the story:

The left panel is unconstrained ML-PPCA: every cell of the 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.

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: . 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:
where is and diagonal. Each feature gets its own noise variance. The model marginal becomes . Compare to PPCA's : only the noise covariance changes.
In factor-analysis terminology the columns of 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:

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 , 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- dataset, want a fast deterministic answer | ML-PCA closed-form | One eigendecomposition, done |
| Very high , want only a few components | EM-PCA | per iteration vs 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 , 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 span the principal subspace of the sample covariance (with a free rotation ). They wrote:
The maximum of the likelihood function is obtained when the eigenvectors are chosen to be those whose eigenvalues are the 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 rather than . Roweis also showed how to take the limit 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 versus diagonal . PPCA is rotationally invariant in data space (rotating the data rotates 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 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 has exactly the form of ridge regression for a reason.
- Convolution Visualiser: See how a linear operator (here ) acts on its input; useful intuition for the projection .
Related Posts
- PCA and SVD: The Linear Algebra You Actually Need: The standard PCA primer this post builds on, including the SVD relationship.
- LDA vs PCA: Supervised Meets Unsupervised Dimensionality Reduction: When PCA's variance objective is the wrong target for classification.
- EM Algorithm: Inferring Hidden Coin Bias: The intuition for EM that underpins EM-PCA, Bayesian PCA, and FA in this post.
- Approximate Inference: From MCMC to Variational Bayes: How variational PCA fits into the wider approximate-inference picture sketched in this post.
- Relevance Vector Machine vs SVM in Python: Same ARD mechanism, applied to kernel basis functions instead of latent columns.
- Bayesian Model Comparison: The Evidence Framework: The marginal-likelihood machinery behind Bayesian PCA's automatic dimensionality selection.
- SVD for Recommender Systems: Matrix Factorisation in NumPy: The probabilistic cousin: recast the same low-rank factorisation as a latent-variable model with missing data.
- Variational Autoencoders in NumPy: Three Digits, No KL Term: PPCA with a neural-network decoder and an amortised encoder, and what the KL term buys in generated digits.








