Module contents
Lesson 4 of 27Core 90 min

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 P(D∣T=1,S=1)P(D\given T=1,S=1), 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 ϕ(A,B)\phi(A,B) is a nonnegative table with one axis per variable. The product of ϕ(A,B)\phi(A,B) and ψ(B,C)\psi(B,C) has axes (A,B,C)(A,B,C) and value ϕ(a,b)ψ(b,c)\phi(a,b)\psi(b,c). Reduction by evidence B=b0B=b_0 selects a slice and removes axis BB. Marginalizing BB sums its values:

τ(A,C)=∑bϕ(A,b)ψ(b,C).\tau(A,C)=\sum_b\phi(A,b)\psi(b,C).

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 P(Q∣e)P(Q\given e), first reduce each factor using ee. Choose hidden variable ZZ, multiply all factors containing ZZ and sum ZZ 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 QQ.

Eliminating a variable is correct by distributivity: factors that do not contain ZZ 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.

InteractiveElimination step by step
DTP(D)P(T|D)P(S=1|D)
D=000.900.900.20
D=010.900.100.20
D=100.100.200.70
D=110.100.800.70

Synthetic model: D is disease, T test and S symptom; T and S are independent given D. Enumeration computes two products for each of eight configurations before filtering; fixing S multiplies four rows. Contributions over D are summed for each value of T. These are not measured timings.

Tables
Stagetables
P(T=1 | S=1)pending
Reduced-product multiplications0
Naive enumeration16 multiplications
Advance from tables to the posterior. Evidence fixes the symptom and disease is eliminated by summing over its values.

In this synthetic example P(D=1)=0.1P(D=1)=0.1, P(T=1∣D=1)=0.8P(T=1\given D=1)=0.8, P(T=1∣D=0)=0.1P(T=1\given D=0)=0.1, P(S=1∣D=1)=0.7P(S=1\given D=1)=0.7 and P(S=1∣D=0)=0.2P(S=1\given D=0)=0.2. Test and symptom are independent given D. Query TT with evidence S=1S=1: multiply the three reduced factors and sum out D. For T=1T=1, products of D=1D=1 and D=0D=0 are 0.0560.056 and 0.0180.018, summing to P(T=1,S=1)=0.074P(T=1,S=1)=0.074. For T=0T=0 we obtain 0.1760.176. Their sum is P(S=1)=0.25P(S=1)=0.25 and hence P(T=1∣S=1)=0.074/0.25=0.296P(T=1\given S=1)=0.074/0.25=0.296. 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 P(e)P(e).

A bucket that does reduce a chain

Consider A→B→CA\to B\to C with P(A=1)=0.3P(A=1)=0.3, P(B=1∣A=0)=0.2P(B=1\given A=0)=0.2, P(B=1∣A=1)=0.8P(B=1\given A=1)=0.8, P(C=1∣B=0)=0.1P(C=1\given B=0)=0.1 and P(C=1∣B=1)=0.9P(C=1\given B=1)=0.9. We want P(A∣C=1)P(A\given C=1). Reduction leaves ϕ(C=1∣B)\phi(C=1\given B) as a vector over B. To eliminate B, multiply that vector and P(B∣A)P(B\given A), then sum B:

g(A)=∑bP(B=b∣A)P(C=1∣B=b).g(A)=\sum_b P(B=b\given A)P(C=1\given B=b).

This yields g(0)=0.8(0.1)+0.2(0.9)=0.26g(0)=0.8(0.1)+0.2(0.9)=0.26 and g(1)=0.2(0.1)+0.8(0.9)=0.74g(1)=0.2(0.1)+0.8(0.9)=0.74. Multiplying by A’s prior gives weights 0.7(0.26)=0.1820.7(0.26)=0.182 and 0.3(0.74)=0.2220.3(0.74)=0.222. They sum to P(C=1)=0.404P(C=1)=0.404 and the result is P(A=1∣C=1)=0.222/0.404≈0.5495P(A=1\given C=1)=0.222/0.404\approx0.5495. There is no need to build the eight-entry table (A,B,C)(A,B,C).

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 g(A)g(A) summarizes all B possibilities for each retained A value.

The procedure also computes a multi-axis query. For example, P(A,C∣e)P(A,C\given e) 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.

InteractiveOrder matters exponentially
0123456

All nodes are binary. Dashed lines mark fill; size counts table entries before summing the variable, not measured memory.

Ordernone
Observed width0
Largest binary bucket table1
Last node neighbors0
Choose a graph and click nodes to eliminate them. Compare eliminating the center of a star first with the min-fill order.

With ww binary neighbors, the bucket product can have 2w+12^{w+1} entries before summing out the variable; the result has up to 2w2^w. With unequal cardinalities the actual cardinality product matters, not just ww. In a star with six leaves, eliminating the center first produces a bucket with 27=1282^7=128 entries and width six. Eliminating leaves first keeps width one. On a square n×nn\times n lattice, treewidth grows linearly with nn: 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 P(C∣A,B)P(C\given A,B) 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 nn Boolean variables and mm clauses, create an independent Bernoulli(1/2)(1/2) 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 XX. The network has polynomial size and

P(X=1)=#{asignaciones satisfactorias}2n.P(X=1)=\frac{\#\{\text{asignaciones satisfactorias}\}}{2^n}.

Thus deciding whether P(X=1)>0P(X=1)>0 decides satisfiability: a general polynomial solution would solve 3-SAT. Exact marginal computation also recovers the number of satisfying assignments by multiplying by 2n2^n, 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.

InteractiveMarginals, MPE and MAP differ
000
0.000
001
0.400
010
0.350
011
0.000
100
0.250
101
0.000
110
0.000
111
0.000

The table is a synthetic model supported on three states. Marginal MAP sums Z before maximizing over X,Y; MPE maximizes the full joint.

4.0
3.5
2.5
Marginal modes (X,Y,Z)000
Probability of that vector0.000
MPE of all three001
Marginal MAP of (X,Y)00
Adjust weights of three configurations and compare the mode vector, MPE and MAP of the X,Y pair.

With initial weights P(001)=0.4P(001)=0.4, P(010)=0.35P(010)=0.35 and P(100)=0.25P(100)=0.25, all three individual modes are zero, but P(000)=0P(000)=0. MPE is 001001. For MAP of (X,Y)(X,Y), sum Z: probabilities of 00,01,10,1100,01,10,11 are 0.4,0.35,0.25,00.4,0.35,0.25,0, and MAP is 0000. These are different queries and the last result has only two coordinates.

For marginal MAP, operator order matters. Generally max⁡x∑zf(x,z)≠∑zmax⁡xf(x,z)\max_x\sum_z f(x,z)\ne\sum_z\max_x f(x,z): for example with f=(1001)f=\begin{pmatrix}1&0\\0&1\end{pmatrix} 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 zz can choose a different xx before summing. On the left one xx must be chosen for all zz 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 P(e)=0P(e)=0, 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, τac=∑bϕabψbc\tau_{ac}=\sum_b\phi_{ab}\psi_{bc} 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.

[ ]Tabular factors and eliminationBrowser
"""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.

[ ]Compare elimination, enumeration and einsumBrowser
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 P(F=1)P(F=1) 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

CodeMin-fill order
Implement min_fill_order(G), where G is a dictionary mapping each node to its neighbors in a simple undirected graph. Return (order, width). At each step minimize (fill edges, degree, str(node)); connect neighbors and eliminate the node without modifying G.
def min_fill_order(G):
  return [], 0
Shift+Enter to run
ProofFrom 3-SAT to inference
Prove: Construct a network that decides whether a 3-SAT formula has a satisfying assignment.
0
The formula's Boolean variables are independent, equiprobable roots.

Step 1 of 3. How can each clause be represented?

Numeric
Eliminate a 4×4 grid row by row, left to right and top to bottom. What is the induced width of the complete order?
Quiz
The joint assigns 0.4 to 001, 0.35 to 010, 0.25 to 100 and zero to other configurations. What are the MPE and marginal-mode vector?
CodeSix-node query with einsum
Implement query_einsum(pA,pB,pC,pD,pE,pF), whose axes are A; A,B; A,C; B,C,D; C,E; D,E,F. Return normalized vector P(A|F=1) using a single np.einsum call and check that evidence has positive weight.
import numpy as np
def query_einsum(pA,pB,pC,pD,pE,pF):
  return None
Shift+Enter to run
Key idea
Exact inference exploits distributivity: elimination order controls factor size, while the query determines which variables are summed and which are maximized.