Chapter 25 — Lab: Learning Graphical Models
Lab Overview¶
You will learn the tables of the Asia network from records, score structures, and run EM on records with holes, checking each step against values computed independently.
| Exercise | Topic | Points |
|---|---|---|
| 1 | Counting a table | 15 |
| 2 | Pseudo-counts | 10 |
| 3 | Log-likelihood of records | 15 |
| 4 | Counting parameters | 10 |
| 5 | The BIC of a family | 15 |
| 6 | The E-step for one record | 20 |
| 7 | One EM iteration | 15 |
| Challenge | The Chow–Liu tree | +10 |
How it works. Records are a NumPy array with one row per record and one column per variable, in the order of VARS; a missing value is -1. A table is a dict from a tuple of parent values (in the order of the parents’ list) to . Complete each function where you see # TODO and run the check cell under it. Do not change the check cells.
import itertools
from math import log
import numpy as np
import networkx as nx
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']
IDX = {v: i for i, v in enumerate(VARS)}
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 sample(n, seed):
rng = np.random.default_rng(seed); data = np.zeros((n, 8), int)
for v in VARS:
p = np.array([CPT[v][tuple(r)] for r in data[:, [IDX[u] for u in PARENTS[v]]]]) if PARENTS[v] else np.full(n, CPT[v][()])
data[:, IDX[v]] = rng.random(n) < p
return data
DATA = sample(5000, 1)
TINY = np.array([[0, 1, 0, 1, 1, 1, 1, 1],
[0, 1, 0, 0, 1, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 1, 0],
[1, 0, 1, 0, 0, 1, 1, 1]])
print('Setup complete:', DATA.shape[0], 'records')Exercise 1: Counting a Table (15 points)¶
mle(data, v, pa) returns the maximum-likelihood table of v given the parents pa: for each tuple of parent values (all of them, in itertools.product([0, 1], repeat=len(pa)) order), . A configuration never seen gets 0.5.
def mle(data, v, pa):
# TODO
raise NotImplementedErrorcheck('TINY: P(D = 1 | E = 1, B = 1) = 1/1', lambda: mle(TINY, 'D', ['E', 'B'])[(1, 1)] == 1.0)
check('TINY: P(B = 1 | S = 1) = 2/3', lambda: np.isclose(mle(TINY, 'B', ['S'])[(1,)], 2 / 3))
check('TINY: P(T = 1 | A = 1) = 1/1', lambda: mle(TINY, 'T', ['A'])[(1,)] == 1.0)
check('a configuration never seen gets 0.5', lambda: mle(TINY[:2], 'T', ['A'])[(1,)] == 0.5)
check('DATA: P(B = 1 | S = 1) within 0.03 of the true 0.60', lambda: abs(mle(DATA, 'B', ['S'])[(1,)] - 0.6) < 0.03)Exercise 2: Pseudo-Counts (10 points)¶
smoothed(data, v, pa, alpha) is the same table with a Beta(, ) prior: . With alpha = 0 it must agree with mle (including 0.5 for an unseen configuration).
def smoothed(data, v, pa, alpha):
# TODO
raise NotImplementedErrorcheck('TINY, alpha = 1: P(B = 1 | S = 1) = (2 + 1) / (3 + 2)', lambda: np.isclose(smoothed(TINY, 'B', ['S'], 1)[(1,)], 0.6))
check('TINY, alpha = 1: unseen configuration gives 1/2', lambda: np.isclose(smoothed(TINY[:2], 'T', ['A'], 1)[(1,)], 0.5))
check('alpha = 0 agrees with mle', lambda: all(np.isclose(smoothed(DATA, 'D', ['E', 'B'], 0)[u], mle(DATA, 'D', ['E', 'B'])[u]) for u in itertools.product([0, 1], repeat=2)))
check('no entry is 0 or 1 with alpha = 0.5', lambda: all(0 < p < 1 for p in smoothed(DATA[:100], 'T', ['A'], 0.5).values()))Exercise 3: Log-Likelihood of Records (15 points)¶
loglik(data, parents, cpt) returns under the tables cpt. A probability of 0 gives -inf (that is expected; silence NumPy’s warning with np.errstate(divide='ignore')).
def loglik(data, parents, cpt):
# TODO
raise NotImplementedErrordef by_hand(row):
x = dict(zip(VARS, row)); s = 0.0
for v in VARS:
p1 = CPT[v][tuple(x[u] for u in PARENTS[v])]
s += log(p1 if x[v] else 1 - p1)
return s
check('one record: matches a direct product of 8 probabilities', lambda: np.isclose(loglik(TINY[:1], PARENTS, CPT), by_hand(TINY[0])))
check('TINY: the sum over the records', lambda: np.isclose(loglik(TINY[:4], PARENTS, CPT), sum(by_hand(r) for r in TINY[:4])))
check('a record that the tables call impossible gives -inf', lambda: loglik(np.array([[0, 0, 0, 0, 0, 1, 0, 0]]), PARENTS, CPT) == -np.inf)
check('learned tables fit their own records at least as well as the true ones', lambda: loglik(DATA, PARENTS, {v: mle(DATA, v, PARENTS[v]) for v in VARS}) >= loglik(DATA, PARENTS, CPT))Exercise 4: Counting Parameters (10 points)¶
n_params(parents) is the number of free parameters of a network of binary variables: one per parent configuration of each variable.
def n_params(parents):
# TODO
raise NotImplementedErrorcheck('the Asia network has 18', lambda: n_params(PARENTS) == 18)
check('8 variables with no edges have 8', lambda: n_params({v: [] for v in VARS}) == 8)
check('the complete graph on 8 variables has 255', lambda: n_params({v: VARS[:i] for i, v in enumerate(VARS)}) == 255)Exercise 5: The BIC of a Family (15 points)¶
family_bic(data, v, pa) is one variable’s term of the BIC: its maximum log-likelihood given the parents, (terms with are 0), minus , where is the number of records.
def family_bic(data, v, pa):
# TODO
raise NotImplementedErrorcheck('S with no parents on TINY: 3 log(3/5) + 2 log(2/5) - log(5)/2', lambda: np.isclose(family_bic(TINY, 'S', []), 3 * log(0.6) + 2 * log(0.4) - 0.5 * log(5)))
check('the sum over families is the log-likelihood of the MLE minus the penalty',
lambda: np.isclose(sum(family_bic(DATA, v, PARENTS[v]) for v in VARS),
loglik(DATA, PARENTS, {v: mle(DATA, v, PARENTS[v]) for v in VARS}) - 0.5 * log(len(DATA)) * n_params(PARENTS)))
check('the true parent of L beats no parent', lambda: family_bic(DATA, 'L', ['S']) > family_bic(DATA, 'L', []))
check('a useless extra parent of X loses', lambda: family_bic(DATA, 'X', ['E', 'A']) < family_bic(DATA, 'X', ['E']))Exercise 6: The E-Step for One Record (20 points)¶
completions(row, cpt) takes one record with -1 for its missing values and returns a list of pairs (completed_row, weight): one per way of filling the holes, with weight under the tables cpt of the Asia graph. The weights sum to 1. (Compute the joint probability of each completion, then normalise.)
def completions(row, cpt):
# TODO
raise NotImplementedErrordef 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
row = np.array([0, 1, 0, 0, -1, 0, 0, 1]) # bronchitis missing
c = lambda: completions(row, CPT)
check('a complete record has one completion, of weight 1', lambda: len(completions(TINY[0], CPT)) == 1 and np.isclose(completions(TINY[0], CPT)[0][1], 1))
check('one hole: two completions whose weights sum to 1', lambda: len(c()) == 2 and np.isclose(sum(w for _, w in c()), 1))
check('the weight of B = 1 is P(B = 1 | the other seven values)', lambda: np.isclose([w for r, w in c() if r[IDX['B']] == 1][0], exact('B', {v: row[IDX[v]] for v in VARS if v != 'B'})))
check('three holes: eight completions, impossible ones with weight 0',
lambda: len(completions(np.array([0, 1, -1, -1, 0, -1, 1, 1]), CPT)) == 8 and min(w for _, w in completions(np.array([0, 1, -1, -1, 0, -1, 1, 1]), CPT)) == 0)Exercise 7: One EM Iteration (15 points)¶
em_step(data, cpt, alpha=1.0) performs one iteration: replace every record by its completions (Exercise 6), then re-estimate every table from the weighted counts with pseudo-counts : . It returns the new tables.
def em_step(data, cpt, alpha=1.0):
# TODO
raise NotImplementedErrorholes = DATA[:1500].copy(); rng = np.random.default_rng(2)
holes[rng.random(len(holes)) < 0.3, IDX['B']] = -1
start = {v: {u: 0.5 for u in t} for v, t in CPT.items()}
memo = {}
def learned():
if 'c' not in memo:
c = start
for _ in range(25): c = em_step(holes, c)
memo['c'] = c
return memo['c']
check('with no holes, one step is counting with pseudo-counts', lambda: all(np.isclose(em_step(DATA[:300], CPT)[v][u], smoothed(DATA[:300], v, PARENTS[v], 1.0)[u]) for v in VARS for u in CPT[v]))
check('after 25 steps, P(B = 1 | S = 1) is within 0.05 of the true 0.60', lambda: abs(learned()['B'][(1,)] - 0.6) < 0.05)
check('the log-likelihood of the complete part rises from the start', lambda: loglik(holes[(holes >= 0).all(1)], PARENTS, learned()) > loglik(holes[(holes >= 0).all(1)], PARENTS, start))Challenge: The Chow–Liu Tree (+10 points)¶
chow_liu(data) returns the edges (as a set of frozensets of two names) of the maximum spanning tree of the 8 variables, each pair weighted by its empirical mutual information (terms with are 0). nx.maximum_spanning_tree does the second half.
def chow_liu(data):
# TODO
raise NotImplementedErrortree = lambda: chow_liu(sample(20_000, 3))
check('a tree: 7 edges joining all 8 variables', lambda: len(tree()) == 7 and nx.is_tree(nx.Graph([tuple(e) for e in tree()])))
check('it contains the strong edges E - X, L - E and S - B', lambda: {frozenset('EX'), frozenset('LE'), frozenset('SB')} <= tree())Lab Report¶
Submit this notebook with:
every check cell showing ✅,
one paragraph: why does Exercise 3’s last check hold for the maximum-likelihood tables, and why does that make the likelihood alone a bad score for choosing a structure?