Note
Go to the end to download the full example code.
Add background knowledge#
GES and XGES take
pairs of variables that must be adjacent (required) or must not be
(forbidden), by name or by column index. Knowledge fixes adjacency, not
direction: a search over equivalence classes still orients edges from the
data.
from causalbase import GES
from causalbase.datasets import load_asia
bundle = load_asia()
frame = bundle.data.to_pandas()
def neighbours(model, node):
"""Return the variables joined to `node` by an edge of either kind."""
adjacency = model.adjacency_
return [v for v in adjacency.columns if adjacency.loc[node, v] or adjacency.loc[v, node]]
In asia, either is tuberculosis or lung cancer, and GES joins it to
both of its causes and to its two effects.
['lung', 'xray', 'tub', 'dysp']
Forbidding lung -- either keeps the two apart whatever the data say.
The search then explains the dependence through other edges, such as a
direct one between lung and xray.
constrained = GES(forbidden=[("lung", "either")]).fit(frame)
neighbours(constrained, "either"), neighbours(constrained, "lung")
(['smoke', 'xray', 'tub', 'dysp'], ['smoke', 'xray', 'tub'])
The constraint costs score: under the same BDeu, the free network is better.
print(f"Free {free.score_:.1f}, with the forbidden pair {constrained.score_:.1f}")
Free -11292.4, with the forbidden pair -11543.1
Total running time of the script: (0 minutes 0.031 seconds)