Chapter 23: Independence and d-Separation — Implementation
A small Bayesian-network class: ancestral sampling and exact queries
Testing independence in data, and comparing with d-separation
Berkson’s paradox: conditioning on a collider creates a correlation
Simpson’s paradox: a common cause reverses a trend, and adjusting for it
Every independence a graph implies: the local Markov property
import itertools
import numpy as np
import networkx as nx
from scipy.stats import chi2_contingency
class BayesNet:
"""Binary variables; cpt[v] maps a tuple of parent values to P(v = 1 | parents)."""
def __init__(self, parents, cpt):
self.parents, self.cpt = parents, cpt
self.G = nx.DiGraph([(p, v) for v, ps in parents.items() for p in ps]); self.G.add_nodes_from(parents)
self.order = list(nx.topological_sort(self.G))
def sample(self, n, rng):
"""Ancestral sampling: each variable after its parents."""
data = {}
for v in self.order:
keys = list(zip(*[data[p] for p in self.parents[v]])) if self.parents[v] else [()] * n
p1 = np.array([self.cpt[v][k] for k in keys])
data[v] = (rng.random(n) < p1).astype(int)
return data
def joint(self):
vs = self.order; rows = np.array(list(itertools.product([0, 1], repeat=len(vs))))
p = np.ones(len(rows))
for j, v in enumerate(vs):
idx = [vs.index(u) for u in self.parents[v]]
p1 = np.array([self.cpt[v][tuple(r[idx])] for r in rows])
p *= np.where(rows[:, j] == 1, p1, 1 - p1)
return vs, rows, p
def prob(self, query, evidence={}):
vs, rows, p = self.joint()
m = lambda d: np.all([rows[:, vs.index(k)] == v for k, v in d.items()], axis=0) if d else np.ones(len(p), bool)
return p[m({**query, **evidence})].sum() / p[m(evidence)].sum()
ASIA = BayesNet({'A': [], 'S': [], 'T': ['A'], 'L': ['S'], 'B': ['S'], 'E': ['T', 'L'], 'X': ['E'], 'D': ['E', 'B']},
{'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}})
data = ASIA.sample(100_000, np.random.default_rng(0))
print(f'P(D = 1): exact {ASIA.prob({"D": 1}):.4f}, from 100 000 samples {data["D"].mean():.4f}')P(D = 1): exact 0.4360, from 100 000 samples 0.4354
2. Testing Independence in Data¶
With data instead of tables, independence must be tested. For : split the data by every value of , run a chi-squared test of independence on the table of each part, and add the statistics and degrees of freedom. A small p-value means the data contradict independence.
from scipy.stats import chi2
def ci_test(data, x, y, Z=()):
"""p-value of the chi-squared test of x ⫫ y | Z, pooled over the strata of Z."""
stat, dof = 0.0, 0
for zs in itertools.product([0, 1], repeat=len(Z)):
mask = np.all([data[z] == v for z, v in zip(Z, zs)], axis=0) if Z else np.ones(len(data[x]), bool)
table = np.array([[np.sum(mask & (data[x] == a) & (data[y] == b)) for b in (0, 1)] for a in (0, 1)])
if (table.sum(0) > 0).all() and (table.sum(1) > 0).all():
s, _, d, _ = chi2_contingency(table, correction=False); stat += s; dof += d
return 1.0 if dof == 0 else chi2.sf(stat, dof)
checks = [('S', 'E', ()), ('S', 'E', ('L',)), ('T', 'L', ()), ('T', 'L', ('E',)), ('A', 'D', ()), ('A', 'D', ('E',)), ('A', 'S', ())]
print(f'{"query":<22}{"d-separated":>12}{"p-value":>10}')
for x, y, Z in checks:
print(f'{x} ⫫ {y} | {{{",".join(Z)}}}'.ljust(22) + f'{str(nx.is_d_separator(ASIA.G, {x}, {y}, set(Z))):>12}{ci_test(data, x, y, Z):>10.3g}')query d-separated p-value
S ⫫ E | {} False 0
S ⫫ E | {L} True 0.0491
T ⫫ L | {} True 0.893
T ⫫ L | {E} False 0
A ⫫ D | {} False 0.391
A ⫫ D | {E} False 0.933
A ⫫ S | {} True 0.278
Where the graph says dependent and the dependence is strong (S and E; T and L given E), the p-values are 0. Two rows deserve a closer look. is a true independence, yet its p-value is 0.049: at the 5% level, a true independence is rejected one time in twenty, and this is such a time. and are dependent according to the graph, yet the test finds nothing (0.39, and 0.93 given E): visits to Asia are rare (1%) and their effect on dyspnoea passes through two uncertain links, so the dependence is real but far too weak to see in 100 000 patients. Tests can only fail to find a dependence; that is why structure learning from data (Chapter 25) is hard.
3. Berkson’s Paradox¶
A collider observed by selection: a scholarship goes to students who are either very talented or very hard-working. In the whole population, talent and effort are independent. Among scholarship holders they are negatively correlated, because a holder who lacks one must have the other.
rng = np.random.default_rng(1)
talent, effort = rng.normal(size=10_000), rng.normal(size=10_000)
selected = (talent + effort) > 1.5 # the collider: admitted on talent + effort
print(f'correlation in the population: {np.corrcoef(talent, effort)[0, 1]:+.3f}')
print(f'correlation among the {selected.sum()} selected: {np.corrcoef(talent[selected], effort[selected])[0, 1]:+.3f}')correlation in the population: +0.033
correlation among the 1444 selected: -0.679
Talent and effort are unrelated in the population (correlation +0.03); among the 1 444 selected students the correlation is −0.68. Hospital studies, published papers (selected for striking results) and dating apps all select on colliders in this way.
4. Simpson’s Paradox¶
A fork confounds. In a classic study of kidney-stone treatments (Charig et al., 1986), treatment A was given more often for large stones, which are harder to treat. The numbers below are the study’s.
# (successes, patients)
STONES = {('A', 'small'): (81, 87), ('A', 'large'): (192, 263), ('B', 'small'): (234, 270), ('B', 'large'): (55, 80)}
for size in ['small', 'large']:
print(f'{size:<6} stones: A {STONES[("A", size)][0] / STONES[("A", size)][1]:.1%} B {STONES[("B", size)][0] / STONES[("B", size)][1]:.1%}')
tot = {t: tuple(map(sum, zip(*[STONES[(t, s)] for s in ('small', 'large')]))) for t in 'AB'}
print(f'overall: A {tot["A"][0] / tot["A"][1]:.1%} B {tot["B"][0] / tot["B"][1]:.1%}')small stones: A 93.1% B 86.7%
large stones: A 73.0% B 68.8%
overall: A 78.0% B 82.6%
Treatment A succeeds more often for small stones (93.1% against 86.7%) and for large stones (73.0% against 68.8%), yet less often overall (78.0% against 82.6%). A was mostly given for large stones, the hard cases.
Stone size is a common cause of the treatment choice and of the outcome: a fork, open as long as size is not taken into account. To estimate what giving A or B to everyone would do, , we adjust for the confounder (the back-door adjustment):
n_size = {s: sum(STONES[(t, s)][1] for t in 'AB') for s in ('small', 'large')}
N = sum(n_size.values())
for t in 'AB':
adj = sum(STONES[(t, s)][0] / STONES[(t, s)][1] * n_size[s] / N for s in ('small', 'large'))
print(f'P(success | do({t})) = {adj:.1%}')P(success | do(A)) = 83.3%
P(success | do(B)) = 77.9%
Adjusted for stone size, A is the better treatment: 83.3% against 77.9%, the direction found within each group.
Adjusting is right for a fork (a confounder), and wrong for a collider: adjusting for a common effect, as in Berkson’s example, creates a bias that was not there. The graph, not the data, tells you which variables to adjust for.
5. Every Independence a Graph Implies¶
The local Markov property: each variable is independent of its non-descendants given its parents. These statements imply all the others (through d-separation). For the Asia network:
for v in ASIA.order:
nondesc = set(ASIA.G) - nx.descendants(ASIA.G, v) - {v} - set(ASIA.parents[v])
if nondesc:
print(f'{v} ⫫ {{{", ".join(sorted(nondesc))}}} | {{{", ".join(ASIA.parents[v])}}}')A ⫫ {B, L, S} | {}
S ⫫ {A, T} | {}
T ⫫ {B, L, S} | {A}
L ⫫ {A, B, T} | {S}
B ⫫ {A, E, L, T, X} | {S}
E ⫫ {A, B, S} | {T, L}
X ⫫ {A, B, D, L, S, T} | {E}
D ⫫ {A, L, S, T, X} | {E, B}
Summary¶
Ancestral sampling draws each variable after its parents; enough samples reproduce the exact probabilities.
A pooled chi-squared test checks conditional independence in data; its verdicts follow d-separation when the sample is large.
Selecting on a collider creates spurious correlations (Berkson); a confounding fork can reverse a trend (Simpson).
Adjust for confounders, never for colliders: the graph decides.
The local Markov property lists the basic independences from which all others follow.