Chapter 23: Independence and d-Separation
Correlation does not imply causation, but it does waggle its eyebrows suggestively.
Randall Munroe, xkcd
23.1 Why Independence Matters¶
Chapter 22 introduced Bayesian networks: a directed acyclic graph whose nodes are variables, with one conditional probability table (CPT) per node, . The joint distribution is their product:
A full joint table over binary variables needs numbers; the network needs only one number per row of each CPT. The saving comes entirely from what the graph says is independent of what. This chapter makes that precise: which independences can be read from the graph, how to read them, and what they do and do not tell us.
Our example is the classic Asia network (Lauritzen and Spiegelhalter, 1988), a small model of chest-clinic diagnosis:
import itertools
import numpy as np
import networkx as nx
VARS = ['A', 'S', 'T', 'L', 'B', 'E', 'X', 'D']
PARENTS = {'A': [], 'S': [], 'T': ['A'], 'L': ['S'], 'B': ['S'], 'E': ['T', 'L'], 'X': ['E'], 'D': ['E', 'B']}
# P(variable = 1 | parents), indexed by the tuple of parent values
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}, # E is "T or L": deterministic
'X': {(1,): 0.98, (0,): 0.05},
'D': {(1, 1): 0.90, (1, 0): 0.70, (0, 1): 0.80, (0, 0): 0.10}}
def joint_table():
"""All 2^8 = 256 assignments and their probabilities, as the product of the CPTs."""
rows, probs = [], []
for values in itertools.product([0, 1], repeat=len(VARS)):
x = dict(zip(VARS, values)); p = 1.0
for v in VARS:
p1 = CPT[v][tuple(x[u] for u in PARENTS[v])]
p *= p1 if x[v] == 1 else 1 - p1
rows.append(values); probs.append(p)
return np.array(rows), np.array(probs)
ROWS, P = joint_table()
col = {v: i for i, v in enumerate(VARS)}
def prob(query, evidence={}):
"""P(query | evidence), both dicts {variable: value}, by summing the joint table."""
match = lambda d: np.all([ROWS[:, col[v]] == val for v, val in d.items()], axis=0) if d else np.ones(len(P), bool)
return P[match({**query, **evidence})].sum() / P[match(evidence)].sum()
n_cpt = sum(len(t) for t in CPT.values())
print(f'joint table: {2 ** 8 - 1} free numbers; the network: {n_cpt}. Total probability {P.sum():.6f}')
print(f'P(lung cancer) = {prob({"L": 1}):.4f}; P(lung cancer | smoker, positive X-ray) = {prob({"L": 1}, {"S": 1, "X": 1}):.4f}')joint table: 255 free numbers; the network: 18. Total probability 1.000000
P(lung cancer) = 0.0550; P(lung cancer | smoker, positive X-ray) = 0.6460
The full joint table would need 255 numbers; the network needs 18. And it answers any question: a patient’s prior chance of lung cancer is 5.5%; for a smoker with a positive X-ray, 64.6%.
23.2 Three Connections¶
Every path in a network is built from three kinds of connection between consecutive variables. Each says something different about how evidence flows.
| Connection | Shape | Without evidence on the middle | With evidence on the middle |
|---|---|---|---|
| Chain | dependent: smoking changes the chance of | independent: once is known, adds nothing about | |
| Fork (common cause) | dependent: both share a cause | independent: given , and are unrelated | |
| Collider (common effect) | independent: tuberculosis and cancer are unrelated | dependent: knowing , one cause explains away the other |
The collider is the surprising one: observing a common effect, or any of its descendants, creates a dependence between causes that were independent. Let us check all three numerically, with a helper that tests whether for every value of and :
def independent(x, y, given=()):
"""True if x and y are independent given the variables in `given`, according to the joint table."""
for zs in itertools.product([0, 1], repeat=len(given)):
z = dict(zip(given, zs))
if prob(z) == 0: continue
p_x = prob({x: 1}, z)
for yv in (0, 1):
if prob({y: yv}, z) > 0 and abs(prob({x: 1}, {**z, y: yv}) - p_x) > 1e-9:
return False
return True
cases = [('chain', 'S', 'E', ()), ('chain', 'S', 'E', ('L',)), ('fork', 'L', 'B', ()), ('fork', 'L', 'B', ('S',)),
('collider', 'T', 'L', ()), ('collider', 'T', 'L', ('E',)), ('collider, descendant', 'T', 'L', ('X',))]
for kind, x, y, z in cases:
print(f'{kind:<22} {x} and {y} given {{{", ".join(z)}}}: {"independent" if independent(x, y, z) else "dependent"}')chain S and E given {}: dependent
chain S and E given {L}: independent
fork L and B given {}: dependent
fork L and B given {S}: independent
collider T and L given {}: independent
collider T and L given {E}: dependent
collider, descendant T and L given {X}: dependent
Explaining away, in numbers. A positive X-ray raises the probability of tuberculosis. Learning, in addition, that the patient has lung cancer explains the X-ray, and brings tuberculosis back down:
for ev, label in [({}, 'nothing known'), ({'X': 1}, 'positive X-ray'), ({'X': 1, 'L': 1}, 'positive X-ray and lung cancer')]:
print(f'P(tuberculosis | {label:<31}) = {prob({"T": 1}, ev):.4f}')P(tuberculosis | nothing known ) = 0.0104
P(tuberculosis | positive X-ray ) = 0.0924
P(tuberculosis | positive X-ray and lung cancer ) = 0.0104
A positive X-ray raises the probability of tuberculosis from 1.04% to 9.24%. Learning that the patient also has lung cancer brings it back to 1.04%, exactly where it started: E is “T or L”, and lung cancer alone accounts for everything the X-ray said about E.
23.3 d-Separation¶
Two variables can influence each other only along a trail: a path in the graph, ignoring arrow directions. A trail is active given evidence if every consecutive triple on it passes:
a chain or fork passes when its middle node is not in ;
a collider passes when its middle node, or one of its descendants, is in .
and are d-separated by (“d” for directed) if no trail between them is active. The central theorem (Geiger, Verma and Pearl, 1990): if and are d-separated by in the graph, then in every distribution that factorises over it, whatever its tables; and if they are not d-separated, some such distribution makes them dependent.
Checking every trail is exponential. The reachability algorithm (Koller and Friedman, Algorithm 3.1; also known as “Bayes ball”) walks the graph once, remembering whether each node was entered from a child (going up) or from a parent (going down):
G = nx.DiGraph([(p, v) for v, ps in PARENTS.items() for p in ps])
def reachable(G, x, Z):
"""The nodes reachable from x by an active trail given the evidence Z."""
Z = set(Z)
ancestors_of_Z = set(Z).union(*(nx.ancestors(G, z) for z in Z)) # colliders pass if they or a descendant are observed
to_visit, visited, reach = [(x, 'up')], set(), set()
while to_visit:
node, direction = to_visit.pop()
if (node, direction) in visited: continue
visited.add((node, direction))
if node not in Z: reach.add(node)
if direction == 'up' and node not in Z: # arrived from a child
to_visit += [(p, 'up') for p in G.predecessors(node)] + [(c, 'down') for c in G.successors(node)]
elif direction == 'down': # arrived from a parent
if node not in Z:
to_visit += [(c, 'down') for c in G.successors(node)]
if node in ancestors_of_Z: # an activated collider: turn back up
to_visit += [(p, 'up') for p in G.predecessors(node)]
return reach - {x}
def d_separated(G, x, y, Z=()):
return y not in reachable(G, x, Z)
print('reachable from A, no evidence: ', sorted(reachable(G, 'A', [])))
print('reachable from A, given E: ', sorted(reachable(G, 'A', ['E'])))
print('reachable from A, given E and S: ', sorted(reachable(G, 'A', ['E', 'S'])))reachable from A, no evidence: ['D', 'E', 'T', 'X']
reachable from A, given E: ['B', 'D', 'L', 'S', 'T']
reachable from A, given E and S: ['L', 'T']
Without evidence, A reaches only its descendants (T, E, X, D): the collider at E blocks the way to L, S and B. Observing E opens the collider, and A now reaches L, S and B (and D through B), but no longer X, whose only link to A runs through the observed E. Adding S to the evidence blocks the fork at S: only T and L remain.
Checking the theorem. For every pair of variables and every evidence set of up to two other variables, we compare three verdicts: our algorithm, networkx (which implements d-separation independently), and the numbers of the joint table.
agree_nx = agree_num = total = sep = 0
mismatches = []
for x, y in itertools.combinations(VARS, 2):
others = [v for v in VARS if v not in (x, y)]
for k in range(3):
for Z in itertools.combinations(others, k):
ours = d_separated(G, x, y, Z)
agree_nx += ours == nx.is_d_separator(G, {x}, {y}, set(Z))
num = independent(x, y, Z)
agree_num += ours == num
if ours != num: mismatches.append((x, y, Z, ours, num))
total += 1; sep += ours
print(f'{total} queries; d-separated in {sep}. Agreement with networkx: {agree_nx}/{total}; with the numbers: {agree_num}/{total}')
for m in mismatches[:6]: print(' graph says', 'separated' if m[3] else 'connected', 'but the numbers say', 'independent' if m[4] else 'dependent', ':', m[:3])616 queries; d-separated in 156. Agreement with networkx: 616/616; with the numbers: 613/616
graph says connected but the numbers say independent : ('E', 'X', ('T', 'L'))
graph says connected but the numbers say independent : ('E', 'D', ('T', 'L'))
graph says connected but the numbers say independent : ('X', 'D', ('T', 'L'))
Our algorithm agrees with networkx on all 616 queries, and with the numbers on 613. The three exceptions all ask about E, X or D given T and L: the graph says they may depend on each other, but E is deterministic (“T or L”), so knowing T and L fixes E, and the numbers find independences the graph does not show. d-separation guarantees every independence it finds; a particular distribution can have more. Such a distribution is called unfaithful to its graph, and deterministic nodes are the classic cause.
23.4 The Markov Blanket¶
Which variables does a node need to know about, to be independent of everything else? Its Markov blanket: its parents, its children, and its children’s other parents (the co-parents, because of the collider rule). Given its blanket, a node is independent of all other nodes.
def markov_blanket(G, v):
children = set(G.successors(v))
return set(G.predecessors(v)) | children | {p for c in children for p in G.predecessors(c)} - {v}
for v in ['L', 'E', 'S']:
mb = markov_blanket(G, v)
rest = [u for u in VARS if u not in mb | {v}]
ok = all(independent(v, u, tuple(sorted(mb))) for u in rest)
print(f'Markov blanket of {v}: {sorted(mb)}; independent of {rest} given it: {ok}')Markov blanket of L: ['E', 'S', 'T']; independent of ['A', 'B', 'X', 'D'] given it: True
Markov blanket of E: ['B', 'D', 'L', 'T', 'X']; independent of ['A', 'S'] given it: True
Markov blanket of S: ['B', 'L']; independent of ['A', 'T', 'E', 'X', 'D'] given it: True
The Markov blanket is what makes Gibbs sampling (Chapter 24) cheap: to resample one variable, only its blanket matters. It is also the natural set of features if you want to predict one variable from the others.
23.5 Markov Equivalence¶
Different graphs can encode exactly the same independences. The chain , the reverse chain and the fork all say one thing: . Only the collider says something different (, but not given ).
Theorem (Verma and Pearl, 1990): two networks are Markov equivalent (encode the same independences) if and only if they have the same skeleton (the undirected edges) and the same v-structures (colliders whose parents are not linked).
def v_structures(G):
U = G.to_undirected()
return {(min(a, b), c, max(a, b)) for c in G for a, b in itertools.combinations(G.predecessors(c), 2) if not U.has_edge(a, b)}
def equivalent(G1, G2):
same_skeleton = {frozenset(e) for e in G1.to_undirected().edges} == {frozenset(e) for e in G2.to_undirected().edges}
return same_skeleton and v_structures(G1) == v_structures(G2)
three = {'chain X→Y→Z': [('X', 'Y'), ('Y', 'Z')], 'chain X←Y←Z': [('Y', 'X'), ('Z', 'Y')], 'fork X←Y→Z': [('Y', 'X'), ('Y', 'Z')], 'collider X→Y←Z': [('X', 'Y'), ('Z', 'Y')]}
graphs = {k: nx.DiGraph(v) for k, v in three.items()}
ref = graphs['chain X→Y→Z']
for k, g in graphs.items():
print(f'{k:<18} equivalent to the chain X→Y→Z: {equivalent(ref, g)}; v-structures {sorted(v_structures(g))}')chain X→Y→Z equivalent to the chain X→Y→Z: True; v-structures []
chain X←Y←Z equivalent to the chain X→Y→Z: True; v-structures []
fork X←Y→Z equivalent to the chain X→Y→Z: True; v-structures []
collider X→Y←Z equivalent to the chain X→Y→Z: False; v-structures [('X', 'Y', 'Z')]
How many networks are equivalent to the Asia network? We try every way of reversing a subset of its edges and keep the acyclic graphs equivalent to it:
edges = list(G.edges)
equiv = []
for flips in itertools.product([0, 1], repeat=len(edges)):
H = nx.DiGraph([(b, a) if f else (a, b) for (a, b), f in zip(edges, flips)])
if nx.is_directed_acyclic_graph(H) and equivalent(G, H):
equiv.append([e for e, f in zip(edges, flips) if f])
print(f'{len(equiv)} networks (counting itself) encode exactly the same independences as Asia')
reversible = sorted({tuple(e) for flips in equiv for e in flips})
print('edges whose direction data alone cannot decide:', reversible)6 networks (counting itself) encode exactly the same independences as Asia
edges whose direction data alone cannot decide: [('A', 'T'), ('S', 'B'), ('S', 'L')]
Six networks, including Asia itself, imply exactly the same independences. Some combinations of the directions of A → T, S → L and S → B can be reversed; but the arrows into the colliders E and D, and E → X, are the same in all six (reversing E → X would create a new v-structure at E).
This has a practical consequence for causal claims. Data observed passively can at best identify the equivalence class, not the arrows inside it: whether smoking causes lung cancer or lung cancer “causes” smoking is the same pattern of independences. Telling them apart needs interventions (experiments, Chapter 10’s A/B tests at scale), background knowledge (a cause comes before its effect), or the extra assumptions of causal inference (Pearl’s do-calculus).
23.6 Intervening Is Not Observing¶
Observing that a patient smokes and making a patient smoke are different operations. Pearl writes the second as : cut every arrow into , set it, and compute in the cut (“mutilated”) graph. Here has no parents, so the two coincide for the effects of smoking; they differ when we intervene on a variable with causes. Observing a positive X-ray raises the probability of lung cancer; forcing the X-ray to be positive (a faulty machine) does not:
def prob_do(query, intervention):
"""P(query | do(intervention)): the network with the intervened variables' tables replaced by constants."""
saved = {v: CPT[v] for v in intervention}
saved_parents = {v: PARENTS[v] for v in intervention}
global ROWS, P
try:
for v, val in intervention.items():
PARENTS[v] = []; CPT[v] = {(): float(val)}
ROWS, P = joint_table()
return prob(query)
finally:
CPT.update(saved); PARENTS.update(saved_parents); ROWS, P = joint_table()
print(f'P(lung cancer) = {prob({"L": 1}):.4f}')
print(f'P(lung cancer | X-ray = 1) = {prob({"L": 1}, {"X": 1}):.4f} (observing)')
print(f'P(lung cancer | do(X-ray = 1)) = {prob_do({"L": 1}, {"X": 1}):.4f} (intervening)')P(lung cancer) = 0.0550
P(lung cancer | X-ray = 1) = 0.4887 (observing)
P(lung cancer | do(X-ray = 1)) = 0.0550 (intervening)
Observing a positive X-ray raises the probability of lung cancer from 5.5% to 48.9%: the X-ray is evidence about its cause. Forcing the X-ray leaves it at 5.5%: acting on an effect tells us nothing about its causes.
23.7 Summary¶
A Bayesian network’s compactness comes from the conditional independences its graph encodes.
Chains and forks pass influence unless their middle node is observed; colliders block it unless the middle node or a descendant is observed (explaining away).
d-separation reads every implied independence from the graph; the reachability algorithm decides it in one pass, and it agrees with the numbers.
Given its Markov blanket (parents, children, children’s other parents) a node is independent of everything else.
Networks with the same skeleton and v-structures are Markov equivalent: passive data cannot tell them apart. Causal direction needs interventions or assumptions; differs from observing .
Exercises¶
In the Asia network, list all trails between A and D. Which are active given {E}? Given {B}? Given nothing?
Is S d-separated from X given {L}? Given {E}? Given {L, T}? Explain each answer with the three connections.
Give the Markov blanket of T and of B. Verify one of them with the
independentfunction.Draw all Markov-equivalent versions of . Which edges can be reversed?
A hospital admits patients who have disease A or disease B. In the hospital’s data, A and B are negatively correlated. Explain with a collider. (This is Berkson’s paradox.)
Why is in the Asia network? Would equal ? Why?
Prove that in a chain , , using only the factorisation.
Further Reading¶
D. Koller, N. Friedman, Probabilistic Graphical Models: Principles and Techniques, MIT Press, 2009, Chapter 3.
J. Pearl, Causality, 2nd ed., Cambridge University Press, 2009.
J. Pearl, D. Mackenzie, The Book of Why, Basic Books, 2018.
S. Lauritzen, D. Spiegelhalter, “Local computations with probabilities on graphical structures and their application to expert systems”, JRSS B, 1988.
R. Shachter, “Bayes-ball: the rational pastime”, UAI, 1998.