Chapter 25 — Implementation: Learning Graphical Models in Practice
This notebook applies the chapter’s methods to four tasks:
From records to answers: learn a network’s graph and tables from records, then use it for diagnosis, and compare its answers with the true network’s.
A classifier with structure: naive Bayes against a tree-augmented naive Bayes (TAN) whose tree is learned by the Chow–Liu algorithm, on real medical data.
A hidden variable: a mixture model of handwritten digits learned by EM, where the hidden variable is the cluster.
Filling holes: the same mixture model imputes missing pixels.
import itertools, time
from math import log
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer, load_digits
from sklearn.model_selection import StratifiedKFold1. From Records to Answers¶
The learning code of the chapter, in compact form: sampling, counting with pseudo-counts, the BIC of one variable’s family, and hill climbing with random restarts.
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}}
IDX = {v: i for i, v in enumerate(VARS)}
def cfg_index(data, pa):
idx = np.zeros(len(data), int)
for u in pa: idx = idx * 2 + data[:, IDX[u]]
return idx
def sample(n, rng, parents=PARENTS, cpt=CPT):
data = np.zeros((n, len(VARS)), int)
for v in VARS:
p1 = np.array([cpt[v][c] for c in itertools.product([0, 1], repeat=len(parents[v]))])
data[:, IDX[v]] = rng.random(n) < p1[cfg_index(data, parents[v])]
return data
def fit(data, parents, alpha=0.5):
cpt = {}
for v, pa in parents.items():
pa = sorted(pa); idx = cfg_index(data, pa); k = 2 ** len(pa)
n1 = np.bincount(idx, weights=data[:, IDX[v]], minlength=k); n = np.bincount(idx, minlength=k)
cpt[v] = {c: (n1[i] + alpha) / (n[i] + 2 * alpha) for i, c in enumerate(itertools.product([0, 1], repeat=len(pa)))}
return {v: sorted(pa) for v, pa in parents.items()}, cpt
def family_bic(data, v, pa):
idx = cfg_index(data, pa); k = 2 ** len(pa)
n1 = np.bincount(idx, weights=data[:, IDX[v]], minlength=k); n = np.bincount(idx, minlength=k); n0 = n - n1
with np.errstate(divide='ignore', invalid='ignore'):
ll = np.nansum(n1 * np.log(n1 / n)) + np.nansum(n0 * np.log(n0 / n))
return ll - 0.5 * log(len(data)) * k
def acyclic(pa):
g = nx.DiGraph([(u, v) for v in pa for u in pa[v]]); g.add_nodes_from(VARS)
return nx.is_directed_acyclic_graph(g)
def hill_climb(data, start, max_parents=3, cache=None):
pa = {v: set(p) for v, p in start.items()}; cache = {} if cache is None else cache
def fs(v, p):
key = (v, frozenset(p))
if key not in cache: cache[key] = family_bic(data, v, sorted(p))
return cache[key]
while True:
best, move = 1e-9, None
for u, v in itertools.permutations(VARS, 2):
if u in pa[v]:
gain = fs(v, pa[v] - {u}) - fs(v, pa[v])
if gain > best: best, move = gain, ('delete', u, v)
if len(pa[u]) < max_parents:
gain2 = gain + fs(u, pa[u] | {v}) - fs(u, pa[u])
if gain2 > best:
pa[v].discard(u); pa[u].add(v)
if acyclic(pa): best, move = gain2, ('reverse', u, v)
pa[u].discard(v); pa[v].add(u)
elif len(pa[v]) < max_parents:
gain = fs(v, pa[v] | {u}) - fs(v, pa[v])
if gain > best:
pa[v].add(u)
if acyclic(pa): best, move = gain, ('add', u, v)
pa[v].discard(u)
if move is None: return pa, sum(fs(v, pa[v]) for v in VARS)
kind, u, v = move
if kind == 'add': pa[v].add(u)
elif kind == 'delete': pa[v].discard(u)
else: pa[v].discard(u); pa[u].add(v)
def learn_structure(data, restarts=20, seed=1):
rng, cache = np.random.default_rng(seed), {}
best, best_score = hill_climb(data, {v: set() for v in VARS}, cache=cache)
for _ in range(restarts):
order = list(rng.permutation(VARS)); start = {v: set() for v in VARS}
for i, v in enumerate(order):
start[v] = set([u for u in order[:i] if rng.random() < 0.25][:3])
g, s = hill_climb(data, start, cache=cache)
if s > best_score: best, best_score = g, s
return best
def query(q, evidence, parents, cpt):
"""P(q = 1 | evidence) by enumeration (8 variables: 256 rows)."""
num = den = 0.0
for vals in itertools.product([0, 1], repeat=len(VARS)):
x = dict(zip(VARS, vals))
if any(x[k] != v for k, v in evidence.items()): continue
p = 1.0
for v in VARS:
p1 = cpt[v][tuple(x[u] for u in parents[v])]
p *= p1 if x[v] else 1 - p1
den += p; num += p * x[q]
return num / denWe learn a network from 20 000 records, the structure first and then the tables with , and ask it the questions a doctor would ask.
records = sample(20_000, np.random.default_rng(20_005))
t0 = time.time()
graph = learn_structure(records)
learned_parents, learned_cpt = fit(records, graph)
print(f'learned in {time.time() - t0:.1f} s; edges:', sorted(f'{u}->{v}' for v in graph for u in graph[v]))
QUERIES = [('L', {'X': 1, 'D': 1}, 'lung cancer | X-ray, dyspnoea'),
('T', {'X': 1, 'D': 1, 'A': 1}, 'tuberculosis | X-ray, dyspnoea, Asia'),
('B', {'D': 1, 'S': 1}, 'bronchitis | dyspnoea, smoker'),
('L', {'S': 1}, 'lung cancer | smoker'),
('T', {'A': 1}, 'tuberculosis | Asia')]
print(f"\n{'question':<38} {'true network':>13} {'learned':>9}")
for q, ev, label in QUERIES:
print(f'{label:<38} {query(q, ev, PARENTS, CPT):>13.4f} {query(q, ev, learned_parents, learned_cpt):>9.4f}')
asia = records[:, IDX['A']] == 1
print(f"\nrecords with a visit to Asia: {asia.sum()}, of which with tuberculosis: {records[asia, IDX['T']].sum()}")learned in 0.3 s; edges: ['A->T', 'B->D', 'E->D', 'E->X', 'L->E', 'L->S', 'S->B', 'T->E']
question true network learned
lung cancer | X-ray, dyspnoea 0.6213 0.6201
tuberculosis | X-ray, dyspnoea, Asia 0.3917 0.4571
bronchitis | dyspnoea, smoker 0.8802 0.8789
lung cancer | smoker 0.1000 0.0994
tuberculosis | Asia 0.0500 0.0637
records with a visit to Asia: 211, of which with tuberculosis: 13
The learned graph is the true one with one edge reversed (L → S), an equivalent graph. On the questions about lung cancer and bronchitis the learned network answers within 0.002 of the true one. On tuberculosis it is off: 0.457 instead of 0.392 given the symptoms and a visit to Asia, 0.064 instead of 0.05 given the visit alone. Those answers depend on , which is estimated from only the records with a visit, and 13 tuberculosis cases among 211 visits give 0.064 (with ). A learned model is as good as the data on the question asked, and a rare condition needs many more records than the network’s size suggests.
2. A Classifier with Structure: Naive Bayes and TAN¶
Naive Bayes is a network with one edge from the class to each feature and no other edge: it assumes the features independent given the class. On real data they rarely are, and naive Bayes counts correlated evidence several times. TAN (tree-augmented naive Bayes, Friedman, Geiger and Goldszmidt, 1997) keeps the class edges and adds a tree among the features, learned by the Chow–Liu algorithm: weight each pair of features by their conditional mutual information given the class, and keep the maximum spanning tree. Among all trees, this one maximises the likelihood (Chow and Liu, 1968).
The data: 569 breast tumours, 30 measurements each, malignant or benign. Each measurement is made binary at its median on the training folds.
X, y = load_breast_cancer(return_X_y=True)
print(f'{X.shape[0]} tumours, {X.shape[1]} measurements; benign: {np.mean(y == 1):.0%}')
def cond_mutual_info(a, b, c, alpha=0.5):
"""I(a; b | c) for binary arrays, with pseudo-counts so that no cell is empty."""
total = 0.0
for k in (0, 1):
m = c == k
t = np.array([[np.sum((a[m] == i) & (b[m] == j)) for j in (0, 1)] for i in (0, 1)], float) + alpha
t /= t.sum()
total += m.mean() * np.sum(t * np.log(t / (t.sum(1, keepdims=True) * t.sum(0, keepdims=True))))
return total
def naive_bayes_fit(Xb, y, alpha=1):
prior = (np.bincount(y, minlength=2) + alpha) / (len(y) + 2 * alpha)
p = np.array([(Xb[y == c].sum(0) + alpha) / ((y == c).sum() + 2 * alpha) for c in (0, 1)]) # P(feature = 1 | class)
return prior, p
def naive_bayes_log_posterior(model, Xb):
prior, p = model
lp = np.log(prior)[None] + Xb @ np.log(p).T + (1 - Xb) @ np.log(1 - p).T
return lp - np.logaddexp(lp[:, :1], lp[:, 1:])
def tan_fit(Xb, y, alpha=1):
d = Xb.shape[1]; W = np.zeros((d, d))
for i, j in itertools.combinations(range(d), 2):
W[i, j] = W[j, i] = cond_mutual_info(Xb[:, i], Xb[:, j], y)
tree = nx.maximum_spanning_tree(nx.from_numpy_array(W)) # Chow-Liu
parent = {0: None} | {v: u for u, v in nx.bfs_edges(tree, 0)} # direct the tree away from feature 0
prior = (np.bincount(y, minlength=2) + alpha) / (len(y) + 2 * alpha)
table = {}
for i, u in parent.items():
for c, pv in itertools.product((0, 1), (0, 1) if u is not None else (0,)):
m = (y == c) & ((Xb[:, u] == pv) if u is not None else True)
table[i, c, pv] = (Xb[m, i].sum() + alpha) / (m.sum() + 2 * alpha)
return prior, parent, table
def tan_log_posterior(model, Xb):
prior, parent, table = model
lp = np.tile(np.log(prior), (len(Xb), 1))
for i, u in parent.items():
pv = Xb[:, u] if u is not None else np.zeros(len(Xb), int)
for c in (0, 1):
p1 = np.where(pv == 1, table.get((i, c, 1), 0.5), table[i, c, 0])
lp[:, c] += np.log(np.where(Xb[:, i] == 1, p1, 1 - p1))
return lp - np.logaddexp(lp[:, :1], lp[:, 1:])
scores = {'naive Bayes': [], 'TAN': []}
for train, test in StratifiedKFold(5, shuffle=True, random_state=0).split(X, y):
median = np.median(X[train], axis=0)
Xtr, Xte = (X[train] > median).astype(int), (X[test] > median).astype(int)
for name, fit_c, post in [('naive Bayes', naive_bayes_fit, naive_bayes_log_posterior), ('TAN', tan_fit, tan_log_posterior)]:
L = post(fit_c(Xtr, y[train]), Xte)
scores[name].append(((L.argmax(1) == y[test]).mean(), -L[np.arange(len(test)), y[test]].mean(), np.exp(L.max(1)).mean()))
print(f"\n{'5-fold cross-validation':<24} {'accuracy':>9} {'log-loss':>9} {'mean confidence':>16}")
for name, s in scores.items():
s = np.array(s); print(f'{name:<24} {s[:, 0].mean():>9.3f} {s[:, 1].mean():>9.3f} {s[:, 2].mean():>16.3f}')569 tumours, 30 measurements; benign: 63%
5-fold cross-validation accuracy log-loss mean confidence
naive Bayes 0.919 0.868 0.992
TAN 0.937 0.211 0.962
TAN is more accurate (0.937 against 0.919), but the larger difference is in the probabilities. Naive Bayes’s mean confidence in its answer is 0.992 while it is right 91.9% of the time: because radius, perimeter and area say nearly the same thing, it multiplies the same evidence in three times and becomes almost certain. Its log-loss, which punishes confident mistakes, is 0.868; TAN’s is 0.211, with a mean confidence of 0.962 for 93.7% right. When the probabilities are used (to rank patients, to set a threshold, to combine with costs), this matters more than accuracy.
Source
Xb = (X > np.median(X, axis=0)).astype(int); names = load_breast_cancer().feature_names
model = tan_fit(Xb, y); parent = model[1]
T = nx.Graph([(names[u], names[v]) for v, u in parent.items() if u is not None])
fig, ax = plt.subplots(figsize=(12, 7))
nx.draw_networkx(T, nx.kamada_kawai_layout(T), ax=ax, node_size=320, node_color='#dbe9ee', edge_color='#999999', font_size=8)
ax.set_title('the Chow-Liu tree among the 30 measurements (all data); the class is a parent of every node'); ax.axis('off')
plt.tight_layout(); plt.show()
The tree links measurements of the same kind: radius, perimeter and area of a tumour are nearly the same information, and the tree makes each depend on another so that the classifier does not count it three times.
3. A Hidden Variable: Clustering Digits with EM¶
A mixture of Bernoullis is a network with one hidden parent (the cluster, values) and one child per pixel, each pixel independent given . The cluster is never observed, so the tables are learned by EM: the E-step computes each image’s posterior over clusters (its responsibilities), the M-step counts pixels weighted by them. The data: 1 797 handwritten digits, 8 × 8 pixels, made black and white.
digits, labels = load_digits(return_X_y=True)
B = (digits > 7).astype(float)
def mixture_em(B, K, iters=60, seed=0, observed=None):
"""EM for a mixture of Bernoullis; observed (same shape as B, 1 = seen) lets pixels be missing."""
rng = np.random.default_rng(seed); n, d = B.shape
M = np.ones_like(B) if observed is None else observed
weights, mu, history = np.full(K, 1 / K), rng.uniform(0.25, 0.75, (K, d)), []
for _ in range(iters):
lp = np.log(weights)[None] + (M * B) @ np.log(mu).T + (M * (1 - B)) @ np.log(1 - mu).T # missing pixels left out
ll = np.logaddexp.reduce(lp, axis=1); history.append(ll.sum())
R = np.exp(lp - ll[:, None]) # E-step: responsibilities
weights = R.sum(0) / n # M-step: weighted counts, alpha = 1
mu = (R.T @ (M * B) + 1) / (R.T @ M + 2)
return weights, mu, R, history
def purity(R, labels):
z = R.argmax(1)
return sum(np.bincount(labels[z == k]).max() for k in np.unique(z)) / len(labels)
runs = []
for seed in range(5):
w, mu, R, hist = mixture_em(B, 10, seed=seed)
runs.append((hist[-1], seed, mu, R))
print(f'start {seed}: final log-likelihood {hist[-1]:10.1f}, purity (share of images in their cluster\'s majority digit) {purity(R, labels):.3f}')
best_ll, best_seed, best_mu, best_R = max(runs, key=lambda r: r[0])
print(f'\nbest start by likelihood: {best_seed}')
z = best_R.argmax(1)
for k in range(10):
print(f'cluster {k}: {np.sum(z == k):>3} images; digits 0-9:', np.bincount(labels[z == k], minlength=10))start 0: final log-likelihood -35147.3, purity (share of images in their cluster's majority digit) 0.722
start 1: final log-likelihood -34811.4, purity (share of images in their cluster's majority digit) 0.710
start 2: final log-likelihood -34776.7, purity (share of images in their cluster's majority digit) 0.728
start 3: final log-likelihood -34834.6, purity (share of images in their cluster's majority digit) 0.770
start 4: final log-likelihood -35515.2, purity (share of images in their cluster's majority digit) 0.663
best start by likelihood: 2
cluster 0: 173 images; digits 0-9: [172 0 0 0 0 0 1 0 0 0]
cluster 1: 164 images; digits 0-9: [ 0 23 135 2 0 0 0 0 4 0]
cluster 2: 351 images; digits 0-9: [ 1 0 1 144 0 52 1 0 11 141]
cluster 3: 140 images; digits 0-9: [ 1 1 38 21 0 0 0 1 71 7]
cluster 4: 208 images; digits 0-9: [ 0 103 3 9 4 2 2 3 81 1]
cluster 5: 182 images; digits 0-9: [ 1 4 0 0 0 1 176 0 0 0]
cluster 6: 192 images; digits 0-9: [ 0 0 0 7 9 1 0 168 0 7]
cluster 7: 133 images; digits 0-9: [ 1 1 0 0 0 124 0 0 4 3]
cluster 8: 84 images; digits 0-9: [ 0 50 0 0 3 0 0 7 3 21]
cluster 9: 170 images; digits 0-9: [ 2 0 0 0 165 2 1 0 0 0]
The five starts end at five different log-likelihoods, from to : each is a local maximum, and EM from one start would have been a gamble. The best likelihood (start 2) is not the best agreement with the digit labels (start 3, purity 0.770 against 0.728): the likelihood measures how well the model describes the pixels, and the labels were never part of the data.
Source
order = np.argsort([-np.bincount(labels[best_R.argmax(1) == k], minlength=10).argmax() for k in range(10)])
fig, axes = plt.subplots(1, 10, figsize=(12, 1.8))
for ax, k in zip(axes, order[::-1]):
z = best_R.argmax(1) == k
ax.imshow(best_mu[k].reshape(8, 8), cmap='gray_r', vmin=0, vmax=1); ax.axis('off')
ax.set_title(f'mostly {np.bincount(labels[z], minlength=10).argmax()}\n{z.sum()} images', fontsize=8)
fig.suptitle('the 10 clusters of the best start: each picture is P(pixel = 1 | cluster)', fontsize=10, y=1.05)
plt.show()
The clusters are not the ten digits. Zeros, fours, sixes, sevens and fives each get a clean cluster; ones are split in two, the largest cluster mixes threes, nines and some fives (144, 141 and 52 of them), and no cluster is mostly nines. Nothing told EM that there are ten digits or what a digit is: it found ten groups of images whose pixels are similar, and a 3 and a 9 written in 8 × 8 pixels share most of theirs. Clustering finds structure in the data, not the structure we have in mind.
4. Filling Holes¶
The mixture handles missing pixels naturally: the E-step uses only the pixels that were seen, and a missing pixel is then predicted by averaging the clusters’ tables with the image’s responsibilities. We hide 20% of the pixels at random and compare with the simplest imputation, each pixel’s most frequent value.
hide = np.random.default_rng(3).random(B.shape) < 0.2
observed = (~hide).astype(float)
w, mu, R, _ = mixture_em(B, 10, seed=best_seed, observed=observed)
filled = (R @ mu) > 0.5 # P(pixel = 1 | the image's seen pixels)
majority = np.broadcast_to(((B * observed).sum(0) / observed.sum(0)) > 0.5, B.shape)
print(f'hidden pixels: {hide.sum()}')
print(f'filled by the mixture: {(filled[hide] == B[hide]).mean():.1%} correct; by each pixel\'s most frequent value: {(majority[hide] == B[hide]).mean():.1%} correct')hidden pixels: 23225
filled by the mixture: 86.9% correct; by each pixel's most frequent value: 79.2% correct
Source
fig, axes = plt.subplots(3, 8, figsize=(10, 4))
for j, i in enumerate(range(0, 8)):
shown = np.where(B[i][:, None] == 1, [0.0, 0.0, 0.0], [1.0, 1.0, 1.0]); shown[hide[i]] = [0.9, 0.6, 0.0]
axes[0, j].imshow(B[i].reshape(8, 8), cmap='gray_r', vmin=0, vmax=1)
axes[1, j].imshow(shown.reshape(8, 8, 3))
axes[2, j].imshow(np.where(hide[i], filled[i], B[i]).reshape(8, 8), cmap='gray_r', vmin=0, vmax=1)
for ax, t in zip(axes[:, 0], ['original', 'holes (orange)', 'filled']):
ax.set_ylabel(t, fontsize=9)
for ax in axes.ravel(): ax.set_xticks([]); ax.set_yticks([])
plt.tight_layout(); plt.show()
Using the image’s own seen pixels, the mixture fills 86.9% of the holes correctly, against 79.2% for each pixel’s most frequent value. The model has learned what digits look like, and the 80% of each image that is left says which kind of digit it is. This is EM’s E-step put to work: the same posterior that gave expected counts during learning now predicts the missing values.
Summary¶
A network learned from records (structure and tables) answers diagnostic queries close to the true network where the data are plentiful, and drifts where a configuration is rare.
Structure learning helps classifiers: a Chow–Liu tree among the features turns naive Bayes, which double-counts correlated measurements, into TAN, with better calibrated probabilities.
A hidden variable makes the likelihood multimodal; EM from several starts, keeping the best likelihood, is standard, and the best likelihood is not always the most useful clustering.
The same EM that learns with a hidden variable learns with missing values, and the learned model fills the holes.