Chapter 24: Inference in Depth
24.1 The Inference Problem¶
Inference answers questions such as : the probability of query variables given evidence, with every other variable summed out. Chapter 23 did it by building the whole joint table, rows: fine for 8 variables, hopeless for 50 (1015 rows). This chapter covers the two ways out: exact inference that never builds the joint, and approximate inference by sampling.
We use the Asia network of Chapter 23.
import itertools, time
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
VARS = ['A', 'S', 'T', 'L', 'B', 'E', 'X', 'D']
PARENTS = {'A': [], 'S': [], 'T': ['A'], 'L': ['S'], 'B': ['S'], 'E': ['T', 'L'], 'X': ['E'], 'D': ['E', 'B']}
CPT = {'A': {(): 0.01}, 'S': {(): 0.5}, 'T': {(1,): 0.05, (0,): 0.01}, 'L': {(1,): 0.10, (0,): 0.01}, 'B': {(1,): 0.60, (0,): 0.30},
'E': {(1, 1): 1.0, (1, 0): 1.0, (0, 1): 1.0, (0, 0): 0.0}, 'X': {(1,): 0.98, (0,): 0.05},
'D': {(1, 1): 0.90, (1, 0): 0.70, (0, 1): 0.80, (0, 0): 0.10}}
def enumerate_query(q, evidence, parents=PARENTS, cpt=CPT):
"""P(q = 1 | evidence) by summing the full joint: the baseline."""
vs = list(parents); num = den = 0.0
for vals in itertools.product([0, 1], repeat=len(vs)):
x = dict(zip(vs, vals))
if any(x[k] != v for k, v in evidence.items()): continue
p = np.prod([cpt[v][tuple(x[u] for u in parents[v])] if x[v] else 1 - cpt[v][tuple(x[u] for u in parents[v])] for v in vs])
den += p; num += p * x[q]
return num / den
EVIDENCE = {'X': 1, 'D': 1}
print(f'P(lung cancer | X-ray, dyspnoea) = {enumerate_query("L", EVIDENCE):.4f} (by enumerating 256 rows)')P(lung cancer | X-ray, dyspnoea) = 0.6213 (by enumerating 256 rows)
24.2 Factors¶
A factor is a table of non-negative numbers over some variables: a CPT is a factor over a variable and its parents; evidence makes smaller factors. Three operations are enough for exact inference:
product : a factor over the union of their variables, multiplying matching entries;
sum-out : remove a variable by adding over its values;
reduction : keep only the entries consistent with evidence.
With NumPy, a factor is an array with one axis per variable, and np.einsum does products and sums in one call.
class Factor:
def __init__(self, vars, table):
self.vars, self.table = list(vars), np.asarray(table, float)
def __mul__(self, other):
vs = self.vars + [v for v in other.vars if v not in self.vars]
letters = {v: chr(97 + i) for i, v in enumerate(vs)}
spec = f"{''.join(letters[v] for v in self.vars)},{''.join(letters[v] for v in other.vars)}->{''.join(letters[v] for v in vs)}"
return Factor(vs, np.einsum(spec, self.table, other.table))
def sum_out(self, var):
i = self.vars.index(var)
return Factor(self.vars[:i] + self.vars[i + 1:], self.table.sum(axis=i))
def reduce(self, var, value):
if var not in self.vars: return self
i = self.vars.index(var)
return Factor(self.vars[:i] + self.vars[i + 1:], np.take(self.table, value, axis=i))
def cpt_factor(v, parents=PARENTS, cpt=CPT):
"""The CPT of v as a factor over (parents..., v)."""
ps = parents[v]; t = np.zeros([2] * (len(ps) + 1))
for vals in itertools.product([0, 1], repeat=len(ps)):
p1 = cpt[v][vals]; t[vals + (1,)] = p1; t[vals + (0,)] = 1 - p1
return Factor(ps + [v], t)
f = cpt_factor('E') * cpt_factor('L')
print('φ(T, L, E) · φ(S, L) has variables', f.vars, 'and shape', f.table.shape)φ(T, L, E) · φ(S, L) has variables ['T', 'L', 'E', 'S'] and shape (2, 2, 2, 2)
24.3 Variable Elimination¶
Instead of building the joint and summing it, push the sums inside the product. For each variable to eliminate, in some order: multiply only the factors that mention it, sum it out, and put the result back. At the end, multiply what is left and normalise.
def variable_elimination(query, evidence, order, parents=PARENTS, cpt=CPT):
"""P(query | evidence); returns the distribution and the size of the largest factor built."""
factors = [cpt_factor(v, parents, cpt) for v in parents]
for var, val in evidence.items():
factors = [f.reduce(var, val) for f in factors]
largest = 0
for var in order:
if var == query or var in evidence: continue
involved = [f for f in factors if var in f.vars]
factors = [f for f in factors if var not in f.vars]
prod = involved[0]
for f in involved[1:]: prod = prod * f
largest = max(largest, prod.table.size)
factors.append(prod.sum_out(var))
result = factors[0]
for f in factors[1:]: result = result * f
return result.table / result.table.sum(), largest
dist, largest = variable_elimination('L', EVIDENCE, order=['A', 'T', 'S', 'B', 'E'])
print(f'P(lung cancer | X-ray, dyspnoea) = {dist[1]:.4f} by variable elimination; largest factor {largest} entries')P(lung cancer | X-ray, dyspnoea) = 0.6213 by variable elimination; largest factor 8 entries
The same answer as enumeration, 0.6213, and the largest table built has 8 entries instead of 256. A patient with a positive X-ray and dyspnoea has a 62% chance of lung cancer.
The order decides the cost. Eliminating a variable creates a factor over all its current neighbours; a bad order creates huge factors. On a small network it barely matters, so we build a larger one: 40 binary variables, each with up to 3 parents among earlier ones, random tables. Enumeration would need rows.
def random_network(n, max_parents, seed):
rng = np.random.default_rng(seed); names = [f'v{i}' for i in range(n)]
parents = {v: sorted(rng.choice(names[:i], size=min(i, rng.integers(0, max_parents + 1)), replace=False).tolist()) if i else [] for i, v in enumerate(names)}
cpt = {v: {vals: float(rng.uniform(.05, .95)) for vals in itertools.product([0, 1], repeat=len(ps))} for v, ps in parents.items()}
return parents, cpt
def min_degree_order(parents, skip):
"""Greedy: repeatedly eliminate the variable with the fewest neighbours in the moral graph."""
M = nx.Graph(); M.add_nodes_from(parents)
for v, ps in parents.items():
M.add_edges_from((p, v) for p in ps); M.add_edges_from(itertools.combinations(ps, 2)) # moralise: marry co-parents
order = []
while len(order) < len(parents) - len(skip):
v = min((u for u in M if u not in skip), key=M.degree)
M.add_edges_from(itertools.combinations(M.neighbors(v), 2)); M.remove_node(v); order.append(v)
return order
par40, cpt40 = random_network(40, 3, seed=4)
query, ev = 'v39', {'v0': 1, 'v20': 0}
skip = {query, *ev}
results = {}
for name, order in [('min-degree', min_degree_order(par40, skip)), ('topological', [v for v in par40 if v not in skip]), ('reverse topological', [v for v in reversed(list(par40)) if v not in skip])]:
t0 = time.time(); dist, largest = variable_elimination(query, ev, order, par40, cpt40)
results[name] = dist[1]
print(f'{name:<20} largest factor {largest:>12,} entries {1000 * (time.time() - t0):7.0f} ms P(v39 = 1 | evidence) = {dist[1]:.6f}')min-degree largest factor 256 entries 1 ms P(v39 = 1 | evidence) = 0.524537
topological largest factor 4,194,304 entries 450 ms P(v39 = 1 | evidence) = 0.524537
reverse topological largest factor 2,048 entries 2 ms P(v39 = 1 | evidence) = 0.524537
All three orders give the same answer, as they must. But eliminating in topological order builds a factor of more than 4 million entries and takes a third of a second; the min-degree heuristic never builds one larger than 256 and takes a millisecond. On bigger networks the gap becomes the difference between seconds and never. Finding the best order is itself NP-hard, so greedy heuristics (min-degree, min-fill) are used.
The size of the largest factor of the best order is governed by the graph’s treewidth. Networks shaped like trees (and polytrees: no undirected cycles) have treewidth 1 and are solved in linear time by belief propagation, which passes messages along edges; general networks are turned into a tree of clusters (the junction tree algorithm), and exact inference is exponential in their treewidth. Exact inference is NP-hard in general (Cooper, 1990): for large, densely connected networks we must approximate.
24.4 Sampling¶
Draw many complete assignments from the network, then count. Three methods, on a query whose evidence is rare: the probability of tuberculosis for a patient who visited Asia, has a positive X-ray and dyspnoea.
Q, EV = 'T', {'A': 1, 'X': 1, 'D': 1}
exact = enumerate_query(Q, EV)
p_ev = sum(np.prod([CPT[v][tuple(x[u] for u in PARENTS[v])] if x[v] else 1 - CPT[v][tuple(x[u] for u in PARENTS[v])] for v in VARS])
for vals in itertools.product([0, 1], repeat=8) for x in [dict(zip(VARS, vals))] if all(x[k] == val for k, val in EV.items()))
print(f'exact P(T = 1 | A, X, D) = {exact:.4f}; the evidence itself has probability {p_ev:.5f}')
def ancestral(rng, fixed=None):
"""One sample in topological order; with fixed, evidence variables are set instead of sampled, and the weight is returned."""
x, w = {}, 1.0
for v in VARS:
p1 = CPT[v][tuple(x[u] for u in PARENTS[v])]
if fixed and v in fixed:
x[v] = fixed[v]; w *= p1 if fixed[v] else 1 - p1
else:
x[v] = int(rng.random() < p1)
return x, w
def rejection(n, rng):
"""Keep only samples that agree with the evidence."""
hits = kept = 0
for _ in range(n):
x, _ = ancestral(rng)
if all(x[k] == v for k, v in EV.items()):
kept += 1; hits += x[Q]
return hits / kept if kept else float('nan'), kept
def likelihood_weighting(n, rng):
"""Fix the evidence, sample the rest, weight each sample by how likely its evidence is."""
num = den = 0.0
for _ in range(n):
x, w = ancestral(rng, EV); num += w * x[Q]; den += w
return num / denexact P(T = 1 | A, X, D) = 0.3917; the evidence itself has probability 0.00099
Rejection sampling throws away every sample that disagrees with the evidence: here almost all of them. Likelihood weighting never wastes a sample: it fixes the evidence and gives each sample a weight, the probability of the evidence given its sampled parents.
rng = np.random.default_rng(0)
for n in [1_000, 10_000, 100_000]:
est, kept = rejection(n, rng)
print(f'{n:>7} samples: rejection keeps {kept:>4}, estimate {est:.4f}; likelihood weighting {likelihood_weighting(n, rng):.4f} (exact {exact:.4f})') 1000 samples: rejection keeps 0, estimate nan; likelihood weighting 0.3774 (exact 0.3917)
10000 samples: rejection keeps 9, estimate 0.1111; likelihood weighting 0.3971 (exact 0.3917)
100000 samples: rejection keeps 99, estimate 0.3535; likelihood weighting 0.3909 (exact 0.3917)
The evidence has probability 0.00099: of 100 000 samples, rejection sampling keeps 99, and with 10 000 only 9, giving 0.11 against the exact 0.39. Likelihood weighting uses every sample, and is within 0.001 of the answer with 100 000. Its weakness appears when much evidence sits downstream, far from the roots: a few samples then carry nearly all the weight.
24.5 Gibbs Sampling¶
Gibbs sampling is a Markov chain Monte Carlo (MCMC) method. Start from any assignment consistent with the evidence; repeatedly pick a non-evidence variable and resample it from its distribution given all the others, which depends only on its Markov blanket (Chapter 23):
After a burn-in, the states visited are (dependent) samples from the posterior. Gibbs sampling scales to models with thousands of variables, where nothing else does.
CHILDREN = {v: [c for c in VARS if v in PARENTS[c]] for v in VARS}
def gibbs(n_sweeps, rng, cpt=CPT, burn_in=500, start=None):
"""Sweeps over the non-evidence variables; returns the running estimate of P(Q = 1 | EV) after burn-in."""
x = {v: 0 for v in VARS} if start is None else dict(start); x.update(EV)
free = [v for v in VARS if v not in EV]; trace = []
for sweep in range(n_sweeps):
for v in free:
w = []
for val in (0, 1):
x[v] = val; p = 1.0
for u in [v] + CHILDREN[v]:
p1 = cpt[u][tuple(x[k] for k in PARENTS[u])]; p *= p1 if x[u] else 1 - p1
w.append(p)
x[v] = int(rng.random() < w[1] / (w[0] + w[1])) if w[0] + w[1] > 0 else x[v]
trace.append(x[Q])
return np.cumsum(trace[burn_in:]) / np.arange(1, n_sweeps - burn_in + 1), trace
est, trace = gibbs(20_500, np.random.default_rng(1))
print(f'Gibbs, 20 000 sweeps after 500 of burn-in: {est[-1]:.4f} (exact {exact:.4f})')Gibbs, 20 000 sweeps after 500 of burn-in: 0.0000 (exact 0.3917)
The answer is 0.0000, against the exact 0.3917. Something is badly wrong, and nothing in the output says so.
When Gibbs fails. Gibbs changes one variable at a time, so a deterministic relation can split the states into regions the chain cannot cross. Here E is “T or L”. With E = 0, T and L must both be 0, and resampling either keeps it at 0; with E = 1, setting both T and L to 0 is impossible. So a chain that starts with E = 0 stays in that region for ever, and one that starts with E = 1 never leaves it: neither visits the whole posterior.
stuck_start = {v: 0 for v in VARS}; stuck_start.update({'T': 1, 'L': 0, 'E': 1})
fixed_start = {v: 0 for v in VARS}; fixed_start.update({'T': 0, 'L': 1, 'E': 1})
for name, start in [('all zeros (E = 0)', None), ('tuberculosis (E = 1)', stuck_start), ('lung cancer (E = 1)', fixed_start)]:
est_s, trace_s = gibbs(5_500, np.random.default_rng(2), start=start)
print(f'chain started from {name:<22}: estimate {est_s[-1]:.4f}')
print(f'exact: {exact:.4f}; exact within the E = 1 region, P(T = 1 | A, X, D, E = 1): {enumerate_query(Q, {**EV, "E": 1}):.4f}')chain started from all zeros (E = 0) : estimate 0.0000
chain started from tuberculosis (E = 1) : estimate 0.5130
chain started from lung cancer (E = 1) : estimate 0.5130
exact: 0.3917; exact within the E = 1 region, P(T = 1 | A, X, D, E = 1): 0.4814
The chain started from all zeros (E = 0) never leaves T = 0 and answers 0. The chains started with E = 1 both answer 0.5130, close to the probability of tuberculosis within the E = 1 region, 0.4814 (5 000 correlated sweeps do not pin it down more precisely). The true answer, 0.3917, mixes the two regions, and no single chain can find it.
A softened network, where E is “T or L” with probability 0.99 (and 0.01 otherwise), lets the chain move:
SOFT = {**CPT, 'E': {(1, 1): 0.99, (1, 0): 0.99, (0, 1): 0.99, (0, 0): 0.01}}
exact_soft = enumerate_query(Q, EV, PARENTS, SOFT)
runs = [gibbs(20_500, np.random.default_rng(s), cpt=SOFT, start=st)[0] for s, st in [(3, stuck_start), (4, fixed_start), (5, None)]]
print(f'exact (softened network) {exact_soft:.4f}; three chains from different starts: {[round(r[-1], 4) for r in runs]}')exact (softened network) 0.3658; three chains from different starts: [np.float64(0.3696), np.float64(0.3568), np.float64(0.3646)]
Source
fig, ax = plt.subplots(figsize=(9, 3.4))
for r, lab in zip(runs, ['start: tuberculosis', 'start: lung cancer', 'start: all zeros']):
ax.plot(r, label=lab)
ax.axhline(exact_soft, color='k', ls='--', label='exact'); ax.set_xscale('log'); ax.set_ylim(0, 1)
ax.set_xlabel('sweeps after burn-in'); ax.set_ylabel('running estimate of P(T = 1 | A, X, D)'); ax.legend(); plt.tight_layout(); plt.show()
With E only nearly deterministic, the chains cross between the regions; the three, started from different states, end at 0.370, 0.357 and 0.365, around the exact 0.366, though the plot shows how slowly they settle in their first hundreds of sweeps.
Diagnosing MCMC. Run several chains from different starts and check that they agree (the Gelman–Rubin statistic formalises this); discard a burn-in; watch the running estimates settle; and remember that successive samples are correlated, so 20 000 sweeps are worth fewer independent samples.
24.6 Choosing a Method¶
| Method | Exact? | Cost | Good when |
|---|---|---|---|
| Enumeration | yes | tiny networks, checking other methods | |
| Variable elimination | yes | exponential in the treewidth | small or tree-like networks |
| Belief propagation, junction tree | yes | linear on trees, exponential in the treewidth otherwise | trees, sparse networks, many queries |
| Rejection sampling | no | wastes samples on unlikely evidence | evidence that is not rare |
| Likelihood weighting | no | weights degenerate with much downstream evidence | evidence near the roots, moderate size |
| Gibbs sampling (MCMC) | no | needs burn-in, mixes slowly with strong dependences | large networks; no determinism |
24.7 Summary¶
Inference sums the joint over unobserved variables; building the joint is exponential.
Factors and three operations (product, sum-out, reduction) support exact inference.
Variable elimination pushes sums inside products; the elimination order decides the size of the factors, bounded below by the treewidth.
Rejection sampling wastes samples on rare evidence; likelihood weighting fixes the evidence and weights samples.
Gibbs sampling resamples each variable from its Markov blanket; it needs burn-in and several chains, and fails with deterministic relations.
Exercises¶
Write the factors of the Asia network for the query . Which can be dropped before eliminating anything? (Hint: variables that are not ancestors of the query or evidence.)
Eliminate the variables of the chain to compute , by hand. What is the largest factor? Which order would be bad?
Moralise the Asia network. What is its treewidth?
With 1 000 000 samples, about how many does rejection sampling keep for the evidence ? Why does likelihood weighting not have this problem?
Write the Gibbs update for in the Asia network: which factors does it involve?
Two Gibbs chains give 0.12 and 0.31 after 10 000 sweeps. What do you conclude, and what do you do?
Further Reading¶
D. Koller, N. Friedman, Probabilistic Graphical Models, MIT Press, 2009, Chapters 9–12.
S. Russell, P. Norvig, Artificial Intelligence: A Modern Approach, 4th ed., 2020, Chapter 13.
G. Cooper, “The computational complexity of probabilistic inference using Bayesian belief networks”, Artificial Intelligence, 1990.
S. Geman, D. Geman, “Stochastic relaxation, Gibbs distributions, and the Bayesian restoration of images”, IEEE PAMI, 1984.
A. Gelman, D. Rubin, “Inference from iterative simulation using multiple sequences”, Statistical Science, 1992.