Search

Search papers and lessons

Latent Variable Model

Level 3 · 15 min read

A latent variable model explains visible data through hidden variables that are never observed, describing each data point as the result of a hidden cause plus noise.

On this page

  • Colour = topic mix
  • Probability
  • Inference
  • Sign in to see your progress

TL;DR

A latent variable model says that the data we see were produced by something we do not see. Each observation xx comes from a hidden variable zz, the latent variable, plus some randomness. We cannot read zz off the data, so the model has to describe how zz and xx relate and then work backwards to guess zz from xx.

Where you'll see it: in the hidden code of a variational autoencoder, in the hidden states of a hidden Markov model, and in the unknown cluster label behind each point in a mixture of Gaussians.

Intuition

Suppose you record the height of every person in a room. You see a single list of numbers, and it looks messy: some heights are near 160 cm, others near 180 cm. Often the mess has a simple cause you did not record, such as the sex of each person. Sex is hidden. Heights are visible. Each height is produced by picking a hidden group, then drawing a height from that group's distribution.

That is a latent variable model. The hidden thing is a label or a small set of numbers that summarise the cause. The visible thing is the data. The model says how the hidden cause shapes the data, and it lets you ask two useful questions: what the hidden cause probably was for a given observation, and what the data look like overall.

Why bother with the hidden layer at all? Because it can make a complicated distribution simple. The overall shape of the heights, with two bumps, is hard to describe directly. Given the hidden group, each bump is just a plain bell curve. The hidden variable turns one hard problem into several easy ones.

flowchart LR
  Z[hidden cause z] -->|generates| X[visible data x]
  X -->|inference: what was z?| Z

The arrow from zz to xx is the generative story. The arrow back is inference, and it is the hard part.

The math

Let xx be the observed data and zz the latent variable, both random variables. A latent variable model specifies a joint distribution over both, usually as a prior over the hidden variable times a likelihood for the data given it:

p(x,z)=p(x∣z) p(z).p(x, z) = p(x \mid z)\, p(z).

Here p(z)p(z) is the prior, how likely each hidden value is before seeing data. The term p(x∣z)p(x \mid z) is the likelihood, how likely the data are if the hidden value is zz. The symbol ∣\mid reads "given".

We never observe zz, so to get the distribution of the data alone we sum or integrate it out. This is the Law of Total Probability applied to the joint distribution. For a continuous hidden variable:

p(x)=∫p(x∣z) p(z) dz.p(x) = \int p(x \mid z)\, p(z)\, dz.

Each zz contributes a weighted share of the density of xx, weighted by how likely zz was. For a discrete zz the integral becomes a sum.

The reverse question, what the hidden cause probably was, is answered by Bayes' Rule:

p(z∣x)=p(x∣z) p(z)p(x).p(z \mid x) = \frac{p(x \mid z)\, p(z)}{p(x)}.

This posterior is the central object of the whole subject. Its numerator is the joint distribution, and its denominator is the marginal p(x)p(x) from the previous equation, which is often the hard part to compute. When zz can take only a few values, the integral is a short sum. When it cannot, the denominator is intractable, and most of the modern methods (variational inference, sampling) exist to approximate it.

Mixture of Gaussians

The simplest useful example has a discrete latent variable z∈{1,…,K}z \in \{1, \dots, K\} and Gaussian likelihoods. With weights πk=p(z=k)\pi_k = p(z = k), means μk\mu_k and standard deviation σ\sigma,

p(x)=∑k=1Kπk N(x∣μk,σ2).p(x) = \sum_{k=1}^{K} \pi_k \, \mathcal{N}(x \mid \mu_k, \sigma^2).

Here N(x∣μ,σ2)\mathcal{N}(x \mid \mu, \sigma^2) is the Gaussian density with mean μ\mu and variance σ2\sigma^2. Each component is one hidden group, and zz says which group a point came from. The plot shows a two-component mixture: the sum has two bumps, while each piece is a plain bell.

−6−4−2024600.10.20.30.4xdensity
  • mixture p(x)
  • z = 1 part
  • z = 2 part
Weight 0.3 on a Gaussian centred at −2 and weight 0.7 on one centred at 3, both with σ = 1. The solid curve is the sum; the dashed curves are the two weighted parts.

Two things to check

The latent variable does not have to be unique or meaningful. Two different hidden structures can give the same p(x)p(x), so the model's hidden variables may be labelled differently from the real causes. This is called identifiability, and it is a real limit on interpreting zz.

Also, the hidden variable is a modelling choice. Pick it too small and the model cannot fit the data. Pick it too large and it fits noise. Training likelihood alone always rewards more components, so use held-out likelihood or a penalised criterion such as BIC to choose the size.

Worked examples

Example
Two coins, one hidden

You have two coins. Coin A lands heads with probability 0.90.9 and coin B with probability 0.20.2. You pick one at random (each with probability 0.50.5), flip it, and see heads. The hidden variable is z∈{A,B}z \in \{A, B\}, the coin you picked. The observation is x=x = heads.

  1. Prior: p(A)=p(B)=0.5p(A) = p(B) = 0.5.
  2. Likelihood: p(H∣A)=0.9p(H \mid A) = 0.9 and p(H∣B)=0.2p(H \mid B) = 0.2.
  3. Marginal, by the law of total probability: p(H)=0.5⋅0.9+0.5⋅0.2=0.55p(H) = 0.5 \cdot 0.9 + 0.5 \cdot 0.2 = 0.55.
  4. Posterior, by Bayes' rule: p(A∣H)=0.5⋅0.90.55=0.450.55≈0.818p(A \mid H) = \dfrac{0.5 \cdot 0.9}{0.55} = \dfrac{0.45}{0.55} \approx 0.818.

Interpretation: before the flip, you were 50% sure of each coin. After seeing heads, you are about 82% sure it was coin A. The observation moved your belief about the hidden variable, and the posterior is exactly that update.

Example
A Gaussian mixture with a single observation

Use the mixture above: weights π1=0.3\pi_1 = 0.3 and π2=0.7\pi_2 = 0.7, means μ1=−2\mu_1 = -2 and μ2=3\mu_2 = 3, and σ=1\sigma = 1. Observe x=0x = 0.

Useful values: φ(u)=e−u2/2/2π\varphi(u) = e^{-u^2/2}/\sqrt{2\pi} is the standard normal density, so φ(2)≈0.05399\varphi(2) \approx 0.05399 and φ(3)≈0.00443\varphi(3) \approx 0.00443.

  1. Likelihood under component 1: φ(0−(−2))=φ(2)≈0.05399\varphi(0 - (-2)) = \varphi(2) \approx 0.05399.
  2. Likelihood under component 2: φ(0−3)=φ(3)≈0.00443\varphi(0 - 3) = \varphi(3) \approx 0.00443.
  3. Marginal: p(0)=0.3⋅0.05399+0.7⋅0.00443≈0.01620+0.00310=0.01930p(0) = 0.3 \cdot 0.05399 + 0.7 \cdot 0.00443 \approx 0.01620 + 0.00310 = 0.01930.
  4. Posterior for component 1: p(z=1∣0)=0.01620/0.01930≈0.839p(z = 1 \mid 0) = 0.01620 / 0.01930 \approx 0.839.

Interpretation: the point x=0x = 0 lies closer to the first component's centre at −2-2 than to the second at 33. Component 1 has the smaller prior weight (0.3 against 0.7), but its likelihood at x=0x = 0 is about 12 times larger, which more than makes up for it. The posterior is about 84% to 16% in favour of component 1. Repeat the calculation at x=1x = 1 and it drops to about 3% for component 1, since 11 is now much nearer the second centre. The prior shifts the balance, but where the observation sits matters more.

Tradeoffs and failure modes

Latent variable models are flexible, but the flexibility has costs. The main ones come from the posterior: once it is hard to compute, everything else gets harder.

SituationWhat goes wrongBetter choice
Few discrete hidden states, such as a small mixtureExact posterior is cheap, so there is little to worry aboutUse exact inference and [[maximum-likelihood-estimation
Continuous hidden variable with a nonlinear link to the dataThe integral for p(x)p(x) has no closed form, so the posterior is intractableVariational inference, see Variational Lower Bound (ELBO), or sampling methods such as Monte Carlo Method
Too many hidden componentsThe model fits noise and generalises badlyHeld-out likelihood, or a prior that switches off unused components
Hidden states are only identified up to relabellingInterpreting a single zz as a real cause can misleadReport results that do not depend on the labels, such as predicted densities
Gradient-based training through sampled zzSampling blocks gradients from reaching the encoderReparameterization Trick, which moves the randomness out of the sample
Likelihood is multimodalThe optimiser can converge to a poor local solutionSeveral random starts, or better initialisation such as k-means

The core rule is simple. Adding a hidden variable buys you a simpler conditional model, and the price is that you must infer the hidden variable and marginalise it, and both steps can be expensive.

History

The idea of explaining observed variety through hidden structure is old. In 1894 Karl Pearson fitted a mixture of two normal distributions to a set of crab measurements, using the method of moments. It was one of the first mixture models ever fitted. Charles Spearman's factor analysis in the early 1900s, where many test scores are explained by a few hidden factors, is another early latent variable model.

Mixtures were hard to fit by hand until the expectation-maximisation algorithm, described by Arthur Dempster, Nan Laird and Donald Rubin in 1977. EM alternates between computing the posterior over the hidden variables and updating the parameters, and it gave the field a general method. Hidden Markov models, which use a hidden chain of states, were developed in the late 1960s and 1970s and became standard in speech recognition.

Latent variable models came back into the spotlight in machine learning with the variational autoencoder, proposed by Diederik Kingma and Max Welling in 2013. They used a neural network to approximate the posterior, which made latent variable models practical for high-dimensional data such as images. Much of modern generative modelling is built on this idea.

Check yourself

QuestionRecall: in the notation p(x,z)=p(x∣z) p(z)p(x, z) = p(x \mid z)\, p(z), which factor is the prior and which is the likelihood?Show answer

p(z)p(z) is the prior, how likely each hidden value is before the data arrive. p(x∣z)p(x \mid z) is the likelihood, how probable the observed data are for a given hidden value.

QuestionComputation: a latent variable zz takes values 1 and 2 with probabilities 0.40.4 and 0.60.6. Given z=1z = 1, xx has likelihood 0.50.5. Given z=2z = 2, it has likelihood 0.10.1. Compute p(x)p(x) for the observed xx.Show answer

By the law of total probability, p(x)=0.4⋅0.5+0.6⋅0.1=0.20+0.06=0.26p(x) = 0.4 \cdot 0.5 + 0.6 \cdot 0.1 = 0.20 + 0.06 = 0.26.

QuestionWhy: why is the posterior p(z∣x)p(z \mid x) harder to compute than the joint p(x,z)p(x, z)?Show answer

The joint is just a product of two terms you specified. The posterior divides by p(x)p(x), which requires summing or integrating the joint over every possible value of zz. For a continuous or high-dimensional zz that sum has no closed form and must be approximated.

QuestionApplied: you fit a mixture of three Gaussians to data that look like two clusters. The model fits well on training data but gives poor predictions on new points. What is a likely cause, and what would you check?Show answer

The model has more hidden components than the data support, so it is modelling noise in the training set. Check held-out likelihood as you vary the number of components, and prefer the smallest number that predicts new data well. A prior that shrinks unused component weights toward zero is another option.

QuestionApplied: in a variational autoencoder, the encoder outputs a mean and variance and you sample zz from that Gaussian. Why can't gradients flow through the sample directly, and what fix is used?Show answer

Sampling is a random operation, so the output zz is not a smooth function of the encoder's parameters, and the gradient cannot be propagated through the draw. The reparameterization trick writes z=μ+σ⋅εz = \mu + \sigma \cdot \varepsilon with ε\varepsilon drawn from a fixed standard normal. The randomness now sits in ε\varepsilon, which does not depend on the parameters, so the path from μ\mu and σ\sigma to the loss is differentiable.

Sources