Algorithmresearch
Greedy equivalence search
Also called GES.
Chickering's score-based causal discovery that adds and then deletes edges over Markov equivalence classes. It finds the true class in the limit under faithfulness and no hidden confounders.
- Time
- O(n^4 2^n) worstΘ(n^2) best
- Space
- O(n^2) extra
- Where
- n = the number of variables
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- David Maxwell Chickering, Christopher Meek, 2002
Greedy equivalence search (GES) learns the Markov equivalence class of a causal directed acyclic graph by maximizing a score, such as the Bayesian information criterion. It does not search over DAGs but over equivalence classes, drawn as CPDAGs, because data cannot tell apart DAGs with the same d-separations. It starts from the empty graph. In the forward phase it adds one edge at a time, always the addition that raises the score most, until no addition helps. In the backward phase it removes one edge at a time in the same way. Chickering (2002) proved that with a consistent score, a distribution faithful to a DAG over the observed variables (no hidden common causes) and enough data, this simple two-phase search finds the true class. It is the standard score-based method of Bayesian network structure learning, next to the test-based PC algorithm.
In plain words
Give every possible causal diagram a grade for how well it explains the data, with a penalty for each arrow. Diagrams that the data cannot tell apart get the same grade, so treat each group of them as one candidate. Start with no arrows. Add the single link that improves the grade most, and repeat until no single link helps. Then remove the single link whose removal improves the grade most, and repeat until no removal helps. With enough data, the first pass ends with every true link and maybe some extra ones, and the second pass takes the extra ones away.
The problem
The input is a set of variables and a decomposable score: the score of a DAG is , a sum of local scores of each variable and its parents. The score must also be score equivalent, so that Markov equivalent DAGs get the same score, and the score of a class is well defined. For Gaussian data with samples and sample covariance , the implementation uses
where is the residual variance of the least-squares regression of on . This is times the BIC of that regression, up to terms that do not depend on .
The goal is the class with the highest score. When the data come from a DAG whose d-separations are exactly the conditional independences of the distribution, the hope is that this class is the class of . The output is a CPDAG: arrows that all DAGs of the class share, and undirected edges elsewhere.
The algorithm
For a current CPDAG and nodes , , let be the parents of , the nodes joined to by an undirected edge, and the nodes of that are adjacent to . A path is semi-directed from to when each edge is undirected or points away from .
- Insert, for non-adjacent , and with no node adjacent to : add and orient for each .
- Delete, for or and : remove the edge, and orient and for each whose edges are undirected.
GES(V, s)- 1
C ← the empty graph on V - 2
repeat - 3
for each non-adjacent X, Y and each T ⊆ N_Y with no node adjacent to X do - 4
skip unless NA ∪ T is a clique and blocks every semi-directed path from Y to X - 5
Δ ← s(Y, NA ∪ T ∪ Pa_Y ∪ {X}) - s(Y, NA ∪ T ∪ Pa_Y) - 6
if the best Δ ≤ 0 then leave the loop - 7
apply the best Insert; C ← CPDAG of a consistent extension - 8
repeat - 9
for each X → Y or X - Y and each H ⊆ NA do - 10
skip unless NA \ H is a clique - 11
Δ ← s(Y, (NA \ H) ∪ Pa_Y \ {X}) - s(Y, (NA \ H) ∪ Pa_Y ∪ {X}) - 12
if the best Δ ≤ 0 then leave the loop - 13
apply the best Delete; C ← CPDAG of a consistent extension - 14
return C
Here means . Lines L4 and L10 are the validity tests of Chickering (2002): exactly the operators that pass them turn the class into another class, and then the change of score is the local difference of line L5 or L11, so no full DAG is scored. After an operator the graph is only partly directed. Line L7 and line L13 complete it to a DAG with the same arrows and no new v-structure by the procedure of Dor and Tarsi (1992): repeatedly take a node with no outgoing arrow whose undirected neighbours are adjacent to all its other neighbours, direct its undirected edges into it, and remove it. Then they turn that DAG into its CPDAG with the rules of Meek (1995).
Example
Take the DAG , , , , with the linear model , , , and independent unit-variance noises. The implementation computes its covariance exactly with fractions, for example . Run GES on this covariance with :
| step | operator | result | |
|---|---|---|---|
| 1 | Insert | 554.00 | |
| 2 | Insert | 268.85 | adds |
| 3 | Insert | 253.07 | adds |
| 4 | Insert | 243.89 | adds |
| 5 | Insert | 127.26 | adds |
| 6 | Insert | 0.50 | adds |
| 7 | Delete | 3.45 | removes , makes |
After step 5 the skeleton is the true one, but the collider is at , not at . That class says , which is false, so step 6 adds the extra edge , which removes the collider at . Step 7, in the backward phase, removes it again with and puts the collider at . The output is , , , , the CPDAG of the true DAG, after 150 operator evaluations.
Correctness
The proof is in proofs/correctness.md. It is partial. It proves:
- Termination. Each Insert adds exactly one edge to the skeleton and each Delete removes one, so there are at most steps.
- Score equivalence. Reversing a covered edge , one with , keeps the Gaussian BIC, because is symmetric in and . Equivalent DAGs are joined by covered reversals (Chickering 1995, cited).
- Local consistency. Adding to the parents of changes the score by , where is the partial correlation of and given . For large enough this is positive exactly when .
Cited, not proved: the validity tests and local formulas of the operators, and the large-sample theorem of Chickering (2002). That theorem says that with a decomposable, score-equivalent, locally consistent score for a distribution faithful to , the forward phase ends at a class whose independences all hold, and the backward phase ends at the class of . Its proof rests on Meek's conjecture, which Chickering proved in the same paper. The tests check the result against exhaustive search over all DAGs on three and four nodes.
Proof: GES stops after at most n(n - 1) operators; the Gaussian BIC is score equivalent and, for large N, locally consistent; with these properties and faithfulness the output is the true class by the cited theorem of Chickering (2002)partial
What is proved and what is cited. This file proves that GES stops, that the Gaussian BIC gives the same score to Markov equivalent DAGs, and that for a large enough sample size it is locally consistent: adding one parent raises the score exactly when the new parent is dependent on the child given the old parents. Two results of Chickering (2002) are cited and not proved: that a valid Insert or Delete gives a class whose score changes by the local formula of lines L5 and L11, and the large-sample optimality theorem, which turns local consistency into the statement that GES returns the true class. The tests check the full claim against exhaustive search over all DAGs on three and four nodes.
Setting. The variables are with . A score is decomposable when the score of a DAG is . It is score equivalent when Markov equivalent DAGs have the same score; then the score of a class is the score of any of its DAGs. The Gaussian BIC local score with samples and covariance matrix (positive definite) is
This is times the BIC of the regression of on , with the terms that do not depend on dropped.
Lemma 1 (termination). GES applies at most Insert operators and at most Delete operators, and then stops.
Proof. An Insert needs and non-adjacent. It adds the edge and only orients edges between and , so the PDAG of line L7 has the skeleton of the current class plus one edge. A consistent extension of has the skeleton of , and the CPDAG of a DAG has the skeleton of that DAG. So each Insert adds exactly one edge to the skeleton and removes none. The skeleton has at most edges, so the forward phase applies at most operators and then finds no valid operator with a positive change, or none at all. In the same way each Delete removes exactly one edge, so the backward phase applies at most as many Delete operators as there are edges. Each step examines finitely many operators.
The lemma does not need score equivalence or the validity theorem. It also bounds the work: at most steps, each with at most operators.
Lemma 2 (two Schur identities). Let and . Then
and , where is the partial correlation of and given .
Proof. For a positive definite block matrix, , because is the Schur complement of . Apply this twice: . The other order gives the right side. For the second claim, let and be the residuals of the regressions of and on . The linear span of is the span of and , and is orthogonal to . So the residual variance of on is , with .
Lemma 3 (score equivalence). Markov equivalent DAGs have the same Gaussian BIC score, for every and every positive definite .
Proof. An edge of a DAG is covered when . Reversing a covered edge gives a DAG (a new cycle through would need a directed path from to of length at least two, whose last inner node is a parent of and so of , which closes a cycle in ). We cite the transformational characterization (Chickering 1995, restated in Chickering 2002): two DAGs are Markov equivalent exactly when one is reached from the other by a sequence of covered edge reversals. So it is enough to show that one reversal keeps the score. Let . Only the families of and change, from and to and . The penalty terms count parents in both cases. The likelihood terms are of the two products of Lemma 2, which are equal.
Lemma 4 (local consistency for large N). Fix . There is such that for all , all , all and all ,
Proof. By Lemma 2 the change is . If , then for . If , then and , which is positive once . There are finitely many triples , so one works for all of them.
For a Gaussian distribution, exactly when . If the distribution is also faithful to a DAG , this holds exactly when d-separates and in . So for the score with the true covariance is decomposable, score equivalent and locally consistent. The tests use the limit of this order as with exact fractions: exactly when , or the two are equal and the change removes a parent.
Cited results. Chickering (2002) proves two facts about the operators. First, Insert is valid (the result is a class that contains a DAG with added) exactly when is a clique and every semi-directed path from to meets , and then the score changes by the formula of line L5; Delete is valid exactly when is a clique, and the score changes by the formula of line L11. Second, the optimality theorem: if the score is decomposable, score equivalent and locally consistent for a distribution faithful to a DAG , then the forward phase ends at a class in which every d-separation is an independence of the distribution (an independence map), and the backward phase ends at the class of . Its proof uses the theorem, also in Chickering (2002), that Meek's conjecture holds: if every independence of holds in , then is reached from by covered edge reversals and single edge deletions. With Lemmas 3 and 4 this gives: with the true covariance and , GES returns the CPDAG of . With a sample covariance, the score is consistent as , and the same theorem gives the true class with probability tending to 1.
What the tests check. For every DAG on three and on four nodes (25 and 543 DAGs), with random weights and the exact limit score, GES returns the class of the true DAG and the class of the best of all DAGs found by exhaustive search. With the float BIC at , GES returns the best class over all 543 DAGs every time. Lemma 3 is checked exactly with fractions on all 543 DAGs on four nodes, and Lemma 4 with the d-separation oracle.
Complexity
The cost is counted in evaluations of the score change of an operator. Each step looks at most at ordered pairs, each with at most subsets or , and there are at most steps. So the worst case is evaluations. The best case is data with no dependence: the first forward step evaluates the operators with , none helps, and the backward phase has nothing to do. Each evaluation needs two local scores; the Gaussian score solves a linear system of size , and a cache keyed by avoids repeats. The graph takes space. In practice the subsets stay small for sparse graphs, and the number of evaluations grows far more slowly than the bound.
Properties
- Consistent, not exact. With a consistent score, and a distribution faithful to a DAG over the observed variables (so no hidden common causes), GES returns the true class with probability tending to 1. For a fixed sample it is a greedy search and can stop at a class that is not the best; see Pitfalls.
- Works on classes. Each state is a whole equivalence class, so the search does not waste steps among equivalent DAGs, and the result does not depend on how the variables are numbered except through ties.
- Deterministic. Ties between operators are broken by the order of the variables.
- Gives a score. Unlike PC, GES returns the score of its answer, which can be compared with other classes.
Variants and improvements
- Turning phase. Later work adds a third phase that reverses edges, which helps at finite sample sizes.
- Speed-ups. Fast GES implementations cache operator scores and recompute only those that touch the changed nodes, and they run on thousands of variables.
- Search over DAGs. Plain hill climbing or tabu search over DAGs with edge additions, deletions and reversals is simpler, but has no large-sample guarantee.
- Other scores. Discrete data use the BIC of multinomial tables or the BDeu marginal likelihood, both decomposable and score equivalent.
- Hidden variables and full orientation. GES assumes that all common causes are measured; the FCI algorithm drops that assumption. With non-Gaussian noise, LiNGAM finds the whole DAG.
When to use it
Use GES when a likelihood-based score fits the data well, the number of variables is moderate, and all common causes are measured. It often gives more stable answers than PC at small and medium sample sizes, because each decision weighs the whole fit of a family instead of one test. For very many variables or very dense graphs, the subsets and make it slow; then use PC, or restrict GES to a candidate set of edges.
Pitfalls
- Local optima at finite N. In the example, use the same exact covariance but . Then step 6 no longer pays its penalty, and GES stops with , , and score . The true class scores : its product of residual variances is , and the output's is . GES stops below the best class, so its guarantee is only a large-sample guarantee.
- Measured rates with data. On 50 data sets of each size from the example model, GES found the true class in 7 runs at , 17 at and 40 at . At , exhaustive search over all 29281 DAGs on five nodes showed that the BIC was highest for the true class in 44 of the 50 runs, but GES reached the highest scoring class in only 20. These rates are measured on the implementation, not proved.
- Weak edges. The penalty wins when a partial correlation is small for the sample size. With the exact covariance of 543 random linear models on four nodes and , GES returned the best class of all DAGs every time, but in 6 cases that class lacked one weak true edge.
- Faithfulness. If two paths cancel, for example and with weights whose products cancel, the guarantee fails and GES can end in a class with a lower score than the best one.
- Causal reading. The output is causal only if there are no hidden common causes and the score is right for the data. A Gaussian score on strongly non-Gaussian or non-linear data can prefer wrong classes.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/greedy-equivalence-search/. The authors are listed in prov/08T080.jsonl.
"""Greedy equivalence search (GES) of Chickering (2002).
The state is a CPDAG: a graph with directed edges (pa, ch) and undirected
edges (nb) that stands for a Markov equivalence class of DAGs. The score is
decomposable: score(dag) = sum of local(v, parents of v). The forward phase
applies the best Insert operator while it raises the score; the backward
phase applies the best Delete operator while it raises the score.
The module also has the Gaussian BIC local score, computed from a covariance
matrix, and helpers that make covariances of linear models exactly with
fractions.
"""
import itertools
import math
from fractions import Fraction
from typing import NamedTuple
class PDAG:
"""Partially directed graph: pa[v] -> v, v -> ch[v], v - nb[v]."""
def __init__(self, nodes):
self.nodes = list(nodes)
self.pa = {v: set() for v in self.nodes}
self.ch = {v: set() for v in self.nodes}
self.nb = {v: set() for v in self.nodes}
def copy(self):
g = PDAG(self.nodes)
for v in self.nodes:
g.pa[v] = set(self.pa[v])
g.ch[v] = set(self.ch[v])
g.nb[v] = set(self.nb[v])
return g
def adj(self, v):
return self.pa[v] | self.ch[v] | self.nb[v]
def adjacent(self, a, b):
return b in self.adj(a)
def add_arrow(self, a, b):
self.ch[a].add(b)
self.pa[b].add(a)
def add_line(self, a, b):
self.nb[a].add(b)
self.nb[b].add(a)
def remove(self, a, b):
for d in (self.pa, self.ch, self.nb):
d[a].discard(b)
d[b].discard(a)
def orient(self, a, b):
"""Turn the undirected edge a - b into a -> b."""
self.nb[a].discard(b)
self.nb[b].discard(a)
self.add_arrow(a, b)
def edges(self):
arrows = sorted((a, b) for a in self.nodes for b in self.ch[a])
lines = sorted((a, b) for a in self.nodes for b in self.nb[a] if str(a) < str(b))
return arrows, lines
def is_clique(g, s):
return all(g.adjacent(a, b) for a, b in itertools.combinations(s, 2))
def blocks_semi_directed(g, y, x, block):
"""True if every semi-directed path from y to x meets the set block."""
seen, stack = {y}, [y]
while stack:
v = stack.pop()
for w in g.ch[v] | g.nb[v]:
if w == x:
return False
if w not in seen and w not in block:
seen.add(w)
stack.append(w)
return True
# ---------------------------------------------------------------------------
# From a PDAG to a DAG and from a DAG to its CPDAG
def consistent_extension(g):
"""A DAG with the skeleton and the arrows of g and no new v-structure
(Dor and Tarsi 1992). Returns parents as a dict, or None if there is none."""
h = g.copy()
parents = {v: set(g.pa[v]) for v in g.nodes}
left = set(g.nodes)
while left:
for x in sorted(left, key=str):
if h.ch[x]:
continue
others = h.adj(x)
if all(others - {y} <= h.adj(y) for y in h.nb[x]):
for y in h.nb[x]:
parents[x].add(y) # orient y -> x
for y in list(h.adj(x)):
h.remove(x, y)
left.discard(x)
break
else:
return None
return parents
def cpdag_of_dag(nodes, parents):
"""The CPDAG of a DAG: arrows of v-structures, then Meek's rules R1 to R3."""
g = PDAG(nodes)
for v in nodes:
for p in parents[v]:
g.add_line(p, v)
for c in nodes:
for a, b in itertools.combinations(sorted(parents[c], key=str), 2):
if not g.adjacent(a, b):
for u in (a, b):
if u in g.nb[c]:
g.orient(u, c)
changed = True
while changed:
changed = False
for b in nodes:
for c in list(g.nb[b]):
if c not in g.nb[b]:
continue
r1 = any(not g.adjacent(a, c) for a in g.pa[b])
r2 = any(a in g.pa[c] for a in g.ch[b])
r3 = any(not g.adjacent(a1, a2) and {a1, a2} <= g.pa[c]
for a1, a2 in itertools.combinations(g.nb[b], 2))
if r1 or r2 or r3:
g.orient(b, c)
changed = True
return g
# ---------------------------------------------------------------------------
# GES
class GESResult(NamedTuple):
cpdag: PDAG
steps: list # ("insert" or "delete", x, y, set, delta)
evaluations: int # number of operators whose score change was computed
def ges(nodes, local):
"""Greedy equivalence search with the decomposable local score local(v, frozenset)."""
g = PDAG(nodes) # @line L1
steps = []
evals = 0
def s(v, ps):
return local(v, frozenset(ps))
while True: # @line L2
best = None
for x in g.nodes:
for y in g.nodes:
if x == y or g.adjacent(x, y):
continue
na = g.nb[y] & g.adj(x)
t0 = sorted(g.nb[y] - g.adj(x), key=str)
for k in range(len(t0) + 1):
for t in itertools.combinations(t0, k): # @line L3
t = set(t)
if not is_clique(g, na | t) or not blocks_semi_directed(g, y, x, na | t): # @line L4
continue
evals += 1
base = na | t | g.pa[y]
delta = s(y, base | {x}) - s(y, base) # @line L5
if best is None or delta > best[0]:
best = (delta, x, y, t)
if best is None or best[0] <= 0: # @line L6
break
delta, x, y, t = best
h = g.copy()
h.add_arrow(x, y)
for u in t:
h.orient(u, y)
g = cpdag_of_dag(g.nodes, consistent_extension(h)) # @line L7
steps.append(("insert", x, y, t, delta))
while True: # @line L8
best = None
for x in g.nodes:
for y in g.nodes:
if x == y or not (x in g.pa[y] or x in g.nb[y]):
continue
na = g.nb[y] & g.adj(x)
h0 = sorted(na, key=str)
for k in range(len(h0) + 1):
for hs in itertools.combinations(h0, k): # @line L9
hs = set(hs)
if not is_clique(g, na - hs): # @line L10
continue
evals += 1
base = (na - hs) | g.pa[y]
delta = s(y, base - {x}) - s(y, base | {x}) # @line L11
if best is None or delta > best[0]:
best = (delta, x, y, hs)
if best is None or best[0] <= 0: # @line L12
break
delta, x, y, hs = best
h = g.copy()
h.remove(x, y)
for u in hs:
if u in h.nb[y]:
h.orient(y, u)
if u in h.nb[x]:
h.orient(x, u)
g = cpdag_of_dag(g.nodes, consistent_extension(h)) # @line L13
steps.append(("delete", x, y, hs, delta))
return GESResult(g, steps, evals) # @line L14
# ---------------------------------------------------------------------------
# Gaussian BIC score
def conditional_variance(cov, v, ps):
"""Var(v | ps) = cov[v][v] - cov[v,P] cov[P,P]^-1 cov[P,v], by elimination.
Works with floats or with exact fractions."""
ps = list(ps)
k = len(ps)
a = [[cov[p][q] for q in ps] + [cov[p][v]] for p in ps]
for i in range(k):
piv = max(range(i, k), key=lambda r: abs(a[r][i]))
a[i], a[piv] = a[piv], a[i]
for r in range(i + 1, k):
f = a[r][i] / a[i][i]
for c in range(i, k + 1):
a[r][c] -= f * a[i][c]
beta = [0] * k
for i in reversed(range(k)):
beta[i] = (a[i][k] - sum(a[i][j] * beta[j] for j in range(i + 1, k))) / a[i][i]
return cov[v][v] - sum(cov[v][p] * b for p, b in zip(ps, beta))
def gaussian_bic(cov, n_samples):
"""local(v, P) = -(N/2) log Var(v | P) - (|P|/2) log N, with a cache."""
cache = {}
half_log_n = 0.5 * math.log(n_samples)
def local(v, ps):
key = (v, ps)
if key not in cache:
var = conditional_variance(cov, v, sorted(ps, key=str))
cache[key] = -0.5 * n_samples * math.log(var) - half_log_n * len(ps)
return cache[key]
return local
def sem_covariance(nodes, weights):
"""Exact covariance of X_v = sum_p w[p, v] X_p + e_v with unit noise
variances; weights maps (p, v) to a Fraction and nodes is a topological order."""
cov = {u: {} for u in nodes}
for i, v in enumerate(nodes):
pas = [(p, w) for (p, c), w in weights.items() if c == v]
for u in nodes[:i]:
cov[u][v] = cov[v][u] = sum((w * cov[p][u] for p, w in pas), Fraction(0))
cov[v][v] = Fraction(1) + sum((w1 * w2 * cov[p1][p2] for p1, w1 in pas for p2, w2 in pas), Fraction(0))
return cov
def sample_covariance(rows, nodes):
n = len(rows)
means = {v: sum(r[v] for r in rows) / n for v in nodes}
return {u: {v: sum((r[u] - means[u]) * (r[v] - means[v]) for r in rows) / n for v in nodes} for u in nodes}
def sample_sem(nodes, weights, n, rng):
rows = []
for _ in range(n):
x = {}
for v in nodes:
x[v] = rng.gauss(0.0, 1.0) + sum(float(w) * x[p] for (p, c), w in weights.items() if c == v)
rows.append(x)
return rows
if __name__ == "__main__":
nodes = ["A", "B", "C", "D", "E"]
w = {("A", "B"): Fraction(4, 5), ("A", "C"): Fraction(7, 10), ("B", "D"): Fraction(3, 5),
("C", "D"): Fraction(3, 5), ("D", "E"): Fraction(9, 10)}
res = ges(nodes, gaussian_bic(sem_covariance(nodes, w), 1000))
for st in res.steps:
print(st[0], st[1], st[2], sorted(st[3]), round(st[4], 2))
print(res.cpdag.edges(), res.evaluations)
test_greedy_equivalence_search.py 284 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/greedy-equivalence-search/. The authors are listed in prov/08T080.jsonl.
import itertools
import random
from fractions import Fraction
from greedy_equivalence_search import (
conditional_variance, consistent_extension, cpdag_of_dag, gaussian_bic, ges,
sample_covariance, sample_sem, sem_covariance,
)
EXAMPLE_NODES = ["A", "B", "C", "D", "E"]
EXAMPLE_WEIGHTS = {("A", "B"): Fraction(4, 5), ("A", "C"): Fraction(7, 10), ("B", "D"): Fraction(3, 5),
("C", "D"): Fraction(3, 5), ("D", "E"): Fraction(9, 10)}
EXAMPLE_DAG = {"A": set(), "B": {"A"}, "C": {"A"}, "D": {"B", "C"}, "E": {"D"}}
# ---------------------------------------------------------------------------
# The large-sample limit of the Gaussian BIC, with exact fractions.
#
# local(v, P) = -(N/2) log Var(v | P) - (|P|/2) log N. For N large enough,
# a difference of two such scores is positive exactly when the ratio of the
# variances is above 1, or equal to 1 with fewer parents. Limit and Delta
# encode this order exactly.
class Delta:
def __init__(self, ratio, params):
self.ratio, self.params = ratio, params
def __gt__(self, other):
if isinstance(other, int):
other = Delta(Fraction(1), 0)
return (self.ratio, self.params) > (other.ratio, other.params)
def __le__(self, other):
return not self > other
class Limit:
def __init__(self, var, k):
self.var, self.k = var, k
def __sub__(self, other):
# (-log var1, -k1) - (-log var2, -k2) = (log(var2 / var1), k2 - k1)
return Delta(other.var / self.var, other.k - self.k)
def limit_score(cov):
cache = {}
def local(v, ps):
if (v, ps) not in cache:
cache[(v, ps)] = Limit(conditional_variance(cov, v, sorted(ps)), len(ps))
return cache[(v, ps)]
return local
def limit_total(local, nodes, parents):
prod, k = Fraction(1), 0
for v in nodes:
s = local(v, frozenset(parents[v]))
prod *= s.var
k += s.k
return -prod, -k # larger is better
# ---------------------------------------------------------------------------
# Helpers
def all_dags(nodes):
pairs = list(itertools.combinations(nodes, 2))
for choice in itertools.product((0, 1, 2), repeat=len(pairs)):
parents = {v: set() for v in nodes}
for (u, v), c in zip(pairs, choice):
if c == 1:
parents[v].add(u)
elif c == 2:
parents[u].add(v)
if topological_order(nodes, parents) is not None:
yield parents
def topological_order(nodes, parents):
order, left = [], set(nodes)
while left:
free = [v for v in sorted(left) if not (parents[v] & left)]
if not free:
return None
order.append(free[0])
left.discard(free[0])
return order
def random_weights(rng, parents):
w = {}
for v in sorted(parents): # sorted: set order of strings varies between runs
for p in sorted(parents[v]):
# Many distinct values, so that exact cancellations of paths
# (unfaithful models) are unlikely.
w[(p, v)] = Fraction(rng.randint(300, 1000), 1000) * rng.choice((1, -1))
return w
def dsep(parents, a, b, s):
keep, stack = {a, b} | s, [a, b, *s]
while stack:
v = stack.pop()
for p in parents[v]:
if p not in keep:
keep.add(p)
stack.append(p)
nb = {v: set() for v in keep}
for v in keep:
for p in parents[v]:
nb[v].add(p)
nb[p].add(v)
for p, q in itertools.combinations(parents[v], 2):
nb[p].add(q)
nb[q].add(p)
seen, stack = {a}, [a]
while stack:
v = stack.pop()
if v == b:
return False
for w in nb[v]:
if w not in seen and w not in s:
seen.add(w)
stack.append(w)
return True
def key(g):
arrows, lines = g.edges()
return tuple(arrows), tuple(lines)
def class_key(nodes, parents):
return key(cpdag_of_dag(nodes, parents))
# ---------------------------------------------------------------------------
# Tests
def test_worked_example():
res = ges(EXAMPLE_NODES, gaussian_bic(sem_covariance(EXAMPLE_NODES, EXAMPLE_WEIGHTS), 1000))
kinds = [(k, x, y, sorted(t)) for k, x, y, t, _ in res.steps]
assert kinds == [("insert", "D", "E", []), ("insert", "B", "D", []), ("insert", "D", "C", []),
("insert", "A", "B", []), ("insert", "C", "A", ["B"]), ("insert", "B", "C", []),
("delete", "B", "C", ["D"])]
assert key(res.cpdag) == class_key(EXAMPLE_NODES, EXAMPLE_DAG)
assert res.evaluations == 150
def test_local_optimum_at_smaller_sample_size():
# With the same exact covariance but N = 500, the forward phase stops with
# the collider at A, and the true class has a higher score.
cov = sem_covariance(EXAMPLE_NODES, EXAMPLE_WEIGHTS)
local = gaussian_bic(cov, 500)
res = ges(EXAMPLE_NODES, local)
assert res.cpdag.edges() == ([("B", "A"), ("C", "A")], [("B", "D"), ("C", "D"), ("D", "E")])
ext = consistent_extension(res.cpdag)
got = sum(local(v, frozenset(ext[v])) for v in EXAMPLE_NODES)
true = sum(local(v, frozenset(EXAMPLE_DAG[v])) for v in EXAMPLE_NODES)
assert true > got + 1.9
prod = Fraction(1)
for v in EXAMPLE_NODES:
prod *= conditional_variance(cov, v, sorted(ext[v]))
assert prod == Fraction(3086174, 3061875) # the true class has product 1
def test_cpdag_and_extension_round_trip():
nodes = list("ABCD")
for parents in all_dags(nodes):
g = cpdag_of_dag(nodes, parents)
ext = consistent_extension(g)
assert ext is not None and class_key(nodes, ext) == key(g)
def test_score_equivalence_exact():
# Equivalent DAGs have the same product of conditional variances, exactly.
rng = random.Random(3)
nodes = list("ABCD")
full = {v: set(nodes[:i]) for i, v in enumerate(nodes)}
cov = sem_covariance(nodes, random_weights(rng, full))
products = {}
for parents in all_dags(nodes):
prod = Fraction(1)
for v in nodes:
prod *= conditional_variance(cov, v, sorted(parents[v]))
products.setdefault(class_key(nodes, parents), set()).add(prod)
assert len(products) == 185
assert all(len(p) == 1 for p in products.values())
def test_local_consistency_of_limit_score():
rng = random.Random(11)
nodes = list("ABCD")
for parents in itertools.islice(all_dags(nodes), 0, 543, 5):
cov = sem_covariance(topological_order(nodes, parents), random_weights(rng, parents))
local = limit_score(cov)
for x, y in itertools.permutations(nodes, 2):
rest = [v for v in nodes if v not in (x, y)]
for k in range(len(rest) + 1):
for p in itertools.combinations(rest, k):
delta = local(y, frozenset(p) | {x}) - local(y, frozenset(p))
assert (delta > 0) == (not dsep(parents, x, y, set(p)))
def check_all_dags(nodes, seed):
rng = random.Random(seed)
dags = list(all_dags(nodes))
for truth in dags:
cov = sem_covariance(topological_order(nodes, truth), random_weights(rng, truth))
local = limit_score(cov)
res = ges(nodes, local)
best = max(dags, key=lambda d: limit_total(local, nodes, d))
assert key(res.cpdag) == class_key(nodes, best)
assert key(res.cpdag) == class_key(nodes, truth)
return len(dags)
def test_every_dag_on_three_nodes_against_exhaustive_search():
assert check_all_dags(list("ABC"), 1) == 25
def test_every_dag_on_four_nodes_against_exhaustive_search():
assert check_all_dags(list("ABCD"), 2) == 543
def test_float_bic_at_large_n_on_four_nodes():
# With the float BIC at N = 10^6, GES still finds the best class over all
# 543 DAGs. It can differ from the truth when a partial correlation is so
# small that the penalty wins; that is a property of the score.
rng = random.Random(4)
nodes = list("ABCD")
dags = list(all_dags(nodes))
agree_truth = 0
for truth in dags:
cov = sem_covariance(topological_order(nodes, truth), random_weights(rng, truth))
local = gaussian_bic(cov, 10 ** 6)
res = ges(nodes, local)
best = max(dags, key=lambda d: sum(local(v, frozenset(d[v])) for v in nodes))
assert key(res.cpdag) == class_key(nodes, best)
agree_truth += key(res.cpdag) == class_key(nodes, truth)
assert agree_truth == 537 # measured: 6 of the 543 models lose one weak edge
def test_random_dags_on_six_nodes():
rng = random.Random(6)
nodes = list("ABCDEF")
for _ in range(30):
order = nodes[:]
rng.shuffle(order)
parents = {v: set() for v in nodes}
for i, j in itertools.combinations(range(6), 2):
if rng.random() < 0.4:
parents[order[j]].add(order[i])
cov = sem_covariance(order, random_weights(rng, parents))
res = ges(nodes, limit_score(cov))
assert key(res.cpdag) == class_key(nodes, parents)
def test_empty_graph_best_case():
nodes = list("ABCDE")
cov = {u: {v: Fraction(int(u == v)) for v in nodes} for u in nodes}
res = ges(nodes, gaussian_bic(cov, 1000))
assert res.steps == [] and res.evaluations == 5 * 4
def test_finite_samples_success_rate():
# Measured, not proved: 50 data sets of size 2000 from the example model.
ok = 0
truth = class_key(EXAMPLE_NODES, EXAMPLE_DAG)
for seed in range(50):
rng = random.Random(seed)
rows = sample_sem(EXAMPLE_NODES, EXAMPLE_WEIGHTS, 2000, rng)
res = ges(EXAMPLE_NODES, gaussian_bic(sample_covariance(rows, EXAMPLE_NODES), 2000))
ok += key(res.cpdag) == truth
assert ok == 40
History
Meek conjectured that if every independence of a DAG also holds in a DAG , then can be reached from by covered edge reversals and single edge additions, and he proposed a two-phase greedy search that would be optimal in the large-sample limit if the conjecture held. Chickering (1995) had shown that equivalent DAGs are joined by covered edge reversals. In 2002 Chickering proved Meek's conjecture and gave the Insert and Delete operators on CPDAGs with their validity tests and local score changes, which made the search, called GES, practical. Dor and Tarsi (1992) gave the extension procedure that GES uses after each step.
References
- David Maxwell Chickering, Optimal structure identification with greedy search, Journal of Machine Learning Research 3, 2002, pp. 507 to 554 (with an erratum on the Dor and Tarsi procedure), The whole paper (the Insert and Delete operators with their validity tests and score changes, the proof of Meek's conjecture, and the large-sample optimality of GES)
- David Maxwell Chickering, A transformational characterization of equivalent Bayesian network structures, Proceedings of the 11th Conference on Uncertainty in Artificial Intelligence (UAI 1995), Morgan Kaufmann, pp. 87 to 98, The whole paper (Markov equivalent DAGs are joined by a sequence of covered edge reversals)
- Dorit Dor and Michael Tarsi, A simple algorithm to construct a consistent extension of a partially oriented graph, Technical Report R-185, Cognitive Systems Laboratory, UCLA, October 1992, The whole report (the consistent extension procedure used after each operator)
- Christopher Meek, Causal inference and causal explanation with background knowledge, Proceedings of the 11th Conference on Uncertainty in Artificial Intelligence (UAI 1995), Morgan Kaufmann, pp. 403 to 410, The whole paper (the orientation rules that turn a DAG pattern into its CPDAG)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 08T080 Edit this page History Report an error Markdown