Chapter 22 — Lab: Probabilistic Graphical Models
Lab Overview¶
| Exercise | Topic | Points |
|---|---|---|
| 1 | Bayes’ rule | 10 |
| 2 | Joint probabilities in a Bayesian network | 15 |
| 3 | Inference by enumeration | 20 |
| 4 | Likelihood weighting | 15 |
| 5 | HMM filtering: the forward algorithm | 20 |
| 6 | The Viterbi algorithm | 20 |
| Challenge | Gibbs sampling | +10 |
Complete the code where you see # TODO, then run the check cell under it.
import itertools
import numpy as np
def check(name, test):
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')
# A Bayesian network over Boolean variables: name -> (parents, {tuple of parent values: P(name = True | parents)}).
# The dictionary lists the variables in a topological order (parents before children).
ALARM = {
'B': ([], {(): 0.001}),
'E': ([], {(): 0.002}),
'A': (['B', 'E'], {(True, True): 0.95, (True, False): 0.94, (False, True): 0.29, (False, False): 0.001}),
'J': (['A'], {(True,): 0.90, (False,): 0.05}),
'M': (['A'], {(True,): 0.70, (False,): 0.01}),
}
def prob(net, name, value, assignment):
"""P(name = value | the values of its parents in assignment)."""
parents, table = net[name]
p_true = table[tuple(assignment[p] for p in parents)]
return p_true if value else 1 - p_true
print('Setup complete.')Exercise 1: Bayes’ Rule (10 points)¶
Complete posterior(prior, sensitivity, false_positive_rate): the probability of having the condition after a positive test.
def posterior(prior, sensitivity, false_positive_rate):
raise NotImplementedError # TODOcheck('the chapter example: 15.4%', lambda: np.isclose(posterior(0.01, 0.90, 0.05), 0.1538, atol=1e-4))
check('chapter exercise 1: prevalence 10%', lambda: np.isclose(posterior(0.10, 0.90, 0.05), 0.09 / (0.09 + 0.045)))Question. The test’s quality is the same in both cases. Why is a positive result so much more convincing when the prevalence is 10%?
Your answer:
Exercise 2: Joint Probabilities (15 points)¶
Complete joint(net, assignment): the product of over all variables, for a complete assignment (a dict variable → bool). Use prob.
def joint(net, assignment):
raise NotImplementedError # TODOcheck('the chapter example: P(j, m, a, ¬b, ¬e) = 0.000628', lambda: np.isclose(joint(ALARM, dict(B=False, E=False, A=True, J=True, M=True)), 0.000628, atol=1e-6))
check('chapter exercise 3: P(¬j, m, a, b, ¬e)', lambda: np.isclose(joint(ALARM, dict(B=True, E=False, A=True, J=False, M=True)), 0.1 * 0.7 * 0.94 * 0.001 * 0.998))
check('the joint sums to 1', lambda: np.isclose(sum(joint(ALARM, dict(zip('BEAJM', v))) for v in itertools.product((True, False), repeat=5)), 1))Exercise 3: Enumeration (20 points)¶
Complete enumerate_query(net, query, evidence), returning : for each value of the query, sum joint over every combination of the hidden variables (those that are neither the query nor evidence), then normalise.
def enumerate_query(net, query, evidence):
raise NotImplementedError # TODOcheck('P(b | j, m) = 0.284', lambda: np.isclose(enumerate_query(ALARM, 'B', {'J': True, 'M': True}), 0.2842, atol=1e-4))
check('P(b | j) = 0.016', lambda: np.isclose(enumerate_query(ALARM, 'B', {'J': True}), 0.0163, atol=1e-4))
check('explaining away: P(b | a) > 0.3 but P(b | a, e) < 0.01', lambda: enumerate_query(ALARM, 'B', {'A': True}) > 0.3 and enumerate_query(ALARM, 'B', {'A': True, 'E': True}) < 0.01)Question. Use your function to answer: are JohnCalls and MaryCalls independent? Are they independent given Alarm? Show the numbers that prove it.
# TODOExercise 4: Likelihood Weighting (15 points)¶
Complete likelihood_weighting(net, query, evidence, n, rng): for each of n samples, go through the variables in order; fix each evidence variable and multiply the sample’s weight by its probability given the sampled parents; sample every other variable (rng.random() < prob(...)). Return the weighted fraction of samples in which the query is True.
def likelihood_weighting(net, query, evidence, n, rng):
raise NotImplementedError # TODOcheck('P(b | a) within 0.03 of the exact value', lambda: abs(likelihood_weighting(ALARM, 'B', {'A': True}, 200_000, np.random.default_rng(0)) - enumerate_query(ALARM, 'B', {'A': True})) < 0.03)
check('P(a | b) within 0.01 (evidence at the top: easy)', lambda: abs(likelihood_weighting(ALARM, 'A', {'B': True}, 20_000, np.random.default_rng(1)) - enumerate_query(ALARM, 'A', {'B': True})) < 0.01)Exercise 5: HMM Filtering (20 points)¶
The machine of the chapter: states 0 = OK, 1 = Worn; readings 0 = Low, 1 = High. Complete filter_hmm(obs, pi0, A, B), returning an array with for every : start with ; then predict with and weight by the evidence; normalise each (this avoids underflow on long sequences and gives the filtered probabilities directly).
PI0 = np.array([0.9, 0.1])
A = np.array([[0.90, 0.10], [0.05, 0.95]])
B = np.array([[0.8, 0.2], [0.3, 0.7]])
def filter_hmm(obs, pi0, A, B):
raise NotImplementedError # TODOcheck('the chapter example: 0.04, 0.35, 0.70', lambda: np.allclose(filter_hmm([0, 1, 1], PI0, A, B), [0.04, 0.351, 0.699], atol=1e-3))
check('chapter exercise 5: a fourth reading, Low', lambda: np.isclose(filter_hmm([0, 1, 1, 0], PI0, A, B)[-1], (lambda p: p[1] / p.sum())((np.array([0.301, 0.699]) @ A) * B[:, 0]), atol=2e-3))Exercise 6: The Viterbi Algorithm (20 points)¶
Complete viterbi(obs, pi0, A, B), returning the most likely state sequence as a list. Work with log probabilities: ; at each step, for every state keep and the that achieved it; then follow the back-pointers from the best final state.
def viterbi(obs, pi0, A, B):
raise NotImplementedError # TODOcheck('the chapter example: OK, Worn, Worn', lambda: viterbi([0, 1, 1], PI0, A, B) == [0, 1, 1])
def _brute(obs):
best = max(itertools.product((0, 1), repeat=len(obs)),
key=lambda xs: np.log(PI0[xs[0]]) + sum(np.log(A[a, b]) for a, b in zip(xs, xs[1:])) + sum(np.log(B[x, o]) for x, o in zip(xs, obs)))
return list(best)
check('chapter exercise 6, and agreement with brute force on 8 readings', lambda: viterbi([1, 1, 0], PI0, A, B) == _brute([1, 1, 0]) and viterbi([0, 0, 1, 0, 1, 1, 1, 0], PI0, A, B) == _brute([0, 0, 1, 0, 1, 1, 1, 0]))Question. On the readings Low, Low, High, Low, High, High, High, Low, compare the Viterbi path with the filtered probabilities. Why can the two disagree at some time steps?
# TODOYour answer:
Challenge: Gibbs Sampling (+10 points)¶
Complete gibbs(net, query, evidence, n, rng, burn_in): start from a random assignment of the hidden variables (evidence fixed); at each step pick the next hidden variable in turn and resample it from ; after burn_in steps, count how often the query is True.
def gibbs(net, query, evidence, n, rng, burn_in=1000):
raise NotImplementedError # TODOcheck('P(b | j, m) within 0.03 of 0.284', lambda: abs(gibbs(ALARM, 'B', {'J': True, 'M': True}, 100_000, np.random.default_rng(0)) - 0.2842) < 0.03)Lab Report¶
Submit this notebook with every check cell showing ✅ and your answers to the three questions.