Causal discovery II: functional models, continuous optimization and invariance
Functional restrictions can distinguish causal structures with identical independences. Study LiNGAM, additive noise, smooth acyclicity in NOTEARS, benchmark scale sensitivity, and invariant causal prediction.
After this lesson you can
- Prove linear direction identification under non-Gaussian independent noise.
- Implement DirectLiNGAM and additive-noise direction diagnostics with HSIC.
- Derive NOTEARS acyclicity and implement augmented-Lagrangian optimization.
- Diagnose benchmark varsortability and the effect of standardization.
- Implement invariant causal prediction across environments.
Before you start
Two variables, two stories
A record relates queue size to latency. If all you know is that both variables are dependent, and share a skeleton and have no distinguishing independence. The previous lesson left direction unresolved. Can distribution shape or changes across environments reveal more?
Yes, with additional mechanism assumptions. Functional causal identifiability uses restrictions on functions and noise to distinguish some structures sharing independences. We build linear non-Gaussian models, additive-noise models, a continuous acyclicity constraint, and an invariant-predictor search. Each answer depends on its assumptions: a computed arrow is not itself an intervention.
Residual asymmetry
Assume , with , positive finite variances, and . If both sources are Gaussian, inverse regression also has a residual independent of : the joint distribution is Gaussian and uncorrelated residual implies independence. In that family bivariate observation does not identify direction.
If either independent source is non-Gaussian, the inverse linear additive model cannot have an independent residual under those conditions. The proof uses Darmois–Skitovich and appears in the exercises. With finite data estimate both regressions and test dependence: a large p-value does not prove independence, and near-Gaussian noise may yield little power.
The proof’s idea is that and inverse residual are two combinations of the same independent sources. Inverse independence requires ; with positive variances both source coefficients in are nonzero. Darmois–Skitovich then forces both shared sources to be Gaussian. The argument fails if or a source is degenerate, and does not itself rule out a nonlinear inverse function.
The additive-noise model generalizes the equation to , with . Many regular choices do not admit an inverse representation of the same form, but non-Gaussian exceptions exist. For example, if are independent unit-rate exponentials, , and , ratio is independent of sum . Thus and also
with inverse noise independent of . Non-Gaussianity alone does not guarantee identification across all nonlinear additive models. See conditions and exceptions in Peters and colleagues.
Post-nonlinear models allow under additional assumptions, including suitable invertibility and regularity of ; their identifiability also has exceptions. Trying an arbitrary flexible regressor does not justify assigning causality to the direction that fits best.
LiNGAM y DirectLiNGAM
In LiNGAM, variables satisfy
where a causal order makes triangular. Errors have positive variance, are mutually independent and non-Gaussian; linearity, acyclicity, and absence of relevant latent confounding are assumed. These assumptions permit ICA to recover the mixing matrix up to source permutation and scale. Acyclic structure and diagonal normalization help resolve ambiguities and obtain ; a sample fit does not verify assumptions.
DirectLiNGAM seeks a root: in the population an exogenous variable is independent of residuals obtained by regressing it out of the other variables under the method’s conditions. It then removes its contribution and repeats on residuals. The lab uses Hyvärinen and Smith’s entropy approximation, equation 3, to order variables and ordinary regression for coefficients; the reference library may use different regularization. Near-Gaussianity weakens statistical signal even when exact non-Gaussianity satisfies the theoretical assumption. See LiNGAM and DirectLiNGAM.
Order and edges are different results. An estimated order fixes which variables may precede each node, but regression on all predecessors can retain small nonzero coefficients due to noise. Further selection or regularization changes the final graph and must be evaluated separately. An omitted common cause can correlate errors and destroy the root-identification property.
Kernel-based dependence
An independence test can use HSIC. Given Gram matrices and , one biased statistic is
With suitable kernels, the population version distinguishes independence from dependence; bandwidth and calibration matter. A permutation test compares the observed value with values from permuting one variable. Cells and figure use as denominator instead of ; this rescales the shown statistic but not permutation order or its p-value. In the lab regressors train on one sample and residuals are evaluated on another. Even so, estimated residuals may contain fit error: the p-value diagnoses the chosen procedure, not a universally exact causal-direction test. If both directions or neither are rejected, report ambiguity.
The Tübingen CauseEffectPairs repository collects real pairs with reference directions that may contain errors. Pair 0001 relates altitude and mean temperature at 349 stations; its proposed reference is altitude to temperature. It is an observational example, not a randomized trial or evaluation of the entire collection.
NOTEARS: acyclicity as a smooth equality
A matrix represents when . NOTEARS proposes the constraint
It is exact in real arithmetic. Since is nonnegative, sums weights of closed walks of length . Expanding the exponential yields nonnegative terms. A DAG has no closed walks and gives ; a directed cycle with nonzero weights contributes a strictly positive term. Consequently, if and only if the graph is acyclic.
To derive the gradient use and :
For two loopless nodes, if weights are and , . The surface is zero on both axes: removing either arrow breaks the cycle.
Squared loss can be combined with and an augmented Lagrangian . A common implementation splits into nonnegative variables for the L1 norm, uses L-BFGS-B on each subproblem, and updates multiplier and penalty. The problem remains nonconvex. At feasible points , so standard regularity cannot simply be invoked. With finite numerical tolerance and threshold, check cycles after optimization; small is not proof of an exact DAG. See Zheng and colleagues and Ng and colleagues.
Numerical precision is especially important near zero: and can be nearly equal, so subtraction loses digits. A threshold may remove one cycle edge but can also remove a real relation or retain another cycle. The lab separately reports the continuous pre-threshold constraint, remaining edges after thresholding, and an acyclicity traversal.
Nonlinear variants change mechanism parameterization and cost, but do not turn numerical output into a causal guarantee. Examine convergence, constraints, threshold selection, and unit sensitivity.
When variance gives accidental clues
Varsortability measures how often marginal variance tends to increase along causal paths in a simulated DAG. It is not invariant to units: multiplying a variable by a constant changes variance without changing causal relations.
In the code convention of Reisach and colleagues, for each length count endpoint pairs connected by at least one path of that length, scoring 1 if variance increases, 0 if it decreases, and 1/2 for a tie. Multiple paths with the same endpoints and length count once; a pair reachable at different lengths appears for each length. With no paths the ratio is undefined. After exact standardization all variances tie and this convention gives 1/2.
Increasing variance can let a heuristic order a benchmark without solving the general causal problem. Standardization removes that specific clue but does not guarantee NOTEARS or another method worsens on every dataset. The figure and lab calculate both scales on the same sample and show actual results.
Invariance across environments
Invariant causal prediction seeks predictor subsets for which the conditional outcome distribution remains stable across environments. If parents of are observed, its mechanism does not change, interventions do not alter that mechanism, and tests control error under model assumptions, the parent set is one invariant candidate.
ICP tests every subset and intersects those not rejected. Under method conditions the intersection is conservative: with corresponding coverage it excludes variables outside the parent set. It can be smaller than the true set or even empty if environments do not distinguish alternatives; failure to reject does not prove invariance. Direct intervention on , unobserved confounding, or mechanism change can break the guarantee. See Peters, Bühlmann and Meinshausen.
The guarantee’s logic is simple: if the true parent set is among candidates and its test does not reject it, the intersection of all unrejected sets is contained within it. Thus a false parent can appear in the intersection only when at least the true parent set is rejected. That inclusion is an error guarantee under test assumptions, not a promise of power or complete parent recovery. If the parent set itself is not considered, the argument no longer applies.
Comparing only marginal residual distributions may be insufficient. If , and are independent standard normals and , the marginal distribution of is equal across both environments, but the conditional slope changes sign. For a linear Gaussian model the lab tests coefficients and error variances with a stated correction; outside that family it needs other tools and assumptions.
The connection to IRM is the search for regularities maintained across environments. An invariant empirical optimum does not automatically identify parents or guarantee robustness to every future change. Likewise, screening variables with Lasso before ICP can remove a parent and break the guarantee unless the causal set’s retention among candidates is justified.
Lab
Experiments separate training and evaluation where appropriate. Simulated data offer known truth for measuring errors; libraries and the real pair provide comparisons, not universal validation of assumptions.
DirectLiNGAM and residuals
Regressions studying direction are fitted on data distinct from those used for HSIC. The entropy approximation finds an order; coefficients are then fitted by least squares. Permutation tests of estimated residuals are exploratory.
import numpy as np
def standardize(x):
z = np.asarray(x, dtype=float)
sd = z.std()
if not np.isfinite(sd) or sd < 1e-12:
raise ValueError('Se necesita varianza positiva')
return (z - z.mean()) / sd
def residual(y, x):
x, y = np.asarray(x), np.asarray(y)
x, y = x-x.mean(), y-y.mean()
variance = np.mean(x*x)
if variance < 1e-12:
raise ValueError('Regresor de varianza nula')
return y - np.mean(x*y)/variance*x
def entropy_approx(u):
"""Aproximación de máxima entropía usada por la opción pwling de lingam."""
u = standardize(u)
logcosh = np.logaddexp(u, -u) - np.log(2.)
return (.5*(1+np.log(2*np.pi)) - 79.047*(logcosh.mean()-.37457)**2
- 7.4129*np.mean(u*np.exp(-.5*u*u))**2)
def direct_lingam(data):
"""DirectLiNGAM pwling sin selección de aristas; OLS sobre el orden."""
original = np.asarray(data, dtype=float)
if original.ndim != 2 or not np.isfinite(original).all():
raise ValueError('Se necesita una matriz finita')
centered = original - original.mean(axis=0)
work = centered.copy()
remaining = list(range(work.shape[1]))
order, diagnostics = [], []
while remaining:
scores = {}
for i in remaining:
xi = standardize(work[:,i])
score = 0.
for j in remaining:
if j == i:
continue
xj = standardize(work[:,j])
ri_j = residual(xi,xj)
rj_i = residual(xj,xi)
delta = entropy_approx(xj)+entropy_approx(ri_j)-entropy_approx(xi)-entropy_approx(rj_i)
score += min(0.,delta)**2
scores[i] = score
chosen = min(scores, key=scores.get)
diagnostics.append(scores)
order.append(chosen)
for j in remaining:
if j != chosen:
work[:,j] = residual(work[:,j],work[:,chosen])
remaining.remove(chosen)
weights = np.zeros((work.shape[1],work.shape[1]))
for k, node in enumerate(order):
parents = order[:k]
if parents:
weights[node,parents] = np.linalg.lstsq(centered[:,parents],centered[:,node],rcond=None)[0]
return order, weights, diagnosticsdef gaussian_kernel(values):
x = np.asarray(values, dtype=float).ravel()
squared = (x[:,None]-x[None,:])**2
positive = squared[squared > 0]
if not len(positive):
raise ValueError('El kernel necesita variación')
width2 = np.median(positive)
return np.exp(-squared/(2*width2))
def center_kernel(k):
return k-k.mean(axis=0)[None,:]-k.mean(axis=1)[:,None]+k.mean()
def hsic_permutation(x, y, permutations=99, seed=2726):
"""HSIC sesgado centrado, kernel RBF y permutaciones Monte Carlo."""
k, l = center_kernel(gaussian_kernel(x)), center_kernel(gaussian_kernel(y))
n = len(k)
statistic = float(np.sum(k*l)/(n-1)**2)
random = np.random.default_rng(seed)
greater = 0
for _ in range(permutations):
idx = random.permutation(n)
permuted = np.sum(k*l[np.ix_(idx,idx)])/(n-1)**2
greater += int(permuted >= statistic)
return statistic, (greater+1)/(permutations+1)def line_data(random, n, non_gaussian):
if non_gaussian:
x = random.uniform(-np.sqrt(3),np.sqrt(3),n)
e = random.uniform(-np.sqrt(3),np.sqrt(3),n)
else:
x, e = random.normal(size=n), random.normal(size=n)
return x, 1.3*x+e
def fit_slope(x,y):
x0,y0=x-x.mean(),y-y.mean()
slope=float(x0@y0/(x0@x0))
return float(y.mean()-slope*x.mean()),slope
def compare_directions(non_gaussian, seed=27261):
random=np.random.default_rng(seed)
xtrain,ytrain=line_data(random,2000,non_gaussian)
x,y=line_data(random,300,non_gaussian)
ax,bx=fit_slope(xtrain,ytrain)
ay,by=fit_slope(ytrain,xtrain)
forward=hsic_permutation(x,y-(ax+bx*x),seed=27262)
backward=hsic_permutation(y,x-(ay+by*y),seed=27263)
# Para comparar, también se usa el coeficiente causal conocido como oráculo.
oracle=hsic_permutation(x,y-1.3*x,seed=27264)
return dict(forward=forward,backward=backward,oracle=oracle,slopes=(bx,by))
def four_variable_data(n=5000, seed=2726):
random=np.random.default_rng(seed)
x0=random.laplace(size=n)/np.sqrt(2)
x1=.8*x0+random.uniform(-np.sqrt(3),np.sqrt(3),n)
x2=-.65*x0+.7*x1+random.exponential(size=n)-1
x3=.9*x1-.6*x2+random.logistic(size=n)*np.sqrt(3)/np.pi
return np.column_stack([x0,x1,x2,x3])data=four_variable_data()
order,weights,scores=direct_lingam(data)
print('DirectLiNGAM pwling, n=5000, semilla 2726')
print('Orden estimado:',order)
print('Coeficientes OLS por orden, fila destino y columna origen:')
print(np.round(weights,3))
print('Puntuaciones de candidatas:',[{k:round(float(v),6) for k,v in s.items()} for s in scores])uniforme=compare_directions(True)
print('Uniforme:', uniforme)
print('Las permutaciones de residuos ajustados son un diagnóstico exploratorio.')gaussiano=compare_directions(False)
print('Gaussiano:',gaussiano)
print('En la población gaussiana ambos sentidos lineales admiten residuos independientes.')Now use a nonlinear ANM and fit a radial-basis-function expansion separately in each direction. Knots and scales are chosen using training data only; HSIC uses independent observations. Permutations remain exploratory because regressors are estimated.
# ANM no lineal: dos regresores RBF ajustados en entrenamiento independiente.
# Reutiliza hsic_permutation de la celda anterior y no depende de bibliotecas extra.
def anm_data(rng, n):
x = rng.uniform(-2., 2., n)
y = x + .8*x*x + rng.normal(0., .35, n)
return x, y
def rbf_fit_predict(x_train, y_train, x_test, knots=15, ridge=.001):
# Anchos y nudos se aprenden solo en entrenamiento.
mean, scale = x_train.mean(), x_train.std()
if scale < 1e-12:
raise ValueError('El predictor necesita variación')
z = (x_train-mean)/scale
z_test = (x_test-mean)/scale
centers = np.quantile(z, np.linspace(.02,.98,knots))
width = max(float((np.quantile(z,.75)-np.quantile(z,.25))/2), 1e-6)
def design(values):
return np.column_stack([np.ones(len(values)), values,
np.exp(-.5*((values[:,None]-centers)/width)**2)])
X = design(z)
penalty = ridge*np.eye(X.shape[1])
penalty[0,0] = 0.
coef = np.linalg.solve(X.T@X+penalty, X.T@y_train)
return design(z_test)@coef
rng_anm = np.random.default_rng(272650)
x_train, y_train = anm_data(rng_anm, 2000)
x_eval, y_eval = anm_data(rng_anm, 300)
r_forward = y_eval-rbf_fit_predict(x_train,y_train,x_eval)
r_backward = x_eval-rbf_fit_predict(y_train,x_train,y_eval)
forward = hsic_permutation(x_eval,r_forward,permutations=99,seed=272651)
backward = hsic_permutation(y_eval,r_backward,permutations=99,seed=272652)
print('ANM no lineal: Y=X+0,8X²+ε; 2000 ajustes y 300 evaluaciones')
print('HSIC, p exploratorio, X hacia Y:',forward)
print('HSIC, p exploratorio, Y hacia X:',backward)
print('Regresores RBF con nudos de entrenamiento; no se prueba independencia por no rechazar.')
print('El error de ajuste limita la calibración de las permutaciones; no prueba causalidad.')NOTEARS and variances
The function solves L-BFGS-B subproblems with split variables. It also returns before thresholding and the actual penalty used. It reports a subproblem convergence failure; reaching penalty or iteration limits yields an approximate result. Check acyclicity after thresholding instead of assuming it. Directed SHD in these cells counts a reversal as one operation.
import numpy as np
from scipy.linalg import expm
from scipy.optimize import minimize
from numbers import Real, Integral
def h_y_gradiente(W):
E = expm(W*W)
return float(np.trace(E)-len(W)), 2*W*E.T
def notears_linear(X, lambda1=0.02, max_iter=30, h_tol=1e-8,
rho_max=1e12, umbral=0.3):
"""NOTEARS cuadrático con desdoblamiento L1; devuelve matriz y diagnósticos."""
parametros = (lambda1, h_tol, rho_max, umbral)
if (any(not isinstance(v, Real) or isinstance(v, bool) or not np.isfinite(v)
for v in parametros) or not isinstance(max_iter, Integral) or
isinstance(max_iter, bool)):
raise ValueError('Los parámetros deben ser números reales finitos')
X = np.asarray(X, dtype=float)
if (X.ndim != 2 or X.shape[0] < 3 or X.shape[1] < 2 or
not np.isfinite(X).all() or lambda1 < 0 or
max_iter < 1 or not 0 <= umbral or h_tol <= 0 or rho_max <= 1):
raise ValueError('Datos o parámetros inválidos')
X = X-X.mean(axis=0)
n,d = X.shape
if np.any(X.var(axis=0) <= 1e-14):
raise ValueError('Una variable no tiene variación')
def unpack(z):
return (z[:d*d]-z[d*d:]).reshape(d,d)
def objetivo(z, rho, alpha):
W = unpack(z)
residual = X-X@W
loss = .5*np.sum(residual*residual)/n
grad_loss = -(X.T@residual)/n
h, grad_h = h_y_gradiente(W)
value = loss+lambda1*z.sum()+alpha*h+.5*rho*h*h
grad = grad_loss+(alpha+rho*h)*grad_h
return value, np.concatenate([(grad+lambda1).ravel(),(-grad+lambda1).ravel()])
bounds = [(0,0) if i==j else (0,None) for _ in range(2)
for i in range(d) for j in range(d)]
z = np.zeros(2*d*d)
rho, alpha, h_prev = 1., 0., np.inf
historial = []
for _ in range(max_iter):
limite = False
while rho < rho_max:
opt = minimize(objetivo, z, args=(rho,alpha), jac=True,
method='L-BFGS-B', bounds=bounds,
options={'maxiter': 800, 'maxls': 60, 'ftol': 1e-10,
'gtol': 1e-7})
if not opt.success:
raise RuntimeError('El subproblema no convergió: '+str(opt.message))
nuevo = opt.x
h_nuevo, _ = h_y_gradiente(unpack(nuevo))
if h_nuevo > .25*h_prev:
if rho*10 >= rho_max:
limite = True
break
rho *= 10
else:
break
z, h_prev = nuevo, h_nuevo
alpha += rho*h_prev
historial.append((float(h_prev),float(rho)))
if h_prev <= h_tol or limite:
break
W = unpack(z)
W[np.abs(W)<umbral] = 0
return W, historial
def es_dag(W):
"""Comprueba ciclos dirigidos sin modificar la matriz."""
E = np.abs(W)>0
pendientes = set(range(len(W)))
while pendientes:
listos = {j for j in pendientes if not any(E[i,j] for i in pendientes)}
if not listos:
return False
pendientes -= listos
return True
def shd_dirigida(W, verdad):
"""Ausencias, extras e inversiones con coste uno."""
E, T = np.abs(W)>0, np.abs(verdad)>0
coste = 0
for i in range(len(W)):
for j in range(i+1,len(W)):
actual = 1 if E[i,j] else -1 if E[j,i] else 0
real = 1 if T[i,j] else -1 if T[j,i] else 0
if E[i,j] and E[j,i]:
coste += 1 + int(real == 0)
else:
coste += int(actual != real)
return costerng = np.random.default_rng(2726)
W0 = np.zeros((3,3))
W0[0,1], W0[1,2] = 1.5, -1.2
X = np.zeros((800,3))
for j in range(3):
X[:,j] = X@W0[:,j] + rng.normal(size=len(X))
out,hist = notears_linear(X)
print('Matriz estimada:', np.round(out,3))
print('SHD dirigida:', shd_dirigida(out,W0), '| DAG:', es_dag(out))
print('h antes de umbral y rho optimizado:', hist[-1], '| iteraciones:',len(hist))def varsortability(W, variances, tolerance=1e-10):
"""Convención de caminos por longitud del código original; empates valen 1/2."""
W = np.asarray(W, float)
v = np.asarray(variances, float)
if W.ndim != 2 or W.shape[0] != W.shape[1] or v.shape != (len(W),):
raise ValueError('Dimensiones incompatibles')
if not np.isfinite(W).all() or not np.isfinite(v).all() or (v < 0).any():
raise ValueError('Valores inválidos')
edges = np.abs(W) > 0
reachable = edges.copy()
score = total = 0.
for _ in range(1,len(W)):
for i,j in zip(*np.nonzero(reachable)):
delta = v[j]-v[i]
score += .5 if abs(delta)<=tolerance else float(delta>0)
total += 1
reachable = reachable @ edges
return score/total if total else np.nan
variancias = np.array([1., 1+2**2, 1+.2**2*5])
cadena = np.array([[0,2,0],[0,0,.2],[0,0,0.]])
valor = varsortability(cadena, variancias)
unidades = varsortability(cadena, variancias*np.array([9,1,1]))
tipificadas = varsortability(cadena, np.ones(3))
print('Varianzas:', variancias, '| varsortability:', valor)
print('Al cambiar unidades de X1:', unidades, '| estandarizadas:', tipificadas)
assert np.allclose([valor,unidades,tipificadas],[2/3,0,.5])# Las fuentes y sus desviaciones son explícitas; se usa la misma muestra en ambas escalas.
N,d=400,10
W=np.zeros((d,d))
for i in range(d):
for j in range(i+1,d):
if rng.random() < .17:
W[i,j]=rng.choice([-1,1])*rng.uniform(.7,1.3)
X10=np.zeros((N,d))
for j in range(d):
X10[:,j]=X10@W[:,j]+rng.normal(0,rng.uniform(.7,1.3),N)
Z=(X10-X10.mean(axis=0))/X10.std(axis=0)
print('Nodos:', d, '| observaciones:', N, '| aristas verdaderas:',np.count_nonzero(W))
print('Varsortability bruta:',round(varsortability(W,X10.var(axis=0)),4))
print('Varsortability estandarizada:',round(varsortability(W,Z.var(axis=0)),4))out_bruto,hist_bruto=notears_linear(X10,lambda1=.02,max_iter=6,rho_max=1e6)
print('Bruto: SHD dirigida',shd_dirigida(out_bruto,W),'| DAG',es_dag(out_bruto),
'| h antes de umbral',hist_bruto[-1][0],'| iteraciones',len(hist_bruto))out_tipificado,hist_tipificado=notears_linear(Z,lambda1=.02,max_iter=6,rho_max=1e6)
print('Estandarizado: SHD dirigida',shd_dirigida(out_tipificado,W),
'| DAG',es_dag(out_tipificado),'| h antes de umbral',hist_tipificado[-1][0],
'| iteraciones',len(hist_tipificado))
print('Un único experimento no establece que estandarizar siempre empeore el método.')Reproduce the ten-variable figure
The figure uses another explicit sample with permuted labels. The order-based method receives the true skeleton as an oracle: it compares orientations and does not learn adjacencies. These cells reconstruct its DGP and rerun NOTEARS on both scales; thresholded output is checked for cycles.
# El mismo mecanismo y semilla que la figura: etiquetas permutadas y 600 filas.
rng_figura = np.random.default_rng(2726)
d_figura, n_figura = 10, 600
orden_figura = rng_figura.permutation(d_figura)
W_figura = np.zeros((d_figura,d_figura))
for i in range(d_figura):
for j in range(i+1,d_figura):
if rng_figura.random() < .27:
W_figura[orden_figura[i],orden_figura[j]] = rng_figura.choice([-1,1])*rng_figura.uniform(.8,1.2)
X_figura = rng_figura.normal(size=(n_figura,d_figura))
for j in orden_figura:
X_figura[:,j] += X_figura @ W_figura[:,j]
X_figura -= X_figura.mean(axis=0)
Z_figura = X_figura / X_figura.std(axis=0)
def orientar_con_esqueleto_conocido(W, variances):
# El esqueleto verdadero es un oráculo; empate resuelto por índice.
rank_order = np.lexsort((np.arange(len(W)),np.round(variances,9)))
rank = np.empty(len(W),dtype=int)
rank[rank_order] = np.arange(len(W))
estimado = np.zeros_like(W)
for i in range(len(W)):
for j in range(i+1,len(W)):
if W[i,j] or W[j,i]:
a,b = (i,j) if rank[i] < rank[j] else (j,i)
estimado[a,b] = 1.
return estimado
alcance = np.abs(W_figura)>0
pares_por_longitud = 0
for _ in range(1,d_figura):
pares_por_longitud += int(alcance.sum())
alcance = alcance @ (np.abs(W_figura)>0)
print('Figura: observaciones',n_figura,'aristas verdaderas',np.count_nonzero(W_figura),
'| parejas por longitud',pares_por_longitud)
print('Aristas verdaderas:',np.argwhere(W_figura!=0).tolist())note_figura, hist_figura = notears_linear(X_figura, lambda1=.02, max_iter=6,
rho_max=1e6, umbral=.3)
oracle_figura = orientar_con_esqueleto_conocido(W_figura, X_figura.var(axis=0))
print('Varianzas originales:',np.round(X_figura.var(axis=0),8))
print('Aristas orden con oráculo:',np.argwhere(oracle_figura!=0).tolist())
print('Aristas NOTEARS original:',np.argwhere(note_figura!=0).tolist())
print('Figura original: varsortability',varsortability(W_figura,X_figura.var(axis=0),1e-9),
'| SHD orden con oráculo',shd_dirigida(oracle_figura,W_figura),
'| SHD NOTEARS',shd_dirigida(note_figura,W_figura),
'| DAG',es_dag(note_figura),'| h antes de umbral',hist_figura[-1][0])note_figura_z, hist_figura_z = notears_linear(Z_figura, lambda1=.02, max_iter=6,
rho_max=1e6, umbral=.3)
oracle_figura_z = orientar_con_esqueleto_conocido(W_figura, Z_figura.var(axis=0))
print('Varianzas estandarizadas:',np.round(Z_figura.var(axis=0),8))
print('Aristas orden con oráculo:',np.argwhere(oracle_figura_z!=0).tolist())
print('Aristas NOTEARS estandarizado:',np.argwhere(note_figura_z!=0).tolist())
print('Figura estandarizada: varsortability',varsortability(W_figura,Z_figura.var(axis=0),1e-9),
'| SHD orden con oráculo',shd_dirigida(oracle_figura_z,W_figura),
'| SHD NOTEARS',shd_dirigida(note_figura_z,W_figura),
'| DAG',es_dag(note_figura_z),'| h antes de umbral',hist_figura_z[-1][0])ICP without prior screening
The following test assumes normal, independent, exogenous errors, common variance under the null, and full-rank matrices. It combines coefficient and variance F-tests by Bonferroni without assuming those tests are independent. It evaluates all subsets before comparison with Lasso, so Lasso selection does not remove potential parents in advance.
import numpy as np
from itertools import combinations
from scipy.special import betainc
def cola_f(valor, grados1, grados2):
"""Cola superior F sin restar una CDF próxima a uno."""
if grados1 <= 0 or grados2 <= 0 or valor < 0:
raise ValueError('F o grados de libertad inválidos')
return float(betainc(grados2/2, grados1/2,
grados2/(grados2+grados1*valor)))
def invariancia_lineal(X, y, entorno, subconjunto):
"""H0: misma media lineal condicional y misma varianza gaussiana.
Prueba global F para coeficientes y comparaciones F de varianza contra
el primer entorno. Bonferroni combina ambas familias a nivel alfa.
"""
X = np.asarray(X, dtype=float)
y = np.asarray(y, dtype=float)
entorno = np.asarray(entorno)
if X.ndim != 2 or y.shape != (len(X),) or entorno.shape != (len(X),):
raise ValueError('Dimensiones incompatibles')
if not np.isfinite(X).all() or not np.isfinite(y).all():
raise ValueError('Datos no finitos')
S = tuple(subconjunto)
if len(set(S)) != len(S) or any(j < 0 or j >= X.shape[1] for j in S):
raise ValueError('Subconjunto inválido')
niveles = np.unique(entorno)
if len(niveles) < 2:
raise ValueError('Se requieren al menos dos entornos')
matriz = np.column_stack([np.ones(len(X)), X[:, S]])
p = matriz.shape[1]
rss, df = [], []
for nivel in niveles:
mask = entorno == nivel
A, z = matriz[mask], y[mask]
if len(z) <= p or np.linalg.matrix_rank(A) != p:
raise ValueError('Entorno sin rango o grados de libertad')
beta = np.linalg.lstsq(A, z, rcond=None)[0]
resid = z-A@beta
rss.append(float(resid@resid))
df.append(len(z)-p)
rss, df = np.array(rss), np.array(df)
if np.any(rss <= 0):
raise ValueError('Varianza residual degenerada')
beta_global = np.linalg.lstsq(matriz, y, rcond=None)[0]
residual_global = y-matriz@beta_global
rss_global = float(residual_global@residual_global)
gl1, gl2 = (len(niveles)-1)*p, int(df.sum())
fcoef = max(0., (rss_global-rss.sum())/gl1/(rss.sum()/gl2))
pcoef = cola_f(fcoef, gl1, gl2)
pvars = []
for j in range(1, len(niveles)):
fvar = (rss[j]/df[j])/(rss[0]/df[0])
pvar = min(1., 2*min(cola_f(fvar, int(df[j]), int(df[0])),
cola_f(1/fvar, int(df[0]), int(df[j]))))
pvars.append(pvar)
pvar_ajustado = min(1., len(pvars)*min(pvars))
p_total = min(1., 2*min(pcoef, pvar_ajustado))
return {'coeficientes': pcoef, 'varianzas': pvar_ajustado, 'conjunto': p_total}
def icp_lineal(X, y, entorno, alfa=.05):
if not 0 < alfa < 1:
raise ValueError('Alfa debe estar entre cero y uno')
d = X.shape[1]
resultados = {}
for k in range(d+1):
for S in combinations(range(d), k):
resultados[S] = invariancia_lineal(X, y, entorno, S)
aceptados = [S for S, prueba in resultados.items() if prueba['conjunto'] > alfa]
interseccion = set.intersection(*(set(S) for S in aceptados)) if aceptados else set()
return sorted(interseccion), aceptados, resultados
print('ICP lineal: F global de coeficientes y F de varianzas, con Bonferroni.')def generar_icp(n_por_entorno, seed, informativos):
"""X0,X1 causan Y; X2 es descendiente de Y; E indica tres entornos."""
rng = np.random.default_rng(seed)
entorno = np.repeat(np.arange(3), n_por_entorno)
base = rng.normal(size=(3*n_por_entorno, 4))
if informativos:
mu0 = np.array([-2., .2, 2.])[entorno]
mu1 = np.array([1.5, -1.5, .5])[entorno]
cambio_desc = np.array([-2., 2., 0.])[entorno]
else:
mu0 = mu1 = cambio_desc = np.zeros(len(entorno))
x0 = base[:, 0] + mu0
x1 = base[:, 1] + mu1
y = 1.4*x0 - x1 + base[:, 2]
x2 = .8*y + base[:, 3] + cambio_desc
return np.column_stack([x0, x1, x2]), y, entorno
X_info, y_info, e_info = generar_icp(300, 272601, True)
X_debil, y_debil, e_debil = generar_icp(300, 272602, False)
print('Dos muestras independientes:', X_info.shape, X_debil.shape,
'; padres verdaderos: 0, 1; el nodo 2 es descendiente de Y.')seleccion_info, aceptados_info, pruebas_info = icp_lineal(X_info, y_info, e_info)
print('Entornos informativos:')
def formato_p(p):
return f'{p:.3g}' if p > 0 else 'por debajo de la precisión numérica'
for S, valores in pruebas_info.items():
print(S, 'p coef:', formato_p(valores['coeficientes']),
'p var corregido:', formato_p(valores['varianzas']),
'p combinado:', formato_p(valores['conjunto']))
print('Subconjuntos no rechazados:', aceptados_info)
print('Intersección:', seleccion_info)
print('Aceptar un conjunto no prueba que sea causal ni que el test tenga potencia perfecta.')seleccion_debil, aceptados_debil, pruebas_debil = icp_lineal(X_debil, y_debil, e_debil)
print('Entornos sin cambios de distribución:')
print('Subconjuntos no rechazados:', aceptados_debil)
print('Intersección:', seleccion_debil)
print('Un resultado vacío es compatible con padres existentes y entornos poco informativos.')
print('Si todos los conjuntos se rechazaran, se devuelve vacío por convenio.')def lasso_coordenadas(X, y, alfa=.02, tolerancia=1e-10, max_iter=5000):
"""Lasso sobre variables estandarizadas: ||y-Xb||²/(2n)+alfa||b||1."""
media = X.mean(axis=0)
escala = X.std(axis=0)
if np.any(escala <= 0):
raise ValueError('Variable constante')
Z = (X-media)/escala
respuesta = y-y.mean()
n,p = Z.shape
beta = np.zeros(p)
resid = respuesta.copy()
for it in range(max_iter):
antiguo = beta.copy()
for j in range(p):
resid += Z[:,j]*beta[j]
correl = float(Z[:,j] @ resid/n)
beta[j] = np.sign(correl)*max(abs(correl)-alfa,0)
resid -= Z[:,j]*beta[j]
if np.max(np.abs(beta-antiguo)) < tolerancia:
return beta, it+1
raise RuntimeError('Lasso no convergió')
beta_lasso, iteraciones_lasso = lasso_coordenadas(X_info, y_info)
seleccion_lasso = [int(j) for j in np.flatnonzero(abs(beta_lasso)>1e-8)]
print('Lasso conjunto, coeficientes en escala tipificada:', np.round(beta_lasso, 4))
print('Variables Lasso:', seleccion_lasso, '| intersección ICP:', seleccion_info)
print('Las comparaciones son de esta muestra; el descendiente 2 no es causa de Y.')
print('No se usa Lasso para cribar ICP: excluir un padre invalidaría la garantía de inclusión.')# Este chequeo prueba solo el nivel del contraste del conjunto parental bajo
# el DGP especificado; no prueba cobertura en modelos no gaussianos.
replicas = 300
rechazos = 0
for seed in range(273000, 273000+replicas):
Xr, yr, er = generar_icp(75, seed, True)
rechazos += invariancia_lineal(Xr, yr, er, (0, 1))['conjunto'] <= .05
tasa = rechazos/replicas
ee_mc = np.sqrt(tasa*(1-tasa)/replicas)
print('Rechazos del conjunto parental bajo la nula:', rechazos, '/', replicas,
'| tasa:', round(tasa, 4), '| EE Monte Carlo aproximado:', round(ee_mc, 4))
print('La cota de nivel procede de las hipótesis del contraste y Bonferroni, no de estas réplicas.')Local comparison and Tübingen data
Prepare a local environment compatible with versions listed in the cell. Compare DirectLiNGAM with PC in simulation and download Tübingen pair 0001 with its integrity hash. PC uses Fisher Z, whose calibration needs justification with non-Gaussian data. The real-pair test is exploratory: stations may be spatially correlated and residuals depend on an estimated fit.
"""Python local, sin archivos de Oryon Learn.
Requiere Python 3.11 y un entorno aislado con:
pip install 'numpy<2' 'scipy==1.13.1' 'scikit-learn>=1.6,<1.8' \
'lingam==1.13.0' 'causal-learn==0.1.4.8'
Descarga el par original de Tübingen. Los contrastes son exploratorios: los
parámetros de regresión son estimados y las estaciones pueden ser dependientes.
"""
from hashlib import sha256
from io import BytesIO
from urllib.request import urlopen
import numpy as np
from lingam import DirectLiNGAM
from causallearn.search.ConstraintBased.PC import pc
def synthetic_data(n=5000, seed=2726):
random=np.random.default_rng(seed)
x0=random.laplace(size=n)/np.sqrt(2)
x1=.8*x0+random.uniform(-np.sqrt(3),np.sqrt(3),n)
x2=-.65*x0+.7*x1+random.exponential(size=n)-1
x3=.9*x1-.6*x2+random.logistic(size=n)*np.sqrt(3)/np.pi
return np.column_stack([x0,x1,x2,x3])
def kernel(v):
d=(v[:,None]-v[None,:])**2
dpos=d[d>0]
if not len(dpos):
raise ValueError('Se necesita variación en ambos argumentos')
return np.exp(-d/(2*np.median(dpos)))
def centered(k):
return k-k.mean(axis=0)[None,:]-k.mean(axis=1)[:,None]+k.mean()
def hsic_test(x,y,permutations=99,seed=272601):
k,l=centered(kernel(x)),centered(kernel(y))
n=len(x)
observed=np.sum(k*l)/(n-1)**2
rng=np.random.default_rng(seed)
count=0
for _ in range(permutations):
ix=rng.permutation(n)
count+=np.sum(k*l[np.ix_(ix,ix)])/(n-1)**2 >= observed
return float(observed),float((count+1)/(permutations+1))
def quadratic_residual(train_x,train_y,test_x,test_y):
# Estandariza con parámetros de entrenamiento y ajusta un polinomio fijo.
mx,sx=train_x.mean(),train_x.std()
my,sy=train_y.mean(),train_y.std()
if min(sx,sy)<=0:
raise ValueError('Escala degenerada')
tx=(train_x-mx)/sx
ty=(train_y-my)/sy
vx=(test_x-mx)/sx
vy=(test_y-my)/sy
design=np.column_stack([np.ones(len(tx)),tx,tx*tx])
coef=np.linalg.lstsq(design,ty,rcond=None)[0]
residual=vy-np.column_stack([np.ones(len(vx)),vx,vx*vx])@coef
return vx,residual
data=synthetic_data()
model=DirectLiNGAM(measure='pwling').fit(data)
cg=pc(data,alpha=.01,stable=True,show_progress=False,verbose=False)
print('Simulación lineal con errores no gaussianos independientes, n=5000')
print('DirectLiNGAM, orden estimado:',model.causal_order_)
print('DirectLiNGAM, matriz con lasso adaptativo, fila destino y columna origen:')
print(np.round(model.adjacency_matrix_,3))
print('PC, matriz de extremos: −1/−1 es no dirigida; −1/+1 es cola/punta:')
print(cg.G.graph)
print('PC usa Fisher Z; sin gaussianidad debe justificarse su calibración.')
url='https://webdav.tuebingen.mpg.de/cause-effect/pair0001.txt'
with urlopen(url,timeout=30) as response:
payload=response.read()
fingerprint=sha256(payload).hexdigest()
if fingerprint!='98f2c6117515788f5c23bf03aeddb496bcee748b3bfd701909a9051e3dbbd9c9':
raise ValueError('Los datos originales cambiaron; revisa la fuente y el hash')
pair=np.loadtxt(BytesIO(payload))
if pair.shape!=(349,2) or not np.isfinite(pair).all():
raise ValueError('Formato inesperado del par 0001')
indices=np.random.default_rng(272600).permutation(len(pair))
train,test=pair[indices[:209]],pair[indices[209:]]
print('\nTübingen par 0001, 349 estaciones; entrenamiento 209 y evaluación 140')
print('Fuente:',url,'SHA-256:',fingerprint)
for source,target,name in [(0,1,'altitud → temperatura'),(1,0,'temperatura → altitud')]:
x,r=quadratic_residual(train[:,source],train[:,target],test[:,source],test[:,target])
stat,p=hsic_test(x,r,seed=272601+source)
print(name,'HSIC',round(stat,7),'p exploratorio',round(p,3))
print('La ficha de Tübingen propone altitud → temperatura; es una referencia, no una verdad experimental absoluta.')
print('Las estaciones pueden ser espacialmente dependientes y los residuos usan parámetros ajustados:')
print('las permutaciones no garantizan un contraste causal exacto ni justifican elegir por sí solas una dirección.')npm run lab and open the connection link.Exercises
Step 1 of 3. Which coefficient b is required for the inverse residual to be independent of Y?
Step 1 of 3. What does a diagonal term of Mᵏ represent?
def h_y_gradiente(W):
"""Devuelve h(W) y su gradiente."""
raise NotImplementedError
def notears_linear(X, lambda1=.02):
"""Devuelve W umbralizada y el historial de h y rho."""
raise NotImplementedErrorCheck the numeric exercise and ties after solving it:
var_ejercicio = np.array([4., .5**2*4+1, .5**2*2+1.5])
grafo_ejercicio = np.array([[0,.5,0],[0,0,.5],[0,0,0.]])
resultado_ejercicio = varsortability(grafo_ejercicio,var_ejercicio)
print('Varianzas:',var_ejercicio,'| varsortability:',resultado_ejercicio)
assert np.allclose(var_ejercicio,[4,2,2])
assert abs(resultado_ejercicio-1/6)<1e-12