Chapter 22 — Assignment Project: A Triage Assistant for a Clinic
Overview¶
A clinic wants a small assistant that, from a few questions at the reception desk, estimates how likely a patient is to have flu (to be seen by a doctor quickly, and kept away from other patients). Doctors want to understand why it says what it says, to ask it any question, and to use it even when some answers are missing.
You will build a Bayesian network from the clinic’s records, query it like a doctor would, let it choose the most useful next question, and compare it with the classifiers of Chapter 8.
Data. 4,000 simulated patient records (they are generated by the notebook; no real patient data is used). Each record has 8 yes/no variables: Winter (the visit is in winter), the confirmed diagnoses Flu, Cold, Allergy, and the symptoms Fever, Cough, Sneezing, Fatigue. The first 3,000 records are for training, the last 1,000 for testing.
The structure (agreed with the doctors):
| Part | Task | Points |
|---|---|---|
| A | Learn the tables from the records | 20 |
| B | Answer the doctors’ questions | 25 |
| C | Choose the next question | 20 |
| D | Compare with Chapter 8’s classifiers, with and without missing answers | 20 |
| E | Report for the clinic | 15 |
import itertools
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import BernoulliNB
from sklearn.metrics import roc_auc_score, log_loss
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')
STRUCTURE = {'Winter': [], 'Flu': ['Winter'], 'Cold': ['Winter'], 'Allergy': ['Winter'],
'Fever': ['Flu', 'Cold'], 'Cough': ['Flu', 'Cold'], 'Sneezing': ['Cold', 'Allergy'], 'Fatigue': ['Flu']}
def simulate_records(n=4000, seed=42):
"""The clinic's records (simulated). The tables used here are hidden from your model."""
hidden_tables = {
'Winter': {(): 0.3}, 'Flu': {(True,): 0.10, (False,): 0.02}, 'Cold': {(True,): 0.25, (False,): 0.10},
'Allergy': {(True,): 0.05, (False,): 0.20},
'Fever': {(True, True): 0.92, (True, False): 0.90, (False, True): 0.15, (False, False): 0.03},
'Cough': {(True, True): 0.95, (True, False): 0.80, (False, True): 0.70, (False, False): 0.05},
'Sneezing': {(True, True): 0.95, (True, False): 0.75, (False, True): 0.85, (False, False): 0.04},
'Fatigue': {(True,): 0.85, (False,): 0.12}}
rng = np.random.default_rng(seed)
rows = []
for _ in range(n):
r = {}
for v, parents in STRUCTURE.items():
r[v] = bool(rng.random() < hidden_tables[v][tuple(r[p] for p in parents)])
rows.append(r)
return pd.DataFrame(rows)
records = simulate_records()
train, test = records.iloc[:3000], records.iloc[3000:]
print(train.mean().round(3).to_dict())
train.head()Part A — Learn the Tables (20 points)¶
A1 (checked). Complete learn_network(df, structure, pseudo=1.0). For every variable and every combination of its parents’ values, estimate by counting, with Laplace smoothing:
. Return a dict name -> (parents, table) in the format of the lab, with tables keyed by tuples of parent values.
def learn_network(df, structure, pseudo=1.0):
raise NotImplementedError # TODO_toy = pd.DataFrame({'R': [True, True, False, False, False], 'G': [True, False, True, False, False]})
check('A1: a toy example with smoothing', lambda: (lambda n: np.isclose(n['R'][1][()], 3 / 7) and np.isclose(n['G'][1][(True,)], 2 / 4) and np.isclose(n['G'][1][(False,)], 2 / 5))(learn_network(_toy, {'R': [], 'G': ['R']})))
net = learn_network(train, STRUCTURE)
for v in ['Flu', 'Fever']:
print(v, {k: round(float(p), 3) for k, p in net[v][1].items()})A2. For the table of Fever, print how many training records support each entry. Which entries would you trust least, and why?
# TODOYour answer:
Part B — The Doctors’ Questions (25 points)¶
B1 (checked). Complete query(net, q, evidence), returning by enumeration (your lab function, adapted to this network format, is fine). If q is already in the evidence, return 1.0 or 0.0.
def prob(net, name, value, assignment):
parents, table = net[name]
p_true = table[tuple(assignment[p] for p in parents)]
return p_true if value else 1 - p_true
def query(net, q, evidence):
raise NotImplementedError # TODOcheck('B1: with no evidence, P(Flu) matches the data', lambda: abs(query(net, 'Flu', {}) - train['Flu'].mean()) < 0.01)
check('B1: a probability between 0 and 1 that rises with fever', lambda: 0 < query(net, 'Flu', {'Fever': False}) < query(net, 'Flu', {'Fever': True}) < 1)B2. Answer, in a table, the doctors’ questions: ; the same in winter; the same with sneezing; the same with fatigue. Then and . Explain each change in one sentence (which of the patterns of Section 22.3 is at work?).
# TODOYour explanations:
Part C — The Next Question (20 points)¶
At the desk, the assistant can ask one more question. The best one is the one that is expected to make it most certain about flu. Uncertainty is measured by the entropy (Chapter 8, decision trees).
C1 (checked). Complete expected_entropy(net, evidence, question): with , return
def entropy(p):
return 0.0 if p <= 0 or p >= 1 else -(p * np.log2(p) + (1 - p) * np.log2(1 - p))
def expected_entropy(net, evidence, question):
raise NotImplementedError # TODOcheck('C1: asking never increases the expected uncertainty', lambda: all(expected_entropy(net, {'Cough': True}, s) <= entropy(query(net, 'Flu', {'Cough': True})) + 1e-12 for s in ['Fever', 'Sneezing', 'Fatigue', 'Winter']))
check('C1: asking about a known answer changes nothing', lambda: np.isclose(expected_entropy(net, {'Cough': True, 'Fever': True}, 'Fever'), entropy(query(net, 'Flu', {'Cough': True, 'Fever': True}))))C2. A patient says they cough. Rank the four other questions (Fever, Sneezing, Fatigue, Winter) by expected entropy. Which should the receptionist ask? Then simulate a full interview: starting from {'Cough': True}, repeatedly ask the best remaining question for the first test patient who has flu and coughs, using their real answers, and print the probability of flu after each answer.
# TODOPart D — Compared with Chapter 8’s Classifiers (20 points)¶
D1. On the 1,000 test patients, predict flu from the five things known at the desk (Winter, Fever, Cough, Sneezing, Fatigue) with: your network; Bernoulli Naive Bayes; and logistic regression (both trained on the same five columns of the training records). Report the AUC and the log loss of each.
# TODOD2. Patients often cannot say whether they have a fever (no thermometer at hand). Hide the Fever answer for a random half of the test patients (np.random.default_rng(0).random(1000) < 0.5). The network simply leaves it out of the evidence; for logistic regression, fill it in with the training mean. Compare the AUCs.
# TODOYour observations:
Part E — Report for the Clinic (15 points)¶
Write 250–350 words for the clinic’s doctors and managers:
What the assistant is (in plain words) and what it was built from.
How well it works (test results), and what it does better than a standard classifier.
One example of its reasoning a doctor would find sensible, and one that surprised you.
Its limits: simulated data, the structure fixed by hand, rare combinations, and what must be checked before any real use (validation on real patients, approval, the doctor stays responsible).
Your report:
Grading Rubric¶
| Part | Full marks if… |
|---|---|
| A (20) | tables learnt correctly (checked); unreliable entries identified with their counts |
| B (25) | queries correct (checked); every change explained with the right pattern (chain, fork, collider) |
| C (20) | expected entropy correct (checked); questions ranked; an interview simulated |
| D (20) | a fair comparison on AUC and log loss; missing answers handled properly; an honest discussion |
| E (15) | clear, accurate, honest about the limits and the doctor’s role |