Chapter 25 — Assignment Project: Learning a Triage Network from Records
Overview¶
An emergency department wants a Bayesian network over ten yes/no variables of its patients, to estimate risks at triage. A senior doctor drew a graph (the expert graph, below); the department also has records. You will learn the tables, test the expert’s graph against one learned from the records, learn from records with holes, and see how much data each step needs.
The records are simulated from a network that plays the role of reality. Its code is in the setup cell (_reality): do not use it before Part D, where you compare your learned graphs with it.
| Part | Task | Points |
|---|---|---|
| A | Tables for the expert graph, and the strength of the prior | 20 |
| B | A learned graph against the expert’s | 25 |
| C | Records with holes: EM against complete cases | 20 |
| D | How much data the structure needs | 20 |
| E | Recommendation | 15 |
import itertools, time
from math import log
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
VARS = ['Old', 'Smoker', 'Infection', 'Pneumonia', 'HeartDisease', 'Fever', 'Cough', 'LowOxygen', 'ChestPain', 'Admitted']
IDX = {v: i for i, v in enumerate(VARS)}
EXPERT = {'Old': [], 'Smoker': [], 'Infection': [], 'Pneumonia': ['Old', 'Smoker', 'Infection'], 'HeartDisease': ['Old', 'Smoker'],
'Fever': ['Infection', 'Pneumonia'], 'Cough': ['Pneumonia'], 'LowOxygen': ['Pneumonia'], 'ChestPain': ['HeartDisease'],
'Admitted': ['Old', 'LowOxygen', 'ChestPain']}
def _reality():
parents = {'Old': [], 'Smoker': [], 'Infection': [], 'Pneumonia': ['Old', 'Smoker', 'Infection'], 'HeartDisease': ['Old', 'Smoker'],
'Fever': ['Infection', 'Pneumonia'], 'Cough': ['Smoker', 'Pneumonia'], 'LowOxygen': ['Pneumonia', 'HeartDisease'],
'ChestPain': ['HeartDisease'], 'Admitted': ['LowOxygen', 'ChestPain']}
tables = {'Old': [0.30], 'Smoker': [0.25], 'Infection': [0.15],
'Pneumonia': [0.02, 0.25, 0.05, 0.35, 0.06, 0.45, 0.10, 0.55], 'HeartDisease': [0.03, 0.08, 0.15, 0.30],
'Fever': [0.05, 0.60, 0.70, 0.90], 'Cough': [0.10, 0.75, 0.40, 0.85], 'LowOxygen': [0.03, 0.25, 0.40, 0.65],
'ChestPain': [0.10, 0.55], 'Admitted': [0.08, 0.35, 0.70, 0.85]}
cpt = {v: dict(zip(itertools.product([0, 1], repeat=len(parents[v])), t)) for v, t in tables.items()}
return parents, cpt
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, seed):
parents, cpt = _reality(); rng = np.random.default_rng(seed); data = np.zeros((n, len(VARS)), int)
for v in VARS:
p1 = np.array([cpt[v][u] for u in itertools.product([0, 1], repeat=len(parents[v]))])
data[:, IDX[v]] = rng.random(n) < p1[cfg_index(data, parents[v])]
return data
TRAIN, VALID, TEST = _sample(3000, 1), _sample(2000, 2), _sample(5000, 3)
MORE = _sample(20_000, 4) # for Part D only
def fit(data, parents, alpha):
"""Tables with pseudo-counts alpha (alpha = 0: maximum likelihood; an unseen configuration gets 0.5)."""
cpt = {}
for v, pa in parents.items():
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] = {u: (n1[i] + alpha) / (n[i] + 2 * alpha) if n[i] + 2 * alpha > 0 else 0.5
for i, u in enumerate(itertools.product([0, 1], repeat=len(pa)))}
return cpt
def loglik(data, parents, cpt):
"""Average log-likelihood per record (-inf if a record has probability 0)."""
ll = 0.0
for v, pa in parents.items():
p1 = np.array([cpt[v][u] for u in itertools.product([0, 1], repeat=len(pa))])[cfg_index(data, pa)]
with np.errstate(divide='ignore'):
ll += np.log(np.where(data[:, IDX[v]] == 1, p1, 1 - p1)).sum()
return ll / len(data)
def family_bic(data, v, pa):
idx = cfg_index(data, list(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
print(f'records: train {len(TRAIN)}, validation {len(VALID)}, test {len(TEST)}')
print('share of patients with each condition:', {v: round(float(TRAIN[:, IDX[v]].mean()), 3) for v in VARS})Part A — Tables for the Expert Graph, and the Strength of the Prior (20 points)¶
Fit the expert graph’s tables on the first 300 training records with and report each one’s validation log-likelihood. Which is best?
Repeat with all 3 000 training records. How does the best , and the difference it makes, change? Explain.
# Your code hereYour explanation:
Part B — A Learned Graph against the Expert’s (25 points)¶
Learn a graph from the 3 000 training records by hill climbing on the BIC (add, delete and reverse moves, at most 3 parents), with at least 10 random restarts. (You may adapt the chapter’s code.)
Fit both graphs’ tables with the chosen in Part A, and compare their validation log-likelihoods and their BIC on the training records.
List the edges in which the two graphs differ (taking an edge’s reversal as a match), and for each say whether the records support the expert or not: compare the BIC of the expert graph with and without that edge.
# Your code hereYour comparison:
Part C — Records with Holes: EM against Complete Cases (20 points)¶
In the department’s real records, two values are often missing: Pneumonia (the X-ray is not always done) and LowOxygen (the oximeter reading is not always written down). The cell below makes the training records with holes: Pneumonia is missing in 40% of records at random; LowOxygen is missing in 50% of the records without fever and 10% of those with fever.
Which kind of missingness is each (MCAR, MAR, MNAR)? Why?
Fit the true structure’s graph (use
_reality()[0]here: this part is about the tables) by (a) complete-case analysis and (b) EM. Report the test log-likelihood of each, and and , compared with the full records.Explain any bias you find in the complete-case tables.
HOLES = TRAIN.copy(); rng = np.random.default_rng(5)
HOLES[rng.random(len(HOLES)) < 0.4, IDX['Pneumonia']] = -1
HOLES[rng.random(len(HOLES)) < np.where(TRAIN[:, IDX['Fever']] == 1, 0.1, 0.5), IDX['LowOxygen']] = -1
print('missing: Pneumonia', round(float((HOLES[:, IDX['Pneumonia']] < 0).mean()), 3), ' LowOxygen', round(float((HOLES[:, IDX['LowOxygen']] < 0).mean()), 3),
' complete records', int((HOLES >= 0).all(1).sum()))# Your code hereYour answers:
Part D — How Much Data the Structure Needs (20 points)¶
Now compare with reality. Learn a graph from 300, 1 000, 3 000 and 20 000 records (use MORE for the last), and for each report: the skeleton edges right, missed and extra against _reality()[0], whether the v-structures match, and the test log-likelihood (tables with ). Which true edges are found last, and why those?
# Your code hereYour answer:
Part E — Recommendation (15 points)¶
Write a short recommendation (half a page) to the department: should they use the expert’s graph, a learned graph, or a combination? How should they handle the missing X-rays and oximeter readings, and what should they change in how records are kept? Support each point with your numbers.
Grading Rubric¶
| Criterion | Excellent | Adequate | Insufficient |
|---|---|---|---|
| A (20) | the validation curve at both sizes, with the change in the best explained | numbers only | missing |
| B (25) | a learned graph with restarts; both compared on held-out data; each disputed edge tested | a learned graph only | missing |
| C (20) | missingness classified correctly; EM and complete cases compared; the bias explained | one method | missing |
| D (20) | four sizes compared with reality; the late edges explained by their strength or rarity | some sizes | missing |
| E (15) | a recommendation grounded in the numbers | generic | missing |