Variable elimination is an exact inference algorithm for probabilistic models that computes marginal or conditional probabilities by summing out unobserved variables one at a time, reusing intermediate results instead of enumerating the full joint distribution. It applies to Bayesian networks, Markov random fields and factor graphs, and it is the conceptual foundation of the junction tree algorithm and many other exact methods in artificial intelligence.
The algorithm exploits the fact that a joint distribution in a graphical model factorizes into local factors. By pushing summations inside products, it replaces an exponential sum over all variables with a sequence of smaller operations whose cost depends on the elimination order and the structure of the graph.
How variable elimination computes a marginal
Variable elimination answers a query such as P(Q | E = e) by working with a set of factors, which are functions over small groups of variables. In a Bayesian network, each conditional probability table is a factor; in a Markov random field, each clique potential is a factor. Evidence is applied first by restricting every factor to the observed values.
The algorithm then repeats one step for each hidden variable in a chosen order: it multiplies all factors that mention the variable, sums the variable out of the product, and adds the resulting new factor back to the pool. When only the query variables remain, the product of the remaining factors is normalized to give the answer.
- Restrict all factors to the observed evidence values.
- Choose an elimination order for the hidden variables.
- For each variable, multiply the factors containing it and sum it out.
- Multiply the remaining factors over the query variables.
- Normalize the result to obtain a probability distribution.
The same procedure works for maximization instead of summation. Replacing sums with max operations yields the most probable explanation, a form known as max-product elimination, which is closely related to the Viterbi algorithm on chains.
Why elimination order determines cost
The cost of variable elimination is dominated by the largest intermediate factor created during the run. If that factor spans k variables, each with d values, the work grows roughly as d to the power k. The order in which variables are eliminated decides how large these factors become.
The smallest achievable maximum factor size, minus one, equals the treewidth of the graph. Finding an optimal order is NP-hard in general, so practical systems rely on greedy heuristics that usually perform well. The table below compares common heuristics.
| Heuristic | Selection rule | Typical behavior |
|---|---|---|
| Min-neighbors | Eliminate the variable with the fewest neighbors | Fast and simple, sometimes suboptimal |
| Min-weight | Minimize the product of neighbor domain sizes | Better when domain sizes differ |
| Min-fill | Minimize new edges added to the graph | Often the best general-purpose choice |
| Weighted min-fill | Weight new edges by domain sizes | Strong on mixed-cardinality models |
Eliminating a variable connects all of its neighbors, creating fill-in edges in the moralized or undirected graph. A poor order adds many such edges and produces huge factors, while a good order keeps factors small. On trees and polytrees, a suitable order yields linear-time inference.
Complexity on typical model structures
Exact inference in general graphical models is NP-hard, and variable elimination does not escape this limit. Its practical value comes from the many real models whose structure keeps the treewidth low. The following table summarizes how structure affects feasibility.
| Model structure | Treewidth | Practical outcome |
|---|---|---|
| Chain or hidden Markov model | 1 | Linear in sequence length |
| Tree or polytree | 1 in the undirected graph | Linear in the number of variables |
| Sparse network with small loops | Low, often under 10 | Usually tractable |
| Grid of size n by n | About n | Exponential in grid width |
| Densely connected model | Close to variable count | Intractable, approximation needed |
Memory is often the binding constraint. A single intermediate factor over 30 binary variables already holds more than a billion entries, so implementations typically estimate factor sizes before execution and switch to approximate inference when limits are exceeded.
Variable elimination compared with related inference methods
Variable elimination is best understood as the single-query member of a family of exact algorithms. Belief propagation and the junction tree algorithm reorganize the same computations so that many marginals can be obtained at once, while sampling and variational methods trade exactness for scalability.
| Method | Exact or approximate | Best suited for |
|---|---|---|
| Variable elimination | Exact | One query on a low-treewidth model |
| Junction tree algorithm | Exact | All single-clique marginals at once |
| Belief propagation | Exact on trees, approximate on loops | Fast message passing on sparse graphs |
| Gibbs sampling | Approximate | Large models with tractable conditionals |
| Variational inference | Approximate | Very large or continuous models |
A key drawback is lack of reuse across queries. Running variable elimination separately for every variable repeats most of the work, which is why the junction tree algorithm caches messages on a tree of cliques derived from an elimination order.
Practical considerations and pitfalls
Implementations should apply pruning before elimination. Variables that are neither queried, observed nor ancestors of those variables in a Bayesian network are barren nodes and can be removed without changing the answer, and d-separation identifies further irrelevant parts of the graph.
- Numerical underflow occurs when many small probabilities are multiplied; working in log space or rescaling factors avoids it.
- Continuous variables require integrals instead of sums, which are closed-form only in special cases such as linear Gaussian models.
- Evidence placement matters: applying evidence early shrinks factors and can reduce cost substantially.
- Order quality should be checked by computing the induced width before running the full computation.
Modern probabilistic programming systems and libraries for graphical models use variable elimination as a default exact engine for small and medium models, and fall back to sampling or variational methods when the estimated induced width is too large.
Put simply
Variable elimination is a smart way to add up probabilities. A model may contain dozens of unknowns. Checking every combination would take far too long. The method removes one unknown at a time instead.
Imagine counting money in a large stack of envelopes. You could list every coin in every envelope. It is faster to total each envelope first and write the number on it. Then you only add the small totals. Variable elimination does the same with probabilities. The order in which you open the envelopes decides how much work remains.
In practice
A hospital analytics team builds a diagnostic Bayesian network with 40 binary variables that link risk factors, diseases and test results. A clinician wants the probability of pneumonia for a patient with fever, a positive chest X-ray and a normal white blood cell count.
Enumerating the joint distribution would require summing over roughly two to the power 36 combinations of hidden variables. The team runs variable elimination with the min-fill heuristic, which finds an order whose largest intermediate factor covers only seven variables. Barren nodes unrelated to the query are pruned first.
The query returns in a few milliseconds with an exact posterior of about 0.72. Because the clinician later asks about several other diseases for the same patient, the team switches to the junction tree algorithm, which reuses the same elimination structure and answers all marginals in one pass.