Probabilistic inference, Monte Carlo, and posterior computation · Probabilistic computation and inference foundations · INF001 · Algorithm
Expectation–maximization (EM)
Fits maximum-likelihood or MAP parameters when introducing latent or missing variables makes complete-data optimization simpler. EM is the fitting engine behind many mixtures, factor models, and hidden-state models;
In CodeSplash
A CodeSplash method runs this entry in Python and R. Set it up from the method's page.
- Gaussian mixture model Verified in Python and R
- Synthetic data — Gaussian mixture Verified in Python and R
Do it in CodeSplash Run it on your own data, in Python or R.
- Availability
- Runs in CodeSplash
- Code example
- Complete calculation
- Who ran it
- CodeSplash's run and the reference's record
- CodeSplash's run
- Verified in Python and R through discover.gmm, synth.mixture. The reference's example ran in Python and R here, and they agree.
- The reference's record
- Python: Ran in the reference's review. The report doesn't record which version of the code ran. R: Reviewed but not run: R wasn't available to the reference's authors.
Purpose
Fits maximum-likelihood or MAP parameters when introducing latent or missing variables makes complete-data optimization simpler. EM is the fitting engine behind many mixtures, factor models, and hidden-state models; it is not another mixture architecture.
Question / hypotheses
Which parameter value maximizes the observed-data likelihood after marginalizing the unobserved variables? The E-step averages latent uncertainty; it does not permanently replace each latent variable by one hard label.
Architecture / computational structure
Alternate posterior expectation and surrogate optimization while retaining sufficient statistics. In a finite mixture, normalize component likelihoods to responsibilities, then update weighted parameters. The supplied component performs one complete EM iteration for a two-component Gaussian mixture whose variances remain fixed at one.
Assumptions
The conditional expectation must be computable, and each M-step must maximize or at least improve its prescribed surrogate. Likelihood monotonicity assumes compatible exact steps and does not imply a global optimum, identifiability, or a finite optimum for an unconstrained Gaussian mixture.
Formula / computational definition
Parameters and notation
Estimated parameters theta are model-specific: mixture weights, component means/covariances, transition probabilities, or loadings. Latent responsibilities are intermediate posterior quantities. For MAP fitting, add the log parameter prior to the displayed M-step objective. Hyperparameters include component count, priors, covariance constraints, initialization, iteration limit, and convergence tolerance. Select structural complexity using independent predictive evidence or an explicitly justified criterion.
Fitting, fine-tuning, and adaptation
Neural fine-tuning is inapplicable to ordinary EM. Warm-start parameters when refitting related data, but rerun both steps and inspect the new objective. A neural decoder may require a generalized M-step with gradient optimization; its incomplete improvement and approximate E-step change the guarantees.
How to use and calibrate
Check likelihood progression, multiple initializations, component occupancy, and held-out log score. Plot responsibilities and fitted density, not only hard labels. Compare results after rescaling or regularization when small components collapse; a covariance floor changes the fitted model.
Example application
Fit overlapping sensor-state populations with uncertain membership, then inspect which observations retain appreciable probability under both states rather than reporting an unjustified certain classification.
Interpretation / pitfalls
Watch out
EM can converge slowly near overlapping components or saddle regions. Monotone likelihood is an optimization property, not a significance test or evidence of good uncertainty calibration. Label switching leaves the likelihood unchanged. The example deliberately fixes variance and component count.
Python and R code examples
Scope: One exact E/M iteration for a specified fixed-variance Gaussian mixture; not a general-purpose EM library.
Implementation route: Python uses NumPy and SciPy; R uses base R. General Gaussian-mixture fitting is available through sklearn.mixture.GaussianMixture and mclust, while other latent-variable models need their own conditional expectations and updates.
Dependencies and validation: Python — executed successfully on the supplied synthetic inputs; imports identify NumPy/SciPy dependencies. R — base R, reviewed but not executed because Rscript is unavailable. Random-number streams differ between languages; matching seed integers do not imply matching draws.
Python and R
The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.
Complete calculation — One exact E/M iteration for a specified fixed-variance Gaussian mixture; not a general-purpose EM library. · needs numpy, scipy
import numpy as np
from scipy.special import logsumexp
x=np.array([-2.,-1.4,-.7,.8,1.4,2.]); mu=np.array([-1.,1.]); w=np.array([.5,.5])
def logjoint(mu,w): return -.5*(x[:,None]-mu[None,:])**2+np.log(w)-.5*np.log(2*np.pi)
J=logjoint(mu,w); before=logsumexp(J,axis=1).sum()
r=np.exp(J-logsumexp(J,axis=1,keepdims=True)); nk=r.sum(0)
mu=(r*x[:,None]).sum(0)/nk; w=nk/len(x)
after=logsumexp(logjoint(mu,w),axis=1).sum()
assert after>=before-1e-10
print('means',mu,'weights',w,'loglik',before,after)
Complete calculation — One exact E/M iteration for a specified fixed-variance Gaussian mixture; not a general-purpose EM library.
x <- c(-2,-1.4,-.7,.8,1.4,2); mu <- c(-1,1); w <- c(.5,.5)
joint <- function(mu,w) sweep(sapply(mu,function(m) dnorm(x,m,1)),2,w,"*")
J <- joint(mu,w); before <- sum(log(rowSums(J)))
r <- sweep(J,1,rowSums(J),"/"); nk <- colSums(r)
mu <- colSums(sweep(r,1,x,"*"))/nk; w <- nk/length(x)
after <- sum(log(rowSums(joint(mu,w)))); stopifnot(after>=before-1e-10)
print(list(means=mu,weights=w,loglik=c(before,after)))
Sources
- Primary/official source 1doi.org
- Primary/official source 2scikit-learn.org
- Primary/official source 3mclust-org.github.io
From the CodeSplash reference, entry INF001.