Probabilistic graphical models¶
A graphical model writes a joint distribution over many variables as a product of small local pieces, and draws which variables directly influence which as a graph. The graph makes the distribution compact, makes independence visible, and tells inference what it can skip. Every modern generative model, from GPT to diffusion, is a graphical model whose local pieces are neural networks.
10,000 ft
Before deep learning, graphical models were how AI handled uncertainty: hidden Markov models in speech recognition, Kalman filters in tracking and navigation, Bayesian networks in medical diagnosis, conditional random fields in named-entity recognition, topic models over document collections, error-correcting codes decoded by belief propagation. Judea Pearl's ACM Turing Award (2011) was for "a calculus for probabilistic and causal reasoning" built on them. The vocabulary has outlived the pre-2012 models: an autoregressive language model is the chain rule of probability drawn as a fully connected DAG with neural conditionals; a VAE is a two-node latent-variable model trained by variational inference; a diffusion model is a long Markov chain of latent variables. EM, Bayesian estimation, MCMC, variational inference and causal graphs all live here.
2,000 ft
Three questions organise the whole field:
- Representation. Factorise \(p(x_1,\dots,x_n)\) into local terms along a graph. A directed graph (Bayesian network) uses conditionals \(p(x_i \mid \text{parents})\) and reads as a generative story; an undirected graph (Markov random field) uses non-negative potentials on cliques and a normaliser \(Z\), and reads as soft constraints. Missing edges are independence assumptions.
- Inference. Compute posteriors and marginals such as \(p(\text{query} \mid \text{evidence})\). Naively an exponential sum; on trees and chains, message passing (variable elimination, belief propagation, the forward algorithm of HMMs) makes it linear. On hard graphs, approximate by sampling (MCMC) or by optimisation (variational inference).
- Learning. Fit parameters (by counting when everything is observed, by EM or gradient methods when some variables are hidden) and, sometimes, the graph itself.
Ground level¶
Why factorise¶
A joint distribution over \(n\) binary variables is a table of \(2^n - 1\) free numbers. For \(n = 30\) that is 1,073,741,823 numbers: impossible to store, to estimate from data, or to sum over. But real variables do not all interact directly. If each variable depends directly on at most \(k\) others, a directed model needs at most \(n\cdot 2^k\) numbers; a chain of 30 binary variables needs \(1 + 29 \times 2 = 59\). The graph turns an exponential object into a sum of small ones. Every gain in the rest of this page (compact storage, data-efficient learning, fast inference) comes from that one move.
Bayesian networks¶
A Bayesian network is a directed acyclic graph (DAG) with one node per variable and a conditional distribution for each node given its parents:
By the chain rule of probability, any joint can be written as \(\prod_i p(x_i \mid x_1,\dots,x_{i-1})\), a DAG in which every earlier variable is a parent of every later one. A Bayesian network is that factorisation with some parents deleted, and each deleted edge is an assumption: \(x_i\) is independent of its other predecessors given its parents.
The running example¶
With \(P(W{=}1\mid R,S) = 0.99, 0.90, 0.80, 0.01\) for \((R,S) = (1,1), (1,0), (0,1), (0,0)\), and \(P(T{=}1 \mid R) = 0.7\) or \(0.2\). The joint has 15 free numbers but the network uses 8. You see wet grass. How likely is rain?
so \(P(R{=}1\mid W{=}1) = 0.1818/0.2530 = 0.719\), up from the prior 0.2. Now you also learn the sprinkler was on. \(P(R{=}1, S{=}1, W{=}1) = 0.2 \cdot 0.1 \cdot 0.99 = 0.0198\) and \(P(R{=}0, S{=}1, W{=}1) = 0.8 \cdot 0.1 \cdot 0.80 = 0.064\), so \(P(R{=}1 \mid W{=}1, S{=}1) = 0.0198/0.0838 = 0.236\). The sprinkler explains away the wet grass: belief in rain falls back almost to its prior, although rain and the sprinkler are independent causes. Add the evidence that traffic is heavy and \(P(R{=}1 \mid W{=}1, T{=}1) = 0.899\): independent effects of the same cause reinforce each other.
Reading independence off the graph¶
Every pattern of evidence flow reduces to three local structures:
- Chain \(A \to B \to C\) (rain → wet grass → slippery path): information flows through \(B\); observing \(B\) blocks it.
- Fork \(A \leftarrow B \to C\) (wet grass ← rain → traffic): a common cause makes \(A\) and \(C\) correlated; observing the cause blocks it.
- Collider \(A \to B \leftarrow C\) (rain → wet grass ← sprinkler): the opposite. \(A\) and \(C\) are independent until you observe \(B\) (or any descendant of \(B\)), which opens the path. That is explaining away, and also selection bias: condition on a common effect (only studying hospitalised patients, only funded start-ups) and you manufacture correlations between its causes.
d-separation generalises this: sets \(X\) and \(Y\) are conditionally independent given \(Z\) if every undirected path between them is blocked, where a path is blocked by a chain or fork node in \(Z\), or by a collider that is not in \(Z\) and has no descendant in \(Z\). It lets you read every conditional independence the graph implies without any arithmetic. A useful corollary: each node is independent of everything else given its Markov blanket (its parents, its children and its children's other parents), which is all a Gibbs sampler needs to look at.
Markov random fields and factor graphs¶
Some dependencies have no natural direction: neighbouring pixels in an image, adjacent spins in a magnet, words that co-occur. A Markov random field (MRF) uses an undirected graph and non-negative potentials \(\psi_C\) on its cliques:
Writing \(\psi_C = e^{-E_C}\) makes this an energy-based model, \(p(\mathbf{x}) \propto e^{-E(\mathbf{x})}\); the Ising model and Boltzmann machines are the classic cases. Independence in an MRF is plain graph separation: \(A \perp C \mid B\) if every path from \(A\) to \(C\) passes through \(B\). The Hammersley–Clifford theorem says that for strictly positive distributions, factorising over the cliques of a graph and satisfying that graph's separation independences are equivalent. The price is \(Z\): a sum over all configurations, needed for probabilities and for learning, and generally intractable. Factor graphs (bipartite graphs of variables and factors) represent both families uniformly and are the natural setting for message passing.
Directed and undirected graphs express different independences: no undirected graph captures a collider's "independent until observed", and no DAG captures a four-cycle of mutual influences. Conditional random fields (Lafferty, McCallum and Pereira, 2001) are MRFs over labels \(\mathbf{y}\) conditioned on inputs \(\mathbf{x}\), \(p(\mathbf{y}\mid\mathbf{x}) \propto \prod_C\psi_C(\mathbf{y}_C, \mathbf{x})\). A linear-chain CRF over a sentence's tags was the standard named-entity recogniser before pre-trained transformers, and a CRF layer on top of a neural encoder is still used when label consistency matters.
Exact inference: pushing sums inside products¶
To compute a marginal you must sum the joint over all other variables. For a chain \(x_1 - x_2 - \dots - x_n\) with \(K\) states each, the naive sum has \(K^n\) terms. But the distributive law lets you push each sum inward past the factors that do not mention its variable:
and the cost becomes \(O(nK^2)\). That is variable elimination: sum variables out one at a time, each time multiplying only the factors that mention the variable and producing a new, smaller factor. The order matters: its cost is exponential in the largest factor created, governed by the graph's treewidth. On trees, reorganising the same computation as messages sent along edges, \(m_{i\to j}(x_j) = \sum_{x_i}\psi(x_i,x_j)\prod_{k \ne j}m_{k\to i}(x_i)\), computes all marginals in two sweeps: belief propagation (Pearl, 1982–1988). Graphs with loops can be clustered into a tree of cliques and solved exactly by the junction tree algorithm (Lauritzen and Spiegelhalter, 1988), exponential in clique size. In general, exact inference in Bayesian networks is NP-hard (Cooper, 1990), so the graph's structure, not the number of variables, decides tractability.
Loopy belief propagation simply runs the message updates on a graph with cycles and hopes. It is not guaranteed to converge or to be exact, but it often works remarkably well: McEliece, MacKay and Cheng (1998) showed that the celebrated turbo-code decoder, which came close to the Shannon limit, is exactly loopy BP.
Hidden Markov models: a chain you can solve exactly¶
An HMM has hidden states \(z_1,\dots,z_T\) forming a Markov chain (transition matrix \(A_{ij} = p(z_t{=}j \mid z_{t-1}{=}i)\)) and an observation \(x_t\) emitted by each state (\(B_{jk} = p(x_t{=}k \mid z_t{=}j)\)). Three classic algorithms, all message passing on the chain (Rabiner's 1989 tutorial is the standard reference):
- Forward algorithm (likelihood): \(\alpha_t(j) = p(x_{1:t}, z_t{=}j) = B_{j,x_t}\sum_i\alpha_{t-1}(i)A_{ij}\), and \(p(x_{1:T}) = \sum_j\alpha_T(j)\). Cost \(O(TK^2)\) instead of \(O(K^T)\): for \(T = 100\), \(K = 2\), about 400 operations instead of \(1.3 \times 10^{30}\).
- Viterbi (most probable hidden path): the same recursion with \(\max\) in place of \(\sum\), plus back-pointers. Max-product instead of sum-product.
- Baum–Welch (learning): forward–backward gives the posterior over hidden states, which is the E-step of EM; the M-step re-estimates \(A\) and \(B\) from expected counts.
The example in Build it is the "occasionally dishonest casino" from Durbin et al.'s Biological Sequence Analysis: a casino switches between a fair die and a loaded die that shows six half the time, and Viterbi recovers when it cheated from the rolls alone. Replace the discrete states with Gaussians and linear dynamics and the same forward recursion is the Kalman filter (Kalman, 1960), still the workhorse of navigation and tracking.
Approximate inference: sample or optimise¶
When exact inference is intractable there are two great families, with opposite trade-offs.
Markov chain Monte Carlo (MCMC) builds a Markov chain whose stationary distribution is the posterior and averages over its samples. Gibbs sampling (Geman and Geman, 1984; brought to Bayesian statistics by Gelfand and Smith, 1990) resamples one variable at a time from its conditional given everything else, which by the Markov-blanket property involves only its neighbours. Metropolis–Hastings (Metropolis et al., 1953; Hastings, 1970) proposes a move and accepts it with a probability that makes the chain reversible. Hamiltonian Monte Carlo uses gradients to make long, informed moves in continuous spaces; the No-U-Turn Sampler (Hoffman and Gelman, 2014) tunes it automatically and is the engine of Stan and PyMC. MCMC is asymptotically exact but can be slow, and convergence is hard to certify.
Variational inference (VI) turns inference into optimisation: pick a tractable family \(q(\mathbf{z})\) and maximise the evidence lower bound
the same decomposition that justifies EM. Mean-field VI assumes \(q\) factorises over variables and updates each factor in turn; stochastic VI scales to huge datasets; and a VAE learns an encoder that outputs \(q(\mathbf{z}\mid\mathbf{x})\) for any \(\mathbf{x}\) (amortised inference), trained with the reparameterisation trick. VI is fast and scalable but biased: minimising \(\mathrm{KL}(q\Vert p)\) makes \(q\) mode-seeking, typically underestimating posterior variance.
| MCMC | Variational inference | |
|---|---|---|
| Output | samples from (approximately) the posterior | a tractable approximate distribution |
| Exact in the limit? | yes, with enough samples | no: limited by the family of \(q\) |
| Speed and scale | slower; hard to parallelise one chain | fast; stochastic gradients; GPUs |
| Diagnosing failure | convergence diagnostics (e.g. \(\hat R\)) | ELBO values; harder to know what you missed |
| Typical home | scientific models, small–medium data (Stan, PyMC) | large models, deep generative models, VAEs |
Learning parameters¶
Fully observed directed models decouple: the log-likelihood is a sum over nodes of \(\log p(x_i \mid \mathrm{pa}_i)\), and the maximum-likelihood estimate of each table is just normalised counts, for example \(\hat P(W{=}1\mid R{=}1,S{=}0) = \#(W{=}1,R{=}1,S{=}0)/\#(R{=}1,S{=}0)\). Counts of zero give zero probabilities that break inference, so add pseudo-counts: a Dirichlet (for two outcomes, Beta) prior, which makes learning itself Bayesian inference over a parameter node \(\theta\) with the data as its children (drawn with a plate, a box meaning "repeat \(m\) times").
Hidden variables couple everything, and EM applies: the E-step runs inference to get posteriors over the hidden variables, the M-step does weighted counting. Baum–Welch for HMMs and EM for Gaussian mixtures are instances. Undirected models are harder because of \(Z\): the gradient of the log-likelihood for parameters of an exponential-family MRF is the difference between a feature's average in the data and its expectation under the model (derived below), and the model expectation needs inference. Hinton's contrastive divergence (2002) approximates it with a few steps of Gibbs sampling started at the data; the same "data term minus model term" structure reappears in energy-based models and, in spirit, in contrastive learning.
Latent Dirichlet allocation: a model you can read¶
LDA (Blei, Ng and Jordan, 2003) shows how much a small graph can say. Each topic \(k\) is a distribution \(\boldsymbol\beta_k\) over the vocabulary. Each document \(d\) draws topic proportions \(\boldsymbol\theta_d \sim \mathrm{Dirichlet}(\boldsymbol\alpha)\); each word position draws a topic \(z \sim \mathrm{Cat}(\boldsymbol\theta_d)\) and then a word \(w \sim \mathrm{Cat}(\boldsymbol\beta_z)\). Three nested plates (topics, documents, words) and four node types define the whole model; inference by collapsed Gibbs sampling or variational EM recovers interpretable topics from raw text. For a decade it was the standard way to explore a document collection, and the generative story (sample latent structure, then sample observations) is the template that VAEs and diffusion models scale up.
Graphical models inside modern AI¶
- Language models make no independence assumptions: the chain rule with every earlier token as a parent, each conditional computed by a transformer. Inference of the next-token distribution is a single forward pass; the hard inference problems move elsewhere (finding the most probable continuation is intractable, which is why decoding uses greedy, beam or sampling).
- VAEs (Kingma and Welling, 2013) are the two-node model \(z \to x\) with a neural \(p(x\mid z)\) and amortised variational inference. Diffusion models (Ho, Jain and Abbeel, 2020) are a deep Markov chain of latents trained on a variational bound.
- State-space sequence models such as S4 and Mamba keep the HMM/Kalman structure of a hidden state updated by a linear recurrence, but deterministically and with learned, input-dependent parameters (see beyond transformers).
- Causal reasoning. A causal graph is a Bayesian network whose edges are read as mechanisms. Pearl's do-operator distinguishes seeing from doing: \(P(y \mid \mathrm{do}(x))\) is computed by cutting the edges into \(x\), and when a set \(Z\) blocks all back-door paths, \(P(y\mid\mathrm{do}(x)) = \sum_z P(y\mid x, z)P(z)\). This is the language for asking whether a model's prediction would survive an intervention, for A/B-test design and for reasoning about fairness.
- Probabilistic programming (Stan, PyMC, NumPyro) lets you write the generative story as code and get MCMC or VI for free; it is how most applied Bayesian modelling is done in 2026.
History¶
- 1921–1950s: Sewall Wright's path analysis in genetics; Markov chains; the Metropolis algorithm (1953) for statistical physics.
- 1960: Kalman's filter, a linear-Gaussian state-space model with exact recursive inference.
- 1960s–1989: hidden Markov models developed by Baum and colleagues and adopted for speech; Rabiner's 1989 tutorial.
- 1984: Geman and Geman's Gibbs sampler for image restoration on MRFs.
- 1982–1988: Pearl's belief propagation and Probabilistic Reasoning in Intelligent Systems (1988); Lauritzen and Spiegelhalter's junction tree (1988). Bayesian networks become the AI approach to uncertainty.
- 1990: Cooper proves inference NP-hard; Gelfand and Smith bring Gibbs sampling to Bayesian statistics.
- 1993–1998: turbo codes, later recognised as loopy belief propagation.
- 1999–2003: variational methods (Jordan, Ghahramani, Jaakkola and Saul); CRFs (2001); LDA (2003).
- 2000, 2009: Pearl's Causality; Koller and Friedman's textbook Probabilistic Graphical Models (2009). 2011: Pearl's Turing Award.
- 2013–2020: VAEs and diffusion models fuse graphical-model structure with neural conditionals; probabilistic programming matures.
First principles¶
Why conditional independence is the right currency. A distribution's complexity is the number of free parameters it needs. Conditional independence statements cut that number multiplicatively, and they are what domain knowledge naturally provides ("the alarm depends on burglary and earthquake, not on the weather"). The graph is just a lossless notation for a set of such statements.
Why inference is a sum and why sums are hard. Every query, marginal or posterior is a sum of the joint over the unobserved variables: exponentially many terms. Hardness is real: Bayesian network inference can encode satisfiability (count the satisfying assignments of a formula), so no algorithm is efficient on all graphs. What makes particular graphs easy is that the sum factorises (distributive law), which happens to the extent that the graph is tree-like. Message passing is the systematic exploitation of the distributive law; everything else is approximation.
Why the normaliser makes undirected models hard to learn. A directed model is normalised node by node, so its likelihood splits into independent local terms. An undirected model is normalised globally, so every parameter appears in \(Z\), every gradient needs a model expectation, and every model expectation needs inference. This is the deep reason energy-based models were eclipsed by models with tractable likelihoods (autoregressive, flows, VAEs) or no likelihood at all (GANs, score matching, which sidesteps \(Z\) by learning \(\nabla_\mathbf{x}\log p\), since the gradient of \(\log Z\) with respect to \(\mathbf{x}\) is zero).
Why explaining away happens. At a collider, the observation \(W = 1\) demands a cause. Each cause alone is sufficient, so learning that one is present removes the need for the other: \(P(R\mid W, S) < P(R\mid W)\). Formally, conditioning on a common effect couples its parents, \(p(r, s\mid w) \propto p(r)p(s)p(w\mid r,s)\), which does not factorise in \(r\) and \(s\) because \(p(w\mid r,s)\) does not.
Why MCMC is exact and VI is not. MCMC changes the sampler but targets the true posterior: given enough steps, the bias vanishes. VI changes the target: it returns the closest member of a restricted family, and no amount of computation removes the gap if the true posterior lies outside the family.
The maths¶
Factorisations. Directed: \(p(\mathbf{x}) = \prod_i p(x_i\mid\mathrm{pa}_i)\). Undirected: \(p(\mathbf{x}) = Z^{-1}\prod_C\psi_C(\mathbf{x}_C)\). Exponential-family MRF: \(p_\theta(\mathbf{x}) = \exp\big(\theta^\top\boldsymbol\phi(\mathbf{x}) - \log Z(\theta)\big)\) with feature vector \(\boldsymbol\phi\).
HMM recursions. With \(K\) states, \(A \in \mathbb{R}^{K\times K}\), emission column \(\mathbf{b}_t = (p(x_t\mid z_t{=}j))_j \in \mathbb{R}^K\), initial \(\boldsymbol\pi\):
Viterbi replaces the sum in \(A^\top\boldsymbol\alpha\) by a max: \(\delta_t(j) = b_t(j)\max_i\delta_{t-1}(i)A_{ij}\), computed in log space. Scale \(\boldsymbol\alpha_t\) to sum to one at every step and accumulate the logs of the scale factors, or the probabilities underflow after a few hundred steps.
Derivation: the forward recursion
\(\alpha_t(j) = p(x_{1:t}, z_t{=}j) = \sum_i p(x_{1:t}, z_{t-1}{=}i, z_t{=}j)\). Factorise with the model's independences: \(x_t\) depends only on \(z_t\), and \(z_t\) only on \(z_{t-1}\):
Summing over \(i\) gives the recursion. Each step costs \(K^2\), so the total is \(O(TK^2)\). The independence assumptions are used exactly once each, which is the general pattern: every independence the graph encodes is a sum that can be moved inward.
Derivation: the MRF log-likelihood gradient is data minus model
For \(p_\theta(\mathbf{x}) = \exp(\theta^\top\boldsymbol\phi(\mathbf{x}))/Z(\theta)\) and data \(\mathbf{x}^{(1)},\dots,\mathbf{x}^{(m)}\):
So \(\nabla_\theta = \mathbb{E}_{\text{data}}[\boldsymbol\phi] - \mathbb{E}_{p_\theta}[\boldsymbol\phi]\): at the maximum-likelihood solution, model expectations of the features match their empirical averages (moment matching). The log-likelihood is concave in \(\theta\) (since \(\nabla^2\log Z\) is the covariance of \(\boldsymbol\phi\)), so there is no bad local optimum; the difficulty is purely computing \(\mathbb{E}_{p_\theta}[\boldsymbol\phi]\), which is inference.
Derivation: the mean-field update
Let \(q(\mathbf{z}) = \prod_j q_j(z_j)\). Isolate one factor in the ELBO:
where \(\mathbb{E}_{-j}\) is the expectation over all other factors. Define \(\log\tilde p_j(z_j) = \mathbb{E}_{-j}[\log p(\mathbf{x},\mathbf{z})] + \text{const}\) (normalised). Then \(\mathcal{L} = -\mathrm{KL}(q_j\,\Vert\,\tilde p_j) + \text{const}\), maximised at \(q_j^{*}(z_j) \propto \exp\big(\mathbb{E}_{-j}[\log p(\mathbf{x},\mathbf{z})]\big)\). Cycling through the factors is coordinate ascent on the ELBO, and each update depends only on the expectations of variables in \(z_j\)'s Markov blanket. Compare Gibbs sampling, which samples \(z_j\) from \(p(z_j\mid\mathbf{z}_{-j})\) where mean-field averages the log of it.
Back-door adjustment. If \(Z\) contains no descendant of \(X\) and blocks every path between \(X\) and \(Y\) that starts with an arrow into \(X\), then \(P(y\mid\mathrm{do}(x)) = \sum_z P(y\mid x, z)P(z)\). Contrast the observational \(P(y\mid x) = \sum_z P(y\mid x,z)P(z\mid x)\): the difference is precisely confounding through \(Z\).
In practice¶
- Model the story. Draw the generative process first (what causes what, what is hidden), then write it in a probabilistic programming language. Simulate fake data from the model and check that it looks like real data before fitting (prior predictive checks).
- Exact when you can. Chains and trees (HMMs, Kalman filters, tree-structured networks) admit exact, fast inference; use it. Libraries such as pgmpy implement variable elimination and belief propagation for discrete networks.
- NUTS for small and medium continuous models; VI for scale. Stan or PyMC with NUTS is the default for scientific and business models up to tens of thousands of parameters; check convergence diagnostics. Switch to VI (or amortised VI) when data or models are large, and remember it underestimates uncertainty.
- Know where they still win. As of 2026 explicit graphical models remain the right tool when data are scarce and structure is known (epidemiology, reliability, finance risk models), when you need calibrated uncertainty or interpretable assumptions, when sensors must be fused over time (Kalman filters, SLAM), and for causal questions. For raw perception and language, neural models win, but their outputs often feed a small graphical model downstream.
In Finny
A FIRE plan is a causal story with uncertain nodes (returns, inflation, income growth, life events) and a deterministic engine that turns them into outcomes. The Jarvis case study follows the same division of labour this page recommends: the model routes and explains, while computation over the plan's variables happens in code, where its assumptions can be read and checked.
Common misconceptions¶
“Arrows in a Bayesian network mean causation”
Only in a causal graph, which is an extra assumption. Many DAGs encode the same independences (for example \(A \to B\) and \(B \to A\)), so data alone usually cannot orient edges. Reading a learned network causally needs interventions or strong assumptions.
“Independent causes stay independent”
Not once you condition on their common effect. Explaining away and selection bias are the same phenomenon, and conditioning on a collider is one of the commonest analysis errors in observational data.
“Deep learning made graphical models obsolete”
It replaced hand-specified conditional tables with neural networks. The factorisations, the ELBO, message passing on chains and the independence logic are the backbone of language models, VAEs, diffusion models and state-space models.
Build it¶
First, exact inference by enumeration on the running example, and a Gibbs sampler that only ever needs ratios of the joint:
import numpy as np
from itertools import product
rng = np.random.default_rng(0)
# Bayesian network: Rain -> Wet <- Sprinkler (a collider), plus Rain -> Traffic
pR, pS = 0.2, 0.1
pW = {(1, 1): 0.99, (1, 0): 0.90, (0, 1): 0.80, (0, 0): 0.01} # P(W=1 | R, S)
pT = {1: 0.7, 0: 0.2} # P(T=1 | R)
def joint(x): # the factorisation p(r) p(s) p(w|r,s) p(t|r)
r, s, w, t = x["R"], x["S"], x["W"], x["T"]
return ((pR if r else 1-pR) * (pS if s else 1-pS)
* (pW[r, s] if w else 1-pW[r, s]) * (pT[r] if t else 1-pT[r]))
def query(target, **evidence): # exact inference by enumerating all 2^4 worlds
num = den = 0.0
for r, s, w, t in product((0, 1), repeat=4):
world = dict(R=r, S=s, W=w, T=t)
if any(world[k] != v for k, v in evidence.items()): continue
p = joint(world); den += p; num += p * world[target]
return num / den
print(f"P(R=1) = {query('R'):.3f}")
print(f"P(R=1 | W=1) = {query('R', W=1):.3f} wet grass raises belief in rain")
print(f"P(R=1 | W=1, S=1) = {query('R', W=1, S=1):.3f} ...the sprinkler explains it away")
print(f"P(S=1 | R=1) = {query('S', R=1):.3f} = P(S=1): R and S independent a priori")
print(f"P(S=1 | W=1) = {query('S', W=1):.3f}")
print(f"P(S=1 | W=1, R=1) = {query('S', W=1, R=1):.3f} ...dependent once we condition on W")
print(f"P(R=1 | T=1, W=1) = {query('R', T=1, W=1):.3f} two pieces of evidence combine")
# Gibbs sampling for P(R=1 | W=1): resample each hidden variable from its full conditional
state = dict(R=0, S=0, W=1, T=0); hits = []
for it in range(20_000):
for v in ("R", "S", "T"):
p1, p0 = joint({**state, v: 1}), joint({**state, v: 0}) # only v's Markov blanket matters
state[v] = int(rng.random() < p1 / (p0 + p1))
if it >= 1000: hits.append(state["R"])
print(f"Gibbs estimate of P(R=1 | W=1) = {np.mean(hits):.3f} (19,000 samples after burn-in)")
P(R=1) = 0.200
P(R=1 | W=1) = 0.719 wet grass raises belief in rain
P(R=1 | W=1, S=1) = 0.236 ...the sprinkler explains it away
P(S=1 | R=1) = 0.100 = P(S=1): R and S independent a priori
P(S=1 | W=1) = 0.331
P(S=1 | W=1, R=1) = 0.109 ...dependent once we condition on W
P(R=1 | T=1, W=1) = 0.899 two pieces of evidence combine
Gibbs estimate of P(R=1 | W=1) = 0.712 (19,000 samples after burn-in)
The enumeration reproduces the hand calculations. Explaining away runs both ways: wet grass makes the sprinkler likely (0.331), and learning it rained drops that to 0.109. Gibbs sampling agrees with the exact 0.719 to within Monte Carlo error, and notice what it needed: only the ratio \(p_1/(p_0 + p_1)\), in which \(Z\) and every factor not touching the resampled variable cancel.
Second, an HMM: the forward algorithm (checked against brute-force enumeration of all hidden paths) and Viterbi decoding of the dishonest casino:
import numpy as np
from itertools import product
rng = np.random.default_rng(7)
# The occasionally dishonest casino (Durbin et al.): a fair die and a loaded die (P(6) = 1/2)
A = np.array([[0.95, 0.05], # transitions: fair -> fair/loaded
[0.10, 0.90]]) # loaded -> fair/loaded
B = np.array([[1/6] * 6, # emissions for faces 1..6
[0.1] * 5 + [0.5]])
pi = np.array([0.5, 0.5])
def sample(T):
z = [rng.choice(2, p=pi)]
for _ in range(T - 1): z.append(rng.choice(2, p=A[z[-1]]))
return np.array(z), np.array([rng.choice(6, p=B[k]) for k in z])
def forward(x): # log p(x) in O(T K^2), scaled to avoid underflow
a = pi * B[:, x[0]]; logp = np.log(a.sum()); a /= a.sum()
for t in range(1, len(x)):
a = (a @ A) * B[:, x[t]]; c = a.sum(); logp += np.log(c); a /= c
return logp
def viterbi(x): # most probable hidden path, in log space
d = np.log(pi) + np.log(B[:, x[0]]); back = []
for t in range(1, len(x)):
s = d[:, None] + np.log(A) # s[i, j]: best path ending i, then i -> j
back.append(s.argmax(0)); d = s.max(0) + np.log(B[:, x[t]])
path = [int(d.argmax())]
for b in reversed(back): path.append(int(b[path[-1]]))
return np.array(path[::-1])
z, x = sample(8) # check the recursion against brute force
brute = sum(np.prod([pi[zz[0]] * B[zz[0], x[0]]] + [A[zz[t-1], zz[t]] * B[zz[t], x[t]]
for t in range(1, 8)]) for zz in product((0, 1), repeat=8))
print(f"T=8: forward log p(x) = {forward(x):.6f}, brute force over 2^8 paths = {np.log(brute):.6f}")
z, x = sample(300)
print("rolls :", "".join(str(v + 1) for v in x[:60]))
print("truth :", "".join("FL"[v] for v in z[:60]))
print("viterbi:", "".join("FL"[v] for v in viterbi(x)[:60]))
print(f"Viterbi accuracy over 300 rolls: {np.mean(viterbi(x) == z):.3f}; log p(x) = {forward(x):.1f}"
f" vs all-fair die {300 * np.log(1/6):.1f}")
T=8: forward log p(x) = -14.719533, brute force over 2^8 paths = -14.719533
rolls : 642662656116124352625131225316662321141263263636664562226636
truth : LLLLLLLFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFLLLLLLLLLFLLLLLLLL
viterbi: LLLLLLLLLFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFLLLLLLLLLLLLLLLLL
Viterbi accuracy over 300 rolls: 0.843; log p(x) = -524.3 vs all-fair die -537.5
The forward algorithm matches the \(2^8\)-path sum to six decimals in 8 steps of \(2\times2\) work. Viterbi finds the loaded stretches from the clustering of sixes, lagging by a roll or two at each switch because it needs a few sixes as evidence (accuracy was 0.71–0.84 across the six seeds we tried, depending on how many sixes the loaded stretches happened to produce). The HMM explains the rolls far better than a fair die: a log-likelihood ratio of 13.2 nats.
Things to try
- Implement the backward pass and posterior decoding \(p(z_t\mid x_{1:T})\); plot it against the truth and compare its per-roll accuracy with Viterbi's.
- Implement Baum–Welch: start from wrong \(A\) and \(B\), run EM on 5,000 rolls, and watch it recover the loaded die's 0.5 probability of a six. Check that \(\log p(x)\) never decreases.
- In the Bayesian network, compute \(P(R{=}1\mid \mathrm{do}(W{=}1))\) by deleting the edges into \(W\). Why is it 0.2, unlike \(P(R{=}1\mid W{=}1) = 0.719\)?
- Run the Gibbs sampler with the evidence \(W{=}1, S{=}1\) and starting state \(R = 0\). Then make the CPTs nearly deterministic (0.999 and 0.001) and watch how slowly the chain mixes.
- Write the network in pgmpy or PyMC and reproduce the numbers.
Check yourself¶
How many free parameters does the four-node running example need, and how many would an unrestricted joint over the same four binary variables need?
Rain 1, Sprinkler 1, Wet grass 4 (one per parent configuration), Traffic 2: total 8. The unrestricted joint needs \(2^4 - 1 = 15\).
In the DAG A → B → C ← D, are A and D independent? Are they independent given C? Given B?
\(A\) and \(D\) are independent: the only path passes through the collider \(C\), which is unobserved. Given \(C\), the collider opens and they become dependent. Given \(B\) alone they remain independent (the path is still blocked at the unobserved collider \(C\); observing \(B\) blocks it at \(B\) too).
Why does the forward algorithm cost O(TK²) and not O(K^T)?
The Markov property lets the sum over all earlier states be summarised in a \(K\)-vector \(\boldsymbol\alpha_{t-1}\): the future depends on the past only through \(z_{t-1}\). Each step multiplies a \(K\)-vector by a \(K\times K\) matrix, so \(T\) steps cost \(TK^2\). Enumeration would revisit the same partial sums exponentially many times.
Gibbs sampling never needs the normalising constant Z of the posterior. Why?
Each update samples \(x_j \sim p(x_j\mid\mathbf{x}_{-j}) = p(\mathbf{x})/\sum_{x_j'}p(x_j', \mathbf{x}_{-j})\). \(Z\) appears in numerator and denominator and cancels, as do all factors not involving \(x_j\). Only the factors in \(x_j\)'s Markov blanket matter.
You fit a model with mean-field VI and with NUTS. The VI posterior for a parameter has standard deviation 0.1; NUTS gives 0.3. Which do you trust and why the difference?
Trust NUTS, assuming its diagnostics are clean. Mean-field VI minimises \(\mathrm{KL}(q\Vert p)\), which heavily penalises \(q\) putting mass where \(p\) has little, so \(q\) squeezes inside the posterior; factorised \(q\) also ignores correlations between parameters, which shrinks marginal variances further. Underestimated uncertainty is the classic VI failure.
Hard: an autoregressive language model is a Bayesian network. What is its graph, what independence assumptions does it make, and why is finding the single most probable sentence still hard?
The graph has an edge from every earlier token to every later one: the chain-rule factorisation, which makes no conditional-independence assumptions at all; all the modelling lives in the neural conditionals. Computing the probability of a given sentence is easy (one forward pass), but the most probable sentence is a max over \(V^T\) sequences with no chain-like structure to exploit, since each conditional depends on the whole prefix. Greedy and beam search are approximations, and they do not find the true mode.
Hard: why is maximum likelihood for an undirected model a concave problem, yet still hard?
The log-likelihood \(\theta^\top\bar{\boldsymbol\phi} - \log Z(\theta)\) is concave because \(\log Z\) is convex: its Hessian is the covariance of \(\boldsymbol\phi\) under \(p_\theta\), which is positive semi-definite. So there are no bad local optima. But evaluating the objective needs \(Z\) and evaluating the gradient needs \(\mathbb{E}_{p_\theta}[\boldsymbol\phi]\), both of which require inference, which is #P-hard in general. Optimisation is easy; the oracle it calls is not.
Go deeper¶
Papers
- A tutorial on hidden Markov models and selected applications in speech recognition — Rabiner, Proc. IEEE, 1989. The three HMM problems and their algorithms; the classic tutorial.
- Local computations with probabilities on graphical structures — Lauritzen and Spiegelhalter, JRSS B, 1988. The junction tree algorithm.
- Stochastic Relaxation, Gibbs Distributions, and the Bayesian Restoration of Images — Geman and Geman, 1984. MRFs for images and the Gibbs sampler.
- An Introduction to Variational Methods for Graphical Models — Jordan, Ghahramani, Jaakkola and Saul, 1999. Where modern variational inference starts.
- Variational Inference: A Review for Statisticians — Blei, Kucukelbir and McAuliffe, 2017. The best single modern introduction to VI.
- Conditional Random Fields — Lafferty, McCallum and Pereira, ICML 2001. Discriminative sequence labelling and the label-bias problem.
- Latent Dirichlet Allocation — Blei, Ng and Jordan, JMLR 2003. A generative model of documents you can read in one sitting.
- Turbo decoding as an instance of Pearl's "belief propagation" algorithm — McEliece, MacKay and Cheng, 1998. Loopy BP's most famous success.
- The No-U-Turn Sampler — Hoffman and Gelman, JMLR 2014. The sampler inside Stan and PyMC.
- Auto-Encoding Variational Bayes — Kingma and Welling, 2013; and Denoising Diffusion Probabilistic Models: Ho, Jain and Abbeel, 2020. Graphical models with neural factors.
Videos and lectures
- CMU 10-708 Probabilistic Graphical Models (Spring 2020) — Eric Xing. Every lecture has slides, scribe notes and a recording, from representation through VI to deep generative models.
- Probabilistic Graphical Models Specialization — Daphne Koller, Stanford on Coursera. The course version of the Koller–Friedman textbook.
Articles and notes
- Stanford CS228 notes — Ermon group. Concise, well-illustrated notes from representation to learning; the gentlest rigorous path.
Courses and books
- Pattern Recognition and Machine Learning — Bishop, 2006 (free PDF). Chapter 8 (graphical models), 10 (VI), 11 (sampling), 13 (HMMs and linear dynamical systems).
- Probabilistic Machine Learning — Murphy (free). Book 2 covers PGMs, inference and deep generative models in one modern notation.
- Bayesian Reasoning and Machine Learning — Barber (free). Strong on inference algorithms, with code.
- Information Theory, Inference, and Learning Algorithms — MacKay (free). Message passing, Monte Carlo and codes, by one of the people who connected them.
- Causality — Pearl, 2nd edition 2009. The do-calculus and causal graphs.
Code
- pgmpy, PyMC, Stan and NumPyro — Discrete networks with exact inference; probabilistic programming with NUTS and VI.
Where this leads¶
- Autoencoders and VAEs: the latent-variable model and ELBO from this page, with neural networks for both factors.
- Diffusion models: a long chain of latent variables trained on a variational bound.
- The language-modelling objective: the chain rule as a model, and why its likelihood is tractable.
- Beyond transformers: SSMs, Mamba, linear attention: state-space structure, now deterministic and learned.
- Robustness, fairness and privacy: causal graphs as the language for asking what a model's decisions depend on.