Chapter 23 — Lab: Independence and d-Separation
Lab Overview¶
You will write the tools that read independence from a Bayesian network’s graph, and check one against the numbers.
| Exercise | Topic | Points |
|---|---|---|
| 1 | Chain, fork or collider? | 10 |
| 2 | The joint probability of one assignment | 15 |
| 3 | All trails between two nodes | 15 |
| 4 | Is a trail active? | 20 |
| 5 | d-separation | 10 |
| 6 | The Markov blanket | 10 |
| 7 | v-structures and Markov equivalence | 20 |
| Challenge | The back-door adjustment | +10 |
How it works. Each exercise has a function to complete where you see # TODO. Run the check cell under it: ✅ means your function is right, ❌ tells you what is wrong. Graphs are networkx.DiGraphs; you may use G.predecessors, G.successors, nx.descendants, but not nx.is_d_separator. Do not change the check cells.
import itertools
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')
PARENTS = {'A': [], 'S': [], 'T': ['A'], 'L': ['S'], 'B': ['S'], 'E': ['T', 'L'], 'X': ['E'], 'D': ['E', 'B']}
ASIA = nx.DiGraph([(p, v) for v, ps in PARENTS.items() for p in ps])
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}}
print('Setup complete: the Asia network,', ASIA.number_of_nodes(), 'nodes,', ASIA.number_of_edges(), 'edges')Exercise 1: Chain, Fork or Collider? (10 points)¶
connection(G, a, b, c): a, b, c are consecutive on a trail (a–b and b–c are edges in either direction). Return 'collider' if both edges point into b, 'fork' if both point out of b, and 'chain' otherwise.
def connection(G, a, b, c):
# TODO
raise NotImplementedErrorcheck('T → E ← L is a collider', lambda: connection(ASIA, 'T', 'E', 'L') == 'collider')
check('L ← S → B is a fork', lambda: connection(ASIA, 'L', 'S', 'B') == 'fork')
check('S → L → E and E ← L ← S are chains', lambda: connection(ASIA, 'S', 'L', 'E') == 'chain' == connection(ASIA, 'E', 'L', 'S'))Exercise 2: The Joint Probability of One Assignment (15 points)¶
joint(x): x is a dict giving 0 or 1 for every variable. Return using PARENTS and CPT (which store ).
def joint(x):
# TODO
raise NotImplementedErrorallx = [dict(zip(PARENTS, vals)) for vals in itertools.product([0, 1], repeat=8)]
check('all 256 assignments sum to 1', lambda: np.isclose(sum(joint(x) for x in allx), 1))
check('a healthy non-smoker who stayed home', lambda: np.isclose(joint(dict(A=0, S=0, T=0, L=0, B=0, E=0, X=0, D=0)), 0.99 * 0.5 * 0.99 * 0.99 * 0.7 * 1 * 0.95 * 0.9))
check('E = 0 with lung cancer is impossible', lambda: joint(dict(A=0, S=1, T=0, L=1, B=0, E=0, X=0, D=0)) == 0)Exercise 3: All Trails (15 points)¶
trails(G, x, y) returns every simple path between x and y in the graph ignoring directions, each as a list of nodes from x to y. (Hint: nx.all_simple_paths on G.to_undirected().)
def trails(G, x, y):
# TODO
raise NotImplementedErrorcheck('T to L: through E, and the long way round through D, B and S', lambda: sorted(map(tuple, trails(ASIA, 'T', 'L'))) == [('T', 'E', 'D', 'B', 'S', 'L'), ('T', 'E', 'L')])
check('A to D: two trails', lambda: sorted(map(tuple, trails(ASIA, 'A', 'D'))) == [('A', 'T', 'E', 'D'), ('A', 'T', 'E', 'L', 'S', 'B', 'D')])Exercise 4: Is a Trail Active? (20 points)¶
active(G, trail, Z): every consecutive triple must pass. A chain or fork passes if its middle node is not in Z; a collider passes if its middle node or one of its descendants is in Z. Use your connection.
def active(G, trail, Z):
# TODO
raise NotImplementedErrorcheck('a collider blocks without evidence', lambda: not active(ASIA, ['T', 'E', 'L'], []))
check('evidence on the collider opens it', lambda: active(ASIA, ['T', 'E', 'L'], ['E']))
check('evidence on a descendant opens it too', lambda: active(ASIA, ['T', 'E', 'L'], ['X']))
check('evidence on a chain node blocks', lambda: not active(ASIA, ['A', 'T', 'E', 'D'], ['T']))
check('the long trail A..D given E', lambda: active(ASIA, ['A', 'T', 'E', 'L', 'S', 'B', 'D'], ['E']) and not active(ASIA, ['A', 'T', 'E', 'L', 'S', 'B', 'D'], ['E', 'S']))Exercise 5: d-Separation (10 points)¶
d_sep(G, x, y, Z): True if no trail between x and y is active given Z.
def d_sep(G, x, y, Z=()):
# TODO
raise NotImplementedErrorcheck('agrees with networkx on every pair given up to two variables', lambda: all(
d_sep(ASIA, x, y, Z) == nx.is_d_separator(ASIA, {x}, {y}, set(Z))
for x, y in itertools.combinations(PARENTS, 2) for k in range(3) for Z in itertools.combinations([v for v in PARENTS if v not in (x, y)], k)))Exercise 6: The Markov Blanket (10 points)¶
markov_blanket(G, v): the parents, the children, and the children’s other parents of v, as a set without v.
def markov_blanket(G, v):
# TODO
raise NotImplementedErrorcheck('the blanket of L', lambda: markov_blanket(ASIA, 'L') == {'S', 'E', 'T'})
check('the blanket of B includes the co-parent E', lambda: markov_blanket(ASIA, 'B') == {'S', 'D', 'E'})
check('a node is d-separated from the rest by its blanket', lambda: all(d_sep(ASIA, 'E', u, sorted(markov_blanket(ASIA, 'E'))) for u in ['A', 'S']))Exercise 7: Markov Equivalence (20 points)¶
v_structures(G) returns the set of triples (a, c, b) with a < b (alphabetically), edges a → c ← b, and no edge between a and b. equivalent(G1, G2) is True if the two graphs have the same skeleton (undirected edges) and the same v-structures.
def v_structures(G):
# TODO
raise NotImplementedError
def equivalent(G1, G2):
# TODO
raise NotImplementedErrorcheck('Asia has two v-structures', lambda: v_structures(ASIA) == {('B', 'D', 'E'), ('L', 'E', 'T')})
check('a shielded collider is not a v-structure', lambda: v_structures(nx.DiGraph([('a', 'c'), ('b', 'c'), ('a', 'b')])) == set())
check('chain and fork are equivalent; the collider is not', lambda: equivalent(nx.DiGraph([('x', 'y'), ('y', 'z')]), nx.DiGraph([('y', 'x'), ('y', 'z')])) and not equivalent(nx.DiGraph([('x', 'y'), ('y', 'z')]), nx.DiGraph([('x', 'y'), ('z', 'y')])))
check('reversing S → L keeps Asia equivalent; reversing E → X does not', lambda: equivalent(ASIA, nx.DiGraph([(b, a) if (a, b) == ('S', 'L') else (a, b) for a, b in ASIA.edges])) and not equivalent(ASIA, nx.DiGraph([(b, a) if (a, b) == ('E', 'X') else (a, b) for a, b in ASIA.edges])))Challenge: The Back-Door Adjustment (+10 points)¶
adjusted(stats, t): stats maps (treatment, stratum) to (successes, patients). Return , where is the share of all patients (both treatments) in stratum .
def adjusted(stats, t):
# TODO
raise NotImplementedErrorSTONES = {('A', 'small'): (81, 87), ('A', 'large'): (192, 263), ('B', 'small'): (234, 270), ('B', 'large'): (55, 80)}
check('the kidney-stone study: A is better once size is adjusted for', lambda: np.isclose(adjusted(STONES, 'A'), 0.8325, atol=1e-3) and np.isclose(adjusted(STONES, 'B'), 0.7789, atol=1e-3))Lab Report¶
Submit this notebook with:
every check cell showing ✅,
one paragraph: a study of hospital patients finds that diabetes is less common among patients with a broken leg. Draw the graph that explains it, and say what the study should have done.