Chapter 24 — Assignment Project: Inference When Enumeration Is Impossible
Overview¶
A monitoring system is modelled by a Bayesian network of 40 binary variables (alarms, sensors, faults), generated below. Enumerating its 240 assignments is out of the question. You will compute exact answers by variable elimination, then compare three approximate methods against them, and recommend one.
| Part | Task | Points |
|---|---|---|
| A | Exact answers and the cost of an order | 20 |
| B | Likelihood weighting | 20 |
| C | Gibbs sampling | 25 |
| D | Accuracy against time | 20 |
| E | Recommendation | 15 |
import itertools, time
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
PARENTS, CPT = {}, {}
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
NET_P, NET_C = random_network(40, 3, seed=11)
ORDER = list(NET_P) # a topological order
QUERIES = [('v35', {'v2': 1, 'v30': 1}), ('v12', {'v38': 0, 'v39': 1}), ('v20', {'v0': 1, 'v25': 0, 'v36': 1})]
print(sum(len(v) for v in NET_P.values()), 'edges; queries:', QUERIES)Part A — Exact Answers and the Cost of an Order (20 points)¶
Compute the three queries exactly with variable elimination, using a min-degree order. Report the answers, the largest factor and the time.
For the first query, also try the topological order and the reverse topological order. Explain the differences in cost.
# Your code hereYour explanation:
Part B — Likelihood Weighting (20 points)¶
Implement likelihood weighting for this network and estimate the three queries with 1 000, 10 000 and 50 000 samples. Report the absolute errors against Part A, and the effective number of samples for each query.
# Your code herePart C — Gibbs Sampling (25 points)¶
Implement Gibbs sampling for this network (resample every non-evidence variable from its Markov blanket, in each sweep). For the first query, run three chains of 5 000 sweeps from random starts, with 500 sweeps of burn-in. Plot their running estimates against the exact answer, and report each chain’s final error.
# Your code herePart D — Accuracy Against Time (20 points)¶
For the three queries, give each method about the same time budget (for example 3 seconds): how large is each one’s error? Present a table, and explain the differences.
# Your code hereYour table and explanation:
Part E — Recommendation (15 points)¶
The monitoring team will run thousands of such queries a day, on networks of 40 to 200 variables. Which method would you recommend, under which conditions would you switch, and how would they check, in production, that the answers are trustworthy?
Grading Rubric¶
| Criterion | Excellent | Adequate | Insufficient |
|---|---|---|---|
| A (20) | exact answers; the cost of orders explained with factor sizes | answers only | missing |
| B (20) | errors and effective samples, interpreted | errors only | missing |
| C (25) | three chains, plot, burn-in, agreement discussed | one chain | missing |
| D (20) | a fair comparison under the same budget, explained | numbers only | missing |
| E (15) | a justified choice with switching conditions and checks | generic | missing |