Chapter 24 — Lab: Inference in Depth
Lab Overview¶
You will build exact inference from factors, then three samplers, and check every one against enumeration on the Asia network.
| Exercise | Topic | Points |
|---|---|---|
| 1 | Factor product | 15 |
| 2 | Summing a variable out | 10 |
| 3 | Reducing by evidence | 10 |
| 4 | Variable elimination | 20 |
| 5 | Rejection sampling | 10 |
| 6 | A likelihood weight | 15 |
| 7 | The Gibbs conditional | 20 |
| Challenge | Effective sample size | +10 |
How it works. A factor is a pair (vars, table): a list of variable names and a NumPy array with one axis of size 2 per variable, in the same order. Complete each function where you see # TODO and run the check cell under it. Do not change the check cells.
import itertools
import numpy as np
def check(name, test):
"""Run one self-check: test() must return True; any exception or False is reported."""
try:
ok = test()
except NotImplementedError:
print(f'❌ {name}: not implemented yet'); return
except Exception as e:
print(f'❌ {name}: {type(e).__name__}: {e}'); return
print(f'✅ {name}' if ok else f'❌ {name}: wrong result')
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 exact(q, ev):
num = den = 0.0
for vals in itertools.product([0, 1], repeat=8):
x = dict(zip(VARS, vals))
if any(x[k] != v for k, v in ev.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 VARS])
den += p; num += p * x[q]
return num / den
def cpt_factor(v):
ps = PARENTS[v]; t = np.zeros([2] * (len(ps) + 1))
for vals in itertools.product([0, 1], repeat=len(ps)):
t[vals + (1,)] = CPT[v][vals]; t[vals + (0,)] = 1 - CPT[v][vals]
return (ps + [v], t)
print('Setup complete')Exercise 1: Factor Product (15 points)¶
product(f, g): the result’s variables are those of f, followed by those of g not in f; each entry is the product of the matching entries of f and g. (One way: loop over all assignments of the result; another: np.einsum.)
def product(f, g):
# TODO
raise NotImplementedErrorf, g = (['a', 'b'], np.array([[1., 2.], [3., 4.]])), (['b', 'c'], np.array([[5., 6.], [7., 8.]]))
pv, pt = product(f, g)
check('variables a, b, c', lambda: pv == ['a', 'b', 'c'])
check('entry (a=1, b=0, c=1) = 3 × 6', lambda: pt[1, 0, 1] == 18)
check('the CPTs of T and E multiply to a factor over A, T, L, E', lambda: product(cpt_factor('T'), cpt_factor('E'))[0] == ['A', 'T', 'L', 'E'])def sum_out(f, var):
# TODO
raise NotImplementedErrorsv, st = sum_out((pv, pt), 'b')
check('removes b', lambda: sv == ['a', 'c'])
check('(a=0, c=0) = 1·5 + 2·7 = 19', lambda: st[0, 0] == 19)
check('summing a CPT over its own variable gives ones', lambda: np.allclose(sum_out(cpt_factor('D'), 'D')[1], 1))Exercise 3: Reducing by Evidence (10 points)¶
reduce(f, var, value) keeps only the entries with var = value, and removes var. A factor without var is returned unchanged.
def reduce(f, var, value):
# TODO
raise NotImplementedErrorrv, rt = reduce(f, 'a', 1)
check('a = 1 keeps the row [3, 4]', lambda: rv == ['b'] and np.allclose(rt, [3, 4]))
check('a factor without the variable is unchanged', lambda: reduce(g, 'a', 0) is g)Exercise 4: Variable Elimination (20 points)¶
ve(query, evidence, order): start from the CPT factors of all variables; reduce them by the evidence; for each variable in order, multiply the factors that contain it and sum it out; finally multiply the remaining factors and normalise. Return .
def ve(query, evidence, order):
# TODO
raise NotImplementedErrorcheck('P(L | X, D) matches enumeration', lambda: np.isclose(ve('L', {'X': 1, 'D': 1}, ['A', 'T', 'S', 'B', 'E']), exact('L', {'X': 1, 'D': 1})))
check('another order, the same answer', lambda: np.isclose(ve('L', {'X': 1, 'D': 1}, ['E', 'B', 'S', 'T', 'A']), exact('L', {'X': 1, 'D': 1})))
check('P(T | A, X) with a third order', lambda: np.isclose(ve('T', {'A': 1, 'X': 1}, ['S', 'L', 'B', 'D', 'E']), exact('T', {'A': 1, 'X': 1})))Exercise 5: Rejection Sampling (10 points)¶
rejection(q, ev, n, rng): draw n samples in the order of VARS (each variable with rng.random() < P(1 | parents)), keep those consistent with ev, and return the share of kept samples with q = 1 (or nan if none is kept).
def rejection(q, ev, n, rng):
# TODO
raise NotImplementedErrorcheck('P(L | S = 1) within 0.02 of the exact 0.1 with 20 000 samples', lambda: abs(rejection('L', {'S': 1}, 20_000, np.random.default_rng(0)) - 0.1) < 0.02)
check('impossible evidence returns nan', lambda: np.isnan(rejection('L', {'E': 0, 'L': 1}, 500, np.random.default_rng(1))))Exercise 6: A Likelihood Weight (15 points)¶
lw_sample(ev, rng): sample in the order of VARS, but set evidence variables to their values instead of sampling them, multiplying the weight by . Return (x, weight).
def lw_sample(ev, rng):
# TODO
raise NotImplementedErrorx, w = lw_sample({'A': 1, 'X': 1}, np.random.default_rng(2))
check('the evidence is set', lambda: x['A'] == 1 and x['X'] == 1)
check('the weight is P(A = 1) × P(X = 1 | E)', lambda: np.isclose(w, 0.01 * (0.98 if x['E'] else 0.05)))
def lw_est():
rng = np.random.default_rng(3); num = den = 0.0
for _ in range(20_000):
x, w = lw_sample({'A': 1, 'X': 1, 'D': 1}, rng); num += w * x['T']; den += w
return abs(num / den - exact('T', {'A': 1, 'X': 1, 'D': 1})) < 0.03
check('weighted estimate of P(T | A, X, D) within 0.03', lw_est)Exercise 7: The Gibbs Conditional (20 points)¶
gibbs_conditional(v, x): the probability that v = 1 given all other variables in x, computed from v’s own CPT and its children’s CPTs only:
CHILDREN = {v: [c for c in VARS if v in PARENTS[c]] for v in VARS}
def gibbs_conditional(v, x):
# TODO
raise NotImplementedErrorstate = dict(A=0, S=1, T=0, L=1, B=1, E=1, X=1, D=1)
check('B given its blanket matches the exact conditional', lambda: np.isclose(gibbs_conditional('B', state), exact('B', {k: v for k, v in state.items() if k != 'B'})))
check('S given its blanket matches the exact conditional', lambda: np.isclose(gibbs_conditional('S', state), exact('S', {k: v for k, v in state.items() if k != 'S'})))
check('T is forced to 1 when E = 1 and L = 0', lambda: gibbs_conditional('T', {**state, 'L': 0}) == 1.0)Challenge: Effective Sample Size (+10 points)¶
ess(x): , summing the autocorrelations of the centred series while they are at least 0.05.
def ess(x):
# TODO
raise NotImplementedErrorrng = np.random.default_rng(4)
check('independent samples: ESS close to n', lambda: 9_000 < ess(rng.normal(size=10_000)) <= 10_000 * 1.05)
def ar1():
x = np.zeros(20_000)
for t in range(1, len(x)): x[t] = 0.9 * x[t - 1] + rng.normal()
return 500 < ess(x) < 1_600
check('a strongly correlated series: ESS about n / 19', ar1)Lab Report¶
Submit this notebook with:
every check cell showing ✅,
one paragraph: with the evidence A = 1, X = 1, D = 1, about how many of 1 000 000 samples would your rejection sampler keep? Why does the likelihood weighting of Exercise 6 not waste samples, and when does it struggle?