Exact inference: variable elimination and treewidth
Exact inference in graphical models reduces to summing products of factors in a clever order. Implement variable elimination, see how cost depends on the chosen order's induced width, prove that the general problem is NP-hard, and distinguish marginal, MPE and marginal MAP queries.
After this lesson you can
- Perform variable elimination on tabular factors by hand and in code.
- Calculate the induced width of an elimination order and apply minimum-fill heuristics.
- Prove NP-hardness of Bayesian-network inference by reduction from 3-SAT.
- Distinguish marginal, MPE and marginal MAP queries and explain why they are not interchangeable.
- Recognize variable elimination as tensor contraction with einsum.
Before you start
Sum without building the entire joint distribution
To diagnose a disease we want , not a table of every possible combination of hospital variables. A Bayesian network or factor graph represents the joint as a product of local tables. Structure allows variables no longer needed to be summed out before forming a global product.
A factor is a nonnegative table with one axis per variable. The product of and has axes and value . Reduction by evidence selects a slice and removes axis . Marginalizing sums its values:
Axis names matter: equally shaped tables may represent different variables. Cardinalities for the same variable must match. A scalar table is a factor without axes; retaining it is necessary to preserve evidence weight.
Variable elimination
For query , first reduce each factor using . Choose hidden variable , multiply all factors containing and sum out of the product. Replace those factors with the result and repeat for the remaining non-query variables. Finally multiply remaining factors and normalize over .
Eliminating a variable is correct by distributivity: factors that do not contain are constant with respect to its sum and can move outside it. Every step preserves the original sum of products exactly. The order of summation does not change the result, although it changes the shape and size of intermediate factors. If evidence has zero probability, the conditional is undefined.
In this synthetic example , , , and . Test and symptom are independent given D. Query with evidence : multiply the three reduced factors and sum out D. For , products of and are and , summing to . For we obtain . Their sum is and hence . These figures come from the tables, not clinical data.
The counter compares two concrete strategies: enumerate eight configurations and perform two multiplications per configuration, or reduce evidence first and perform two multiplications for each D and T combination. Then sum D for each T. Additions, reads and memory access are omitted; this is not a timing comparison. Do not normalize every intermediate factor if you need evidence probability: changing scale without saving the constant can preserve the final posterior but loses .
A bucket that does reduce a chain
Consider with , , , and . We want . Reduction leaves as a vector over B. To eliminate B, multiply that vector and , then sum B:
This yields and . Multiplying by A’s prior gives weights and . They sum to and the result is . There is no need to build the eight-entry table .
This illustrates what enters a bucket: only factors containing the eliminated variable. A’s prior does not contain B, so it stays outside the sum. Any other factor containing B must enter the same product before summing. The new factor summarizes all B possibilities for each retained A value.
The procedure also computes a multi-axis query. For example, retains both and eliminates only hidden variables; the result is a two-dimensional table summing to one. An observed variable must not be treated as free again: its evidence has selected a slice. With no hidden variables, multiply reduced factors and normalize.
The induced graph and order
Build the primal graph by connecting variables occurring in one factor. When eliminating a node, all active neighbors share a factor and are connected by fill edges. An order’s induced width is the maximum number of active neighbors of a node when eliminated. Treewidth is the minimum of that width over all complete orders.
With binary neighbors, the bucket product can have entries before summing out the variable; the result has up to . With unequal cardinalities the actual cardinality product matters, not just . In a star with six leaves, eliminating the center first produces a bucket with entries and width six. Eliminating leaves first keeps width one. On a square lattice, treewidth grows linearly with : no order makes all intermediate tables constant-sized.
Finding the best order is difficult in general. Min-fill counts missing edges between each candidate’s neighbors and eliminates the one needing the fewest; min-degree chooses the one with fewest active neighbors. These are heuristics, not optimal-width guarantees. Evidence reduces scopes before building the graph, and query variables remain active. Partial-elimination width includes these retained neighbors; do not confuse it with the full graph’s minimum treewidth.
To apply min-fill by hand, list each candidate’s active neighbors, count pairs lacking an edge, select the minimum and add those edges. Recalculate afterward: fill edges change degrees and scores for the next choice. Ties can use several rules; this lesson’s code breaks ties by degree, then node name converted to text for reproducibility.
Width predicts an exponential bound, not exact implementation cost. Sparse table multiplication can exploit zeros, while dense representation allocates every entry. Bucket factor count, cardinalities, simultaneous storage and each table’s specific structure also matter. Equal maximum widths can still yield different total operations or other factor sizes. In a highly imbalanced model, eliminating a high-cardinality variable can cost more than neighbor count suggests.
A directed network’s graph must reflect table scopes. A table connects A, B and C in the primal graph: the parents gain an edge even without a direct arrow. This is moralization applied to the node’s family. After observation, building the graph from already reduced factors can remove axes and reduce work.
Difficulty is structural
Inference hardness is not established by one example of a bad order. Given a 3-SAT formula with Boolean variables and clauses, create an independent Bernoulli root for each variable. For each clause create a deterministic node equal to one exactly when the clause is true; its parents are the variables appearing in it. Connect clause outputs through a binary tree of deterministic AND nodes and call its output . The network has polynomial size and
Thus deciding whether decides satisfiability: a general polynomial solution would solve 3-SAT. Exact marginal computation also recovers the number of satisfying assignments by multiplying by , so it is #P-hard by that counting reduction. Deterministic tables with zeros are essential to this construction. This does not say every network is hard: chains and bounded-width trees allow efficient inference with bounded cardinalities. The classic result by Cooper analyzes inference complexity in belief networks.
Marginal, MPE and marginal MAP
Query types answer different questions. A marginal sums every non-query variable. MPE seeks the most probable joint configuration of unobserved variables given observations. Marginal MAP on a subset first sums the rest and then maximizes over that subset. The vector of individual marginal modes need not be MPE, or even have positive probability.
With initial weights , and , all three individual modes are zero, but . MPE is . For MAP of , sum Z: probabilities of are , and MAP is . These are different queries and the last result has only two coordinates.
For marginal MAP, operator order matters. Generally : for example with the first equals one and the second two. Elimination that exchanges maximum and sum can solve a different query. For MPE, save the decisions from each elimination as well as maxima to reconstruct the configuration by backtracking.
An interpretation of the inequality: on the right each value of can choose a different before summing. On the left one must be chosen for all values after accumulating uncertainty. Thus for marginal MAP, a safe strategy sums non-answer variables first and maximizes answer variables afterward. This can restrict available orders and increase cost relative to an ordinary marginal.
Impossible evidence needs an explicit check. If , the usual quotient defines no conditional distribution: returning zeros or dividing by zero hides a model or data problem. For very unlikely but positive evidence, floating-point arithmetic can lose precision; scaling with recorded constants or log calculations can help. In log space, adding probabilities needs log-sum-exp, not a maximum unless explicitly approximating.
Tensor contractions
A factor is a tensor with named axes. Multiplying factors and summing out a variable is a tensor contraction. For example, is expressed as np.einsum('ab,bc->ac', phi, psi). One call can specify the whole query; the chosen path determines which intermediate products form. np.einsum_path shows a path and cost estimates, while min-fill operates on graph scopes: they need not choose the same order or optimize exactly the same metric.
Lab: a factor engine
The next class retains axis names and validates cardinalities. Evidence selects integer state indices. The engine returns posterior, evidence weight, min-fill order and partial-elimination width; an independent enumerator provides a control. This cell is self-contained.
"""Factores tabulares con ejes nombrados e inferencia exacta discreta."""
from itertools import product
import numpy as np
class Factor:
def __init__(self, scope, values):
self.scope = tuple(scope)
self.values = np.asarray(values, dtype=float)
if len(set(self.scope)) != len(self.scope) or self.values.ndim != len(self.scope):
raise ValueError('cada eje debe tener un nombre distinto')
if not np.all(np.isfinite(self.values)) or np.any(self.values < 0):
raise ValueError('los factores deben ser finitos y no negativos')
def restrict(self, variable, value):
if variable not in self.scope:
return self
axis = self.scope.index(variable)
if not isinstance(value, (int, np.integer)) or not 0 <= value < self.values.shape[axis]:
raise ValueError('valor de evidencia fuera del dominio')
scope = self.scope[:axis] + self.scope[axis+1:]
return Factor(scope, np.take(self.values, value, axis=axis))
def __mul__(self, other):
union = self.scope + tuple(v for v in other.scope if v not in self.scope)
for v in set(self.scope) & set(other.scope):
if self.values.shape[self.scope.index(v)] != other.values.shape[other.scope.index(v)]:
raise ValueError('cardinalidades incompatibles')
def align(factor):
ordered = [v for v in union if v in factor.scope]
axes = [factor.scope.index(v) for v in ordered]
data = np.transpose(factor.values, axes) if axes else factor.values
shape = [factor.values.shape[factor.scope.index(v)] if v in factor.scope else 1 for v in union]
return data.reshape(shape)
return Factor(union, align(self) * align(other))
def sum_out(self, variable):
if variable not in self.scope:
return self
axis = self.scope.index(variable)
return Factor(self.scope[:axis] + self.scope[axis+1:], self.values.sum(axis=axis))
def reorder(self, order):
order = tuple(order)
if set(order) != set(self.scope) or len(order) != len(self.scope):
raise ValueError('orden incompatible')
return Factor(order, np.transpose(self.values, [self.scope.index(v) for v in order]))
def factor_graph(factors):
graph = {v: set() for factor in factors for v in factor.scope}
for factor in factors:
for v in factor.scope:
graph[v].update(set(factor.scope) - {v})
return graph
def min_fill_order(graph, candidates=None):
"""Ordena candidatos; el ancho incluye vecinos retenidos en la consulta."""
graph = {v: set(neighbors) for v, neighbors in graph.items()}
if any(v in ns or any(u not in graph or v not in graph[u] for u in ns) for v, ns in graph.items()):
raise ValueError('se requiere un grafo simple no dirigido')
remaining = set(graph) if candidates is None else set(candidates)
if not remaining <= set(graph):
raise ValueError('candidato ausente del grafo')
order, width = [], 0
while remaining:
def score(v):
ns = list(graph[v])
missing = sum(b not in graph[a] for i, a in enumerate(ns) for b in ns[i+1:])
return missing, len(ns), str(v)
v = min(remaining, key=score)
neighbors = list(graph[v])
width = max(width, len(neighbors))
for a in neighbors:
graph[a].update(set(neighbors) - {a})
graph[a].discard(v)
del graph[v]
remaining.remove(v)
order.append(v)
return order, width
def variable_elimination(factors, query, evidence=None):
evidence = {} if evidence is None else dict(evidence)
query = tuple(query)
if not factors:
raise ValueError('se requiere al menos un factor')
sizes = {}
for factor in factors:
for variable, size in zip(factor.scope, factor.values.shape):
if variable in sizes and sizes[variable] != size:
raise ValueError('cardinalidades incompatibles')
sizes[variable] = size
graph0 = factor_graph(factors)
if len(set(query)) != len(query) or not set(query) <= set(graph0) or set(query) & set(evidence):
raise ValueError('consulta y evidencia deben ser variables distintas del modelo')
if not set(evidence) <= set(graph0):
raise ValueError('evidencia ajena al modelo')
reduced = list(factors)
for variable, value in evidence.items():
reduced = [factor.restrict(variable, value) for factor in reduced]
graph = factor_graph(reduced)
order, width = min_fill_order(graph, set(graph) - set(query))
for variable in order:
bucket = [factor for factor in reduced if variable in factor.scope]
reduced = [factor for factor in reduced if variable not in factor.scope]
joint = bucket[0]
for factor in bucket[1:]:
joint = joint * factor
reduced.append(joint.sum_out(variable))
joint = reduced[0]
for factor in reduced[1:]:
joint = joint * factor
result = joint.reorder(query)
evidence_weight = result.values.sum()
if evidence_weight <= 0:
raise ValueError('evidencia con peso cero')
return Factor(query, result.values / evidence_weight), evidence_weight, order, width
def exhaustive(factors, query, evidence=None):
evidence = {} if evidence is None else dict(evidence)
sizes = {}
for factor in factors:
for variable, size in zip(factor.scope, factor.values.shape):
if variable in sizes and sizes[variable] != size:
raise ValueError('cardinalidades incompatibles')
sizes[variable] = size
variables = tuple(sizes)
out = np.zeros(tuple(sizes[v] for v in query))
for values in product(*(range(sizes[v]) for v in variables)):
state = dict(zip(variables, values))
if any(state[v] != x for v, x in evidence.items()):
continue
weight = np.prod([factor.values[tuple(state[v] for v in factor.scope)] for factor in factors])
out[tuple(state[v] for v in query)] += weight
if out.sum() <= 0:
raise ValueError('evidencia con peso cero')
return out/out.sum(), out.sum()The next example builds six synthetic conditional tables with a fixed seed, queries A and observes F=1. It compares elimination, complete enumeration and an einsum contraction with F reduced. NumPy prints the path so you can inspect intermediate factors; this estimates operations rather than measuring time.
import numpy as np
rng=np.random.default_rng(42)
def cpt(shape):
values=rng.uniform(.1,1.,size=shape)
return values/values.sum(axis=-1,keepdims=True)
factors=[Factor(('A',),cpt((2,))),Factor(('A','B'),cpt((2,2))),
Factor(('A','C'),cpt((2,2))),Factor(('B','C','D'),cpt((2,2,2))),
Factor(('C','E'),cpt((2,2))),Factor(('D','E','F'),cpt((2,2,2)))]
result,pe,order,width=variable_elimination(factors,('A',),{'F':1})
exact,p_exact=exhaustive(factors,('A',),{'F':1})
arrays=[f.values for f in factors]
expr='a,ab,ac,bcd,ce,de->a'
operands=arrays[:-1]+[arrays[-1][:,:,1]]
raw=np.einsum(expr,*operands,optimize='optimal')
assert np.allclose(result.values,exact) and np.isclose(pe,p_exact)
assert np.allclose(result.values,raw/raw.sum()) and np.isclose(pe,raw.sum())
path,details=np.einsum_path(expr,*operands,optimize='optimal')
print('posterior:',result.values,'P(F=1):',pe)
print('orden min-fill y anchura parcial:',order,width)
print('ruta einsum:',path)
print(details)The weight matches because the tables are normalized as a Bayesian network. For generic unnormalized factors, the same value is a sum of weights, not necessarily a probability. In larger networks, estimating operations and memory before materializing factors avoids exhausting resources.
Exercises
def min_fill_order(G):
return [], 0Step 1 of 3. How can each clause be represented?
import numpy as np
def query_einsum(pA,pB,pC,pD,pE,pF):
return None