Algorithmresearch
LiNGAM
Also called linear non-Gaussian acyclic model.
Identifies the full causal DAG of a linear model with non-Gaussian noise, by independent component analysis or by DirectLiNGAM's search for exogenous variables.
- Time
- Θ(n^3 m + n^4) worst · best
- Space
- Θ(n m) extra
- Where
- m = the number of samples; n = the number of variables
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Shohei Shimizu, Patrik O. Hoyer, Aapo Hyvärinen, Antti Kerminen, 2006
LiNGAM, the linear non-Gaussian acyclic model, is a structural causal model in which each variable is a linear function of its causes plus an independent error, the causes form a directed acyclic graph, and the errors are not Gaussian. The same name is used for the methods that learn the graph from data. Methods such as the PC algorithm and greedy equivalence search use only conditional independences, so they can return only a Markov equivalence class, and they cannot orient for two variables. LiNGAM uses the shape of the distribution, not only its covariances. Shimizu, Hoyer, Hyvärinen and Kerminen (2006) proved that this identifies the whole DAG and its weights, and found it with independent component analysis. DirectLiNGAM (Shimizu et al. 2011), the version on this page, finds the causes one at a time instead.
In plain words
Suppose one quantity causes another, and each also has its own random push from outside. If the pushes follow the bell curve, the data look the same in both directions, and no method can tell cause from effect. If the pushes have any other shape, the directions differ. When you predict the effect from the cause, what is left over is the effect's own push, and it has nothing to do with the cause. When you predict the cause from the effect, what is left over still depends on the effect, even if it is uncorrelated with it. DirectLiNGAM uses this to find a variable that nothing else causes, removes its influence from all other variables, and repeats. This gives an order from causes to effects. Regression along this order then gives the arrows and their strengths.
The problem
The data are samples of variables from the model
where means the edge , the graph of has no directed cycle, and the components of are independent, non-Gaussian, with mean 0 and finite positive variance. There are no hidden common causes: every dependence between errors would have to come from such a cause, and the model forbids it. A causal order is an order of the variables in which every edge points forward, a topological order of the graph. A variable is exogenous when it has no parent, so it equals its own error.
The task is to estimate a causal order and . Then is a linear mixture of independent non-Gaussian sources, which is the model of independent component analysis, with the extra structure that is triangular up to a permutation.
The algorithm
For two centred variables, the residual of on is , the error of the least-squares fit. Hyvärinen and Smith (2013) compare the two directions between standardized and by the log-likelihood ratio
where is the differential entropy of a standardized variable, with standardized too. favours . The implementation uses their approximation with , and ; the first term is the entropy of a standard Gaussian, the largest entropy at unit variance.
DirectLiNGAM(X)- 1
U ← the variables of X, sorted by name; K ← the empty list - 2
while U has more than one variable do - 3
S(i) ← 0 for each i in U - 4
for each i in U do - 5
for each j in U after i do compute R(i, j) - 6
S(i) ← S(i) + min(0, R(i, j))^2; S(j) ← S(j) + min(0, -R(i, j))^2 - 7
m ← the i in U with the smallest S(i), ties by name; append m to K - 8
for each j in U other than m do x_j ← the standardized residual of x_j on x_m - 9
remove m from U - 10
append the last variable of U to K - 11
B ← least squares of each x_j on the variables before j in K, with the original data; set every |b| < τ to 0 - 12
return K and B
The score is the total evidence against being a cause of the others: it grows only when some pair favours the direction into . An exogenous variable should have a score near 0. Line L8 removes the influence of the chosen variable, and the residuals follow a LiNGAM model with the same weights on the remaining variables, so the loop can repeat. The implementation uses . The original DirectLiNGAM measures the dependence between and its residuals with a kernel independence measure instead of ; the structure of the loop is the same.
Example
Take , , , , with , , , , and errors uniform on , so of unit variance. The implementation draws samples with seed 1 and gives the columns in the order , so the input order tells nothing.
In round 1, all four ratios of are positive: , , , . So , while every other variable loses at least one pair, for example and . DirectLiNGAM takes and replaces by their residuals on .
| round | scores | chosen |
|---|---|---|
| 1 | : 0, : 0.0106, : 0.0088, : 0.0023, : 0.0032 | |
| 2 | , : both below 0.00001, : 0.0051, : 0.0043 | |
| 3 | : below 0.00001, : 0.0071, : 0.0042 | |
| 4 | : below 0.00001, : 0.0076 |
The order is . After round 1, and are both exogenous in the residual model, so the order of and is free, and both orders are causal orders. Line L11 gives the weights : 0.83, : 0.71, : 0.61, : 0.63, : 0.91, and sets the five other coefficients, all below 0.1 in size, to 0. This is the true graph with all five edges oriented. On the same data, PC or GES could orient only and .
Why the direction shows. Take and , where and are independent and each is or with probability . The forward residual is independent of . The backward regression of on has slope , and its residual is uncorrelated with . But and never happen together, while each has probability , so and are dependent. The tests check this with exact fractions.
Why Gaussian errors fail. With Gaussian errors, uncorrelated means independent. Then every order of the variables gives a linear model with independent errors and the same covariance matrix, so all orders fit equally well. The tests check this exactly for all 6 orders of a model on three variables.
Correctness
The proof is in proofs/correctness.md. It is partial. It cites the Darmois-Skitovich theorem (Darmois 1953, Skitovich 1953): if two linear combinations of independent variables are independent, then every variable that appears in both is Gaussian. From it the proof shows:
- Identifiability. If , both with acyclic graphs and independent errors, and at most one component of is Gaussian, then . The matrix maps to ; Darmois-Skitovich makes it a scaled permutation, and acyclicity with the unit diagonal makes it the identity.
- Exogenous variables. An exogenous variable is independent of all its residuals, and a variable with a parent has a dependent residual: the one of its last parent in a causal order.
- Residual model. Regressing out an exogenous variable leaves a model with the same weights and errors on the other variables.
- DirectLiNGAM with an exact test. If line L7 chooses a variable that is independent of its residuals, the loop runs rounds, is a causal order, and line L11 without the threshold returns in the population.
Not proved: that the approximate score of line L6 picks an exogenous variable. Hyvärinen and Smith (2013) show that the exact likelihood ratio has the right sign for two variables in the population (cited). For the approximation and for finite samples the rates are measured, see Pitfalls.
Proof: A linear acyclic model with independent non-Gaussian errors is identified by the distribution of x, and DirectLiNGAM with an exact independence test returns a causal order and the weights; the Darmois-Skitovich theorem is citedpartial
What is proved and what is cited. This file proves that the weight matrix is identified (two such models with the same distribution of have the same ), and that DirectLiNGAM finds a causal order and when it can decide exactly whether two variables are independent. It cites the Darmois-Skitovich theorem. It does not prove that the implementation's choice step, which compares approximate entropies instead of testing independence, picks an exogenous variable; Hyvärinen and Smith (2013) show this for the exact likelihood ratio of two variables, and the tests measure it for the approximation.
Setting. The model is on variables. is the weight matrix of a DAG: means the edge , and the graph has no directed cycle, so some ordering of the variables (a causal order) makes strictly lower triangular. The errors are independent, with mean 0 and finite positive variances. Then is invertible (it is unit triangular in a causal order), and with . The entry is the total effect of on ; , and unless is an ancestor of or .
Theorem (Darmois 1953, Skitovich 1953; cited). Let be independent random variables and , . If and are independent, then every with is Gaussian.
Theorem 1 (identifiability). Let , where both and are weight matrices of DAGs, and both have independent components with finite positive variances, and at most one component of is Gaussian. Then and .
Proof. From and we get with , an invertible matrix. Take two rows . The components and are independent, so by Darmois-Skitovich for every with non-Gaussian. So each column of a non-Gaussian has at most one non-zero entry, and since is invertible, exactly one, in a row . Two such columns cannot share a row: they would both be multiples of the same unit vector, and would be singular.
If all are non-Gaussian, is a bijection and for a permutation matrix and an invertible diagonal . If exactly one is Gaussian, the other columns fill distinct rows, and the remaining row has its only non-zero entry in column . Suppose for some . Independent components with finite variances are uncorrelated, but , since the other terms vanish. This contradiction shows that column also has one non-zero entry, and again .
So every row of is a non-zero multiple of a row of , for a permutation . The diagonal entry gives , so for every . If , this entry is , an edge . If were not the identity, it would have a cycle of length at least 2, and these edges would form a directed cycle in the graph of . So is the identity, for all , , and .
With two or more Gaussian errors the theorem fails: the tests show that every order of three Gaussian variables gives a linear model with independent errors and the same covariance.
For the rest of the file, every is non-Gaussian. For variables , the residual of on is . A variable is exogenous when it has no parent.
Lemma 2 (an exogenous variable is independent of its residuals). If is exogenous, then is independent of for every .
Proof. . Write . Then , so , a function of errors other than , and so independent of .
Lemma 3 (a variable with a parent has a dependent residual). If has a parent, then and are dependent for some .
Proof. Fix a causal order and let be the parent of that comes last in it. The other parents of come before , so they are not descendants of , and does not appear in them. In the error appears only through , so . Take and , so . The variable does not contain , because is not a descendant of . If , then has the coefficient in and in . If , then , and has the coefficient in and in . In both cases one non-Gaussian error has non-zero coefficients in both variables, so by Darmois-Skitovich they are dependent.
Lemma 4 (removing an exogenous variable). Let be exogenous and for . Then . So the residuals follow the same kind of model on the other variables, with the same weights and errors.
Proof. By Lemma 2, . The total effects satisfy , because every directed path from to ends with one edge into (and ). So
and subtracting gives the claim.
Theorem 5 (DirectLiNGAM with an exact test). Replace the choice of line L7 by: choose a variable in that is independent of all its residuals , . Then such an always exists, the loop ends after rounds, is a causal order, and the regressions of line L11 without the threshold return .
Proof. By induction on the rounds, the current variables follow a model of the theorem's kind on , with the weights of restricted to : this holds at the start, and Lemma 4 keeps it after line L8. A DAG has a node with no parent, so by Lemma 2 a valid choice exists, and by Lemma 3 every valid choice has no parent among the current variables. In the restricted model, has no parent in , so every edge of into starts at a variable that left earlier, and no edge goes from a later variable into . Each round removes one variable, so there are rounds, and is a causal order. In line L11, the regression of on the variables before it is with independent of those variables, which are not descendants of . As the covariance matrix of the variables before is positive definite, the least-squares coefficients are unique and equal the .
What the implementation does instead. Line L7 of the implementation chooses the that minimizes , where is the log-likelihood ratio of the models and , computed with an approximation of the differential entropy. Hyvärinen and Smith (2013) show that with exact entropies in the population when is the true model of two variables (cited). The approximation has no such guarantee, and the threshold of line L11 drops small weights. The tests measure the result: with uniform errors the order was right in all 50 random models on five variables with 1000 samples.
Complexity
Round has variables and computes one ratio for each pair, and each ratio costs for two regressions and four entropies. Summed over the rounds this is . Line L8 adds in total. In line L11, the regression of the -th variable needs for its covariances and to solve the system, so in total. The work does not depend on the data, so the best and worst cases agree. The standardized copies of the data take space. A kernel independence measure, as in the original DirectLiNGAM, costs far more per pair than the entropy approximation.
Properties
- Full orientation. The output is one DAG, not an equivalence class. This is possible only because the errors are not Gaussian.
- Weights included. Line L11 gives the strength of each edge, so total effects follow from .
- Deterministic. Ties in line L7 are broken by name, and the result does not depend on the order of the input columns.
- Consistent, not exact. The identifiability theorem holds for the population. On a finite sample the order can be wrong, and the threshold can drop weak edges.
- No conditional independence tests. Unlike PC, it never tests conditional independence, and it needs no faithfulness assumption for the order.
Variants and improvements
- ICA-LiNGAM. The first method (Shimizu et al. 2006) runs ICA, for example FastICA, to estimate up to the order and scale of its rows. It permutes the rows so that no diagonal entry is near 0, divides each row by its diagonal entry, sets , and permutes the variables to make as near to strictly lower triangular as possible. Comon (1994) showed that ICA identifies the mixing matrix up to permutation and scale when at most one source is Gaussian. ICA can stop at a local optimum and depends on its start; DirectLiNGAM avoids this.
- Kernel measure. DirectLiNGAM as published measures independence with a kernel method, which is slower but uses no entropy approximation.
- Pairwise measures. Hyvärinen and Smith (2013) give the likelihood ratio used here, and other approximations of it.
- Pruning. Instead of a fixed threshold, use the adaptive lasso or tests of the coefficients along the order.
- Extensions. Later work extends LiNGAM to hidden common causes, to time series, and to cyclic models, each with weaker identification results.
When to use it
Use LiNGAM when the relations are close to linear, all common causes are measured, and the errors are clearly not Gaussian, for example skewed, heavy-tailed or bounded. It gives a full DAG where PC or GES leave edges undirected. If the errors look Gaussian, or the data come from sums of many small effects (the central limit theorem makes such errors near Gaussian), use PC or GES and accept the equivalence class. If hidden common causes are likely, use the FCI algorithm or a LiNGAM variant made for them.
Pitfalls
- Gaussian errors. With Gaussian errors the direction is not identified. On two variables with 1000 samples, the implementation found first in 24 of 50 runs, close to a coin flip, against 50 of 50 with uniform errors. On 50 random models with five variables, the order was a causal order in 3 of 50 runs with Gaussian errors, and in 50 of 50 with uniform errors.
- Weak edges. The threshold drops small weights, and sampling noise can keep a spurious one. In the 50 uniform runs, all orders were right, but the set of edges was exactly right in 43. These rates are measured on the implementation, not proved.
- Hidden common causes. A hidden cause of two variables makes their errors dependent, and the model fails. The method still returns a DAG, with no warning.
- Non-linear relations. A non-linear effect leaves residuals that depend on the cause, which can point the arrow the wrong way.
- Weak non-Gaussianity. The signal is in the higher moments. When the errors are nearly Gaussian, many more samples are needed, and the approximate entropy can rank the directions wrongly.
- Measurement error. Noise added to a cause after it acts makes the cause look like an effect, so the order can reverse.
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/lingam/. The authors are listed in prov/YZF859.jsonl.
"""DirectLiNGAM: the causal order of a linear non-Gaussian acyclic model.
The model is x = B x + e, where B is the weight matrix of a DAG and the
components of e are independent and non-Gaussian. DirectLiNGAM (Shimizu et
al. 2011) finds an exogenous variable, regresses it out of the others, and
repeats. To find the exogenous variable this module uses the pairwise
likelihood ratio of Hyvarinen and Smith (2013) with their entropy
approximation, as many implementations do. After the order is known, each
variable is regressed on the earlier ones and small coefficients are set to 0.
Data are given as a dict: variable name -> list of floats (one per sample).
"""
import math
from typing import NamedTuple
K1, K2, GAMMA = 79.047, 7.4129, 0.37457
class LiNGAMResult(NamedTuple):
order: list # causal order, causes first
b: dict # (cause, effect) -> estimated weight, only kept weights
def mean(u):
return sum(u) / len(u)
def standardize(u):
m = mean(u)
c = [x - m for x in u]
s = math.sqrt(sum(x * x for x in c) / len(c))
return [x / s for x in c]
def residual(xi, xj):
"""Residual of xi after least-squares regression on xj (both centred)."""
b = sum(a * c for a, c in zip(xi, xj)) / sum(c * c for c in xj)
return [a - b * c for a, c in zip(xi, xj)]
def entropy(u):
"""Approximate differential entropy of a standardized sample (Hyvarinen 1998
maximum entropy approximation, constants as in Hyvarinen and Smith 2013)."""
n = len(u)
lc = sum(abs(x) + math.log1p(math.exp(-2 * abs(x))) - math.log(2) for x in u) / n # log cosh
ge = sum(x * math.exp(-x * x / 2) for x in u) / n
return (1 + math.log(2 * math.pi)) / 2 - K1 * (lc - GAMMA) ** 2 - K2 * ge ** 2
def likelihood_ratio(xi, xj):
"""R(i, j): positive when the model xi -> xj fits better than xj -> xi."""
ri_j = standardize(residual(xi, xj))
rj_i = standardize(residual(xj, xi))
return entropy(xj) + entropy(ri_j) - entropy(xi) - entropy(rj_i)
def causal_order(data):
"""The DirectLiNGAM search for a causal order."""
x = {v: standardize(col) for v, col in data.items()}
left = sorted(x) # @line L1
order = []
while len(left) > 1: # @line L2
score = {i: 0.0 for i in left} # @line L3
for a in range(len(left)): # @line L4
for c in range(a + 1, len(left)): # @line L5
i, j = left[a], left[c]
r = likelihood_ratio(x[i], x[j])
score[i] += min(0.0, r) ** 2 # @line L6
score[j] += min(0.0, -r) ** 2
m = min(left, key=lambda v: (score[v], v)) # @line L7
order.append(m)
for j in left:
if j != m:
x[j] = standardize(residual(x[j], x[m])) # @line L8
left.remove(m) # @line L9
order.extend(left) # @line L10
return order
def solve(a, rhs):
"""Solve a small linear system by Gaussian elimination with pivoting."""
k = len(rhs)
m = [row[:] + [r] for row, r in zip(a, rhs)]
for i in range(k):
p = max(range(i, k), key=lambda r: abs(m[r][i]))
m[i], m[p] = m[p], m[i]
for r in range(i + 1, k):
f = m[r][i] / m[i][i]
for c in range(i, k + 1):
m[r][c] -= f * m[i][c]
out = [0.0] * k
for i in reversed(range(k)):
out[i] = (m[i][k] - sum(m[i][j] * out[j] for j in range(i + 1, k))) / m[i][i]
return out
def fit_weights(data, order, threshold=0.1):
"""Least squares of each variable on the earlier ones; drop |b| < threshold."""
cen = {v: [x - mean(col) for x in col] for v, col in data.items()}
def dot(u, w):
return sum(p * q for p, q in zip(u, w)) / len(u)
b = {}
for t, y in enumerate(order):
preds = order[:t]
if not preds:
continue
coef = solve([[dot(cen[p], cen[q]) for q in preds] for p in preds], [dot(cen[p], cen[y]) for p in preds])
for p, c in zip(preds, coef):
if abs(c) >= threshold:
b[(p, y)] = c
return b
def direct_lingam(data, threshold=0.1):
order = causal_order(data)
b = fit_weights(data, order, threshold) # @line L11
return LiNGAMResult(order, b) # @line L12
def simulate(order, weights, n, rng, noise):
"""Samples of x = B x + e; weights maps (cause, effect) -> float, order is
a causal order, noise(rng) draws one error with mean 0 and variance 1."""
data = {v: [] for v in order}
for _ in range(n):
x = {}
for v in order:
x[v] = noise(rng) + sum(w * x[p] for (p, c), w in weights.items() if c == v)
data[v].append(x[v])
return data
def uniform_noise(rng):
return rng.uniform(-math.sqrt(3), math.sqrt(3))
def gaussian_noise(rng):
return rng.gauss(0.0, 1.0)
if __name__ == "__main__":
import random
rng = random.Random(1)
w = {("A", "B"): 0.8, ("A", "C"): 0.7, ("B", "D"): 0.6, ("C", "D"): 0.6, ("D", "E"): 0.9}
data = simulate(["A", "B", "C", "D", "E"], w, 1000, rng, uniform_noise)
# Present the variables in a scrambled order to show the order is found from data.
data = {v: data[v] for v in ["E", "C", "A", "D", "B"]}
res = direct_lingam(data)
print(res.order, {k: round(v, 2) for k, v in sorted(res.b.items())})
test_lingam.py 174 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lingam/. The authors are listed in prov/YZF859.jsonl.
import itertools
import random
from fractions import Fraction
from lingam import direct_lingam, gaussian_noise, simulate, uniform_noise
EX_ORDER = ["A", "B", "C", "D", "E"]
EX_WEIGHTS = {("A", "B"): 0.8, ("A", "C"): 0.7, ("B", "D"): 0.6, ("C", "D"): 0.6, ("D", "E"): 0.9}
def consistent(order, weights):
pos = {v: k for k, v in enumerate(order)}
return all(pos[a] < pos[b] for (a, b) in weights)
def random_model(rng, n, p):
order = [chr(65 + i) for i in range(n)]
rng.shuffle(order)
w = {}
for i, j in itertools.combinations(range(n), 2):
if rng.random() < p:
w[(order[i], order[j])] = rng.uniform(0.5, 1.5) * rng.choice((1, -1))
return order, w
def test_worked_example():
rng = random.Random(1)
data = simulate(EX_ORDER, EX_WEIGHTS, 1000, rng, uniform_noise)
data = {v: data[v] for v in ["E", "C", "A", "D", "B"]}
res = direct_lingam(data)
assert res.order == ["A", "C", "B", "D", "E"]
assert set(res.b) == set(EX_WEIGHTS)
assert all(abs(res.b[k] - w) < 0.05 for k, w in EX_WEIGHTS.items())
def test_two_point_noise_exact():
# x = e1, y = x + e2 with e1, e2 independent and equal to -1 or 1.
# Forward residual e2 is independent of x. The backward regression of x
# on y has slope 1/2; its residual is uncorrelated with y but dependent.
outcomes = [(e1, e2) for e1 in (-1, 1) for e2 in (-1, 1)] # each with probability 1/4
p = Fraction(1, 4)
xs = [(e1, e1 + e2) for e1, e2 in outcomes]
slope = sum(p * x * y for x, y in xs) / sum(p * y * y for x, y in xs)
assert slope == Fraction(1, 2)
pairs = [(x - slope * y, y) for x, y in xs]
assert sum(p * r * y for r, y in pairs) == 0 # uncorrelated
def prob(event):
return sum(p for pr in pairs if event(pr))
joint = prob(lambda t: t[0] == 0 and t[1] == 0)
assert joint == 0 and prob(lambda t: t[0] == 0) * prob(lambda t: t[1] == 0) == Fraction(1, 4)
# Forward: residual y - x = e2 and x = e1 factorize exactly.
for a in (-1, 1):
for b in (-1, 1):
j = sum(p for e1, e2 in outcomes if e1 == a and e2 == b)
assert j == Fraction(1, 2) * Fraction(1, 2)
def test_gaussian_every_order_fits_exactly():
# For a Gaussian model, every order of the variables gives a linear model with
# uncorrelated (so independent) errors and the same covariance.
nodes = ["A", "B", "C"]
w = {("A", "B"): Fraction(4, 5), ("A", "C"): Fraction(-1, 2), ("B", "C"): Fraction(3, 4)}
cov = covariance(nodes, w, {v: Fraction(1) for v in nodes})
for order in itertools.permutations(nodes):
b, var = {}, {}
for t, y in enumerate(order):
preds = list(order[:t])
coef = solve_exact([[cov[p][q] for q in preds] for p in preds], [cov[p][y] for p in preds])
for p, c in zip(preds, coef):
b[(p, y)] = c
var[y] = cov[y][y] - sum(c * cov[p][y] for p, c in zip(preds, coef))
assert covariance(list(order), b, var) == cov
def covariance(order, w, noise_var):
cov = {u: {} for u in order}
for i, v in enumerate(order):
pas = [(p, x) for (p, c), x in w.items() if c == v]
for u in order[:i]:
cov[u][v] = cov[v][u] = sum((x * cov[p][u] for p, x in pas), Fraction(0))
cov[v][v] = noise_var[v] + sum((x1 * x2 * cov[p1][p2] for p1, x1 in pas for p2, x2 in pas), Fraction(0))
return cov
def solve_exact(a, rhs):
k = len(rhs)
m = [row[:] + [r] for row, r in zip(a, rhs)]
for i in range(k):
p = next(r for r in range(i, k) if m[r][i] != 0)
m[i], m[p] = m[p], m[i]
for r in range(i + 1, k):
f = m[r][i] / m[i][i]
for c in range(i, k + 1):
m[r][c] -= f * m[i][c]
out = [Fraction(0)] * k
for i in reversed(range(k)):
out[i] = (m[i][k] - sum(m[i][j] * out[j] for j in range(i + 1, k))) / m[i][i]
return out
def test_residuals_of_a_source_follow_the_same_model():
# Lemma: regress a source m out of every variable; the residuals satisfy
# r_j = sum_{p != m} b_pj r_p + e_j. Checked exactly on coefficient vectors over e.
rng = random.Random(2)
for _ in range(30):
order, wf = random_model(rng, 5, 0.6)
w = {k: Fraction(round(v * 8), 8) or Fraction(1, 8) for k, v in wf.items()}
coef = {}
for v in order:
vec = {v: Fraction(1)}
for (p, c), x in w.items():
if c == v:
for k, a in coef[p].items():
vec[k] = vec.get(k, 0) + x * a
coef[v] = vec
m = order[0]
r = {}
for j in order[1:]:
cjm = coef[j].get(m, 0) # Cov(x_j, x_m) / Var(x_m), unit noise variances
r[j] = {k: a - cjm * coef[m].get(k, 0) for k, a in coef[j].items()}
want = {j: Fraction(1)}
for (p, c), x in w.items():
if c == j and p != m:
for k, a in r[p].items():
want[k] = want.get(k, 0) + x * a
assert {k: a for k, a in r[j].items() if a} == {k: a for k, a in want.items() if a}
def test_two_variables_uniform_noise():
ok = 0
for seed in range(50):
rng = random.Random(seed)
data = simulate(["X", "Y"], {("X", "Y"): 0.8}, 1000, rng, uniform_noise)
ok += direct_lingam({"Y": data["Y"], "X": data["X"]}).order == ["X", "Y"]
assert ok == 50
def test_two_variables_gaussian_noise():
# With Gaussian noise the direction is not identified: about half right.
ok = 0
for seed in range(50):
rng = random.Random(seed)
data = simulate(["X", "Y"], {("X", "Y"): 0.8}, 1000, rng, gaussian_noise)
ok += direct_lingam({"Y": data["Y"], "X": data["X"]}).order == ["X", "Y"]
assert ok == 24 # measured: 24 of 50, close to a coin flip
def test_random_models_uniform_noise():
order_ok = support_ok = 0
for seed in range(50):
rng = random.Random(seed)
order, w = random_model(rng, 5, 0.5)
data = simulate(order, w, 1000, rng, uniform_noise)
res = direct_lingam({v: data[v] for v in sorted(data)})
order_ok += consistent(res.order, w)
support_ok += set(res.b) == set(w)
assert order_ok == 50
assert support_ok == 43
def test_random_models_gaussian_noise():
order_ok = 0
for seed in range(50):
rng = random.Random(seed)
order, w = random_model(rng, 5, 0.5)
data = simulate(order, w, 1000, rng, gaussian_noise)
res = direct_lingam({v: data[v] for v in sorted(data)})
order_ok += consistent(res.order, w)
assert order_ok == 3
History
Darmois (1953) and Skitovich (1953) proved, independently, that two independent linear combinations of independent variables can share only Gaussian variables. Comon (1994) used this to show that independent component analysis identifies its mixing matrix up to permutation and scale when the sources are not Gaussian. In 2006 Shimizu, Hoyer, Hyvärinen and Kerminen applied this to causal discovery: in a linear acyclic model with non-Gaussian errors, the triangular structure of fixes the permutation and scale, so the whole DAG is identified. Their ICA-LiNGAM found it with FastICA. Shimizu and co-authors gave DirectLiNGAM in 2011, which finds exogenous variables one at a time and needs no iterative ICA, and Hyvärinen and Smith (2013) gave the pairwise likelihood ratios that many implementations use.
References
- Shohei Shimizu, Patrik O. Hoyer, Aapo Hyvärinen and Antti Kerminen, A linear non-Gaussian acyclic model for causal discovery, Journal of Machine Learning Research 7, 2006, pp. 2003 to 2030, The whole paper (the model, its identifiability through independent component analysis, and the ICA-LiNGAM algorithm with its permutation and pruning steps)
- Shohei Shimizu, Takanori Inazumi, Yasuhiro Sogawa, Aapo Hyvärinen, Yoshinobu Kawahara, Takashi Washio, Patrik O. Hoyer and Kenneth Bollen, DirectLiNGAM: A direct method for learning a linear non-Gaussian structural equation model, Journal of Machine Learning Research 12, 2011, pp. 1225 to 1248, The whole paper (the lemmas on exogenous variables and residuals, and the DirectLiNGAM algorithm)
- Aapo Hyvärinen and Stephen M. Smith, Pairwise likelihood ratios for estimation of non-Gaussian structural equation models, Journal of Machine Learning Research 14, 2013, pp. 111 to 152, The whole paper (the likelihood ratio of two causal directions and its entropy approximation, used in line L5)
- Pierre Comon, Independent component analysis, a new concept?, Signal Processing 36(3), 1994, pp. 287 to 314, The whole paper (identifiability of the mixing matrix up to permutation and scale when at most one source is Gaussian)
- Georges Darmois, Analyse générale des liaisons stochastiques: étude particulière de l'analyse factorielle linéaire, Revue de l'Institut International de Statistique 21, 1953, pp. 2 to 8, The whole paper (the Darmois half of the Darmois-Skitovich theorem)
- V. P. Skitovich, On a property of the normal distribution, Doklady Akademii Nauk SSSR 89, 1953, pp. 217 to 219 (in Russian), The whole paper (the Skitovich half of the Darmois-Skitovich theorem)
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 YZF859 Edit this page History Report an error Markdown