Chapter 24: Inference in Depth — Implementation
Checking variable elimination against enumeration on random networks
Elimination-order heuristics: min-degree against min-fill
Pruning: variables a query does not need
Belief propagation on a chain
How many samples is a Gibbs chain worth? Autocorrelation and effective sample size
import itertools, time
import numpy as np
import networkx as nx
PARENTS, CPT = {}, {} # every call below passes its own network
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)
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
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
def enumerate_query(q, evidence, parents, cpt):
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
print('library ready')library ready
1. Checking Against Enumeration¶
Any new inference code should be checked against brute force on networks small enough to enumerate: 12 variables, random structures and tables, random queries and evidence.
rng = np.random.default_rng(0); worst = 0.0
for trial in range(30):
par, cpt = random_network(12, 3, seed=100 + trial)
vs = list(par); q = vs[rng.integers(len(vs))]
ev = {v: int(rng.integers(2)) for v in rng.choice([u for u in vs if u != q], size=2, replace=False)}
dist, _ = variable_elimination(q, ev, [v for v in vs if v != q and v not in ev], par, cpt)
worst = max(worst, abs(dist[1] - enumerate_query(q, ev, par, cpt)))
print(f'30 random queries: largest difference from enumeration {worst:.2e}')30 random queries: largest difference from enumeration 1.22e-15
2. Min-Degree Against Min-Fill¶
Min-fill eliminates the variable whose elimination adds the fewest new edges between its neighbours; it is usually at least as good as min-degree. We compare the largest factor each builds, on random networks of 60 variables.
def moral_graph(parents):
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))
return M
def greedy_order(parents, skip, cost):
M = moral_graph(parents); order = []
while len(order) < len(parents) - len(skip):
v = min((u for u in M if u not in skip), key=lambda u: cost(M, u))
M.add_edges_from(itertools.combinations(M.neighbors(v), 2)); M.remove_node(v); order.append(v)
return order
degree = lambda M, u: M.degree(u)
fill = lambda M, u: sum(1 for a, b in itertools.combinations(M.neighbors(u), 2) if not M.has_edge(a, b))
print(f'{"network":<10}{"min-degree":>14}{"min-fill":>12}')
for seed in range(5):
par, cpt = random_network(60, 3, seed=seed)
skip = {'v59'}
sizes = [variable_elimination('v59', {}, greedy_order(par, skip, c), par, cpt)[1] for c in (degree, fill)]
print(f'seed {seed:<5}{sizes[0]:>14,}{sizes[1]:>12,}')network min-degree min-fill
seed 0 1,024 1,024
seed 1 1,024 1,024
seed 2 1,024 1,024
seed 3 1,024 1,024
seed 4 1,024 1,024
On these five networks the two heuristics find orders of the same cost: the largest factor has 1 024 entries every time, against millions for a topological order. They differ on other structures; libraries often try both and keep the better order.
3. Pruning What a Query Does Not Need¶
A variable that is not an ancestor of the query or of the evidence sums to 1 and can be removed before anything else (a barren node): its table contributes nothing. For a query near the roots of a large network, this removes most of it.
def prune(parents, cpt, query, evidence):
keep = {query, *evidence}
keep |= set().union(*(nx.ancestors(nx.DiGraph([(p, v) for v, ps in parents.items() for p in ps]), v) for v in list(keep) if any(v in ps or v == u for u, ps in parents.items())))
return {v: parents[v] for v in parents if v in keep}, {v: cpt[v] for v in parents if v in keep}
par, cpt = random_network(60, 3, seed=7)
query, ev = 'v10', {'v5': 1}
small_par, small_cpt = prune(par, cpt, query, ev)
for name, (P_, C_) in [('whole network', (par, cpt)), ('pruned', (small_par, small_cpt))]:
t0 = time.time(); d, big = variable_elimination(query, ev, greedy_order(P_, {query, *ev}, fill), P_, C_)
print(f'{name:<14} {len(P_):>3} variables, largest factor {big:>6}, {1000 * (time.time() - t0):6.1f} ms, P = {d[1]:.6f}')whole network 60 variables, largest factor 1024, 14.6 ms, P = 0.676416
pruned 5 variables, largest factor 4, 0.2 ms, P = 0.676416
4. Belief Propagation on a Chain¶
On a tree, exact inference passes one message per edge in each direction. On a chain with evidence on the last variable, the forward messages are the prior marginals and the backward messages carry the evidence back: this is the forward–backward algorithm of hidden Markov models (Chapter 26).
n = 30
rng = np.random.default_rng(3)
T = [rng.dirichlet([2, 2], size=2) for _ in range(n - 1)] # T[i][a, b] = P(X_{i+1} = b | X_i = a)
prior = np.array([0.6, 0.4]); evidence_last = 1
forward = [prior] # P(X_i), no evidence
for t in T: forward.append(forward[-1] @ t)
backward = [np.eye(2)[evidence_last]] # P(evidence | X_i)
for t in reversed(T): backward.insert(0, t @ backward[0])
posterior = [f * b / (f * b).sum() for f, b in zip(forward, backward)]
par = {f'x{i}': ([f'x{i - 1}'] if i else []) for i in range(n)}
cpt = {'x0': {(): prior[1]}} | {f'x{i + 1}': {(a,): T[i][a, 1] for a in (0, 1)} for i in range(n - 1)}
ve = variable_elimination('x10', {f'x{n - 1}': 1}, [v for v in par if v not in ('x10', f'x{n - 1}')], par, cpt)[0]
print(f'P(x10 = 1 | x29 = 1): belief propagation {posterior[10][1]:.6f}, variable elimination {ve[1]:.6f}')P(x10 = 1 | x29 = 1): belief propagation 0.310979, variable elimination 0.310979
Belief propagation computes the posterior of every variable with two passes, where variable elimination would be run once per variable. On graphs with cycles, the same message passing run anyway (loopy belief propagation) often gives good approximations, and underlies the decoding of modern error-correcting codes.
5. How Many Samples Is a Gibbs Chain Worth?¶
Successive Gibbs samples are correlated. The effective sample size (ESS) estimates how many independent samples they are worth: , with the autocorrelation at lag (summed until it becomes small).
def ess(x):
x = np.asarray(x, float); x = x - x.mean(); n = len(x)
acf = np.correlate(x, x, 'full')[n - 1:] / (x @ x)
s = 0.0
for k in range(1, n):
if acf[k] < 0.05: break
s += acf[k]
return n / (1 + 2 * s), acf
def gibbs_pair(n, rho, rng):
"""A 2-D Gaussian with correlation rho, sampled by Gibbs: x | y ~ N(rho y, 1 - rho²)."""
x = y = 0.0; xs = []
for _ in range(n):
x = rng.normal(rho * y, np.sqrt(1 - rho ** 2)); y = rng.normal(rho * x, np.sqrt(1 - rho ** 2)); xs.append(x)
return xs
for rho in [0.0, 0.9, 0.99]:
e, acf = ess(gibbs_pair(10_000, rho, np.random.default_rng(1)))
print(f'correlation {rho}: 10 000 Gibbs samples are worth about {e:,.0f} independent ones (lag-1 autocorrelation {acf[1]:.2f})')correlation 0.0: 10 000 Gibbs samples are worth about 10,000 independent ones (lag-1 autocorrelation -0.01)
correlation 0.9: 10 000 Gibbs samples are worth about 1,111 independent ones (lag-1 autocorrelation 0.80)
correlation 0.99: 10 000 Gibbs samples are worth about 90 independent ones (lag-1 autocorrelation 0.98)
Without correlation, every sample counts. With a correlation of 0.9 between the two variables, 10 000 Gibbs samples are worth about 1 100 independent ones; with 0.99, about 90: the chain crawls along the narrow ridge of the distribution, one small step at a time. Strongly dependent variables are where Gibbs sampling struggles, and where block updates or other MCMC methods (Hamiltonian Monte Carlo) are used.
Summary¶
Check exact inference against enumeration on small random networks before trusting it.
Min-fill and min-degree heuristics keep elimination tractable; neither is always best.
Pruning barren variables shrinks the problem before inference starts.
Belief propagation on trees computes every posterior in two passes; on a chain it is forward–backward.
Correlated MCMC samples are worth fewer independent ones: report the effective sample size.