Counterfactuals, probabilities of causation and mediation
Structural counterfactuals connect alternative worlds using abduction, action, and prediction. Study twin networks, identification limits, probabilities of causation, and natural and controlled mediation effects.
After this lesson you can
- Calculate SCM counterfactuals using abduction, action, and prediction.
- Construct a twin network and examine its counterfactual independences.
- Show observationally and interventionally equivalent models can disagree on counterfactuals.
- Calculate Tian–Pearl bounds for probabilities of necessity and sufficiency.
- Estimate natural direct and indirect effects and discuss mediation assumptions.
Before you start
The incident occurred; what with the patch?
A server suffered an incident and did not receive a patch. Asking what incident rate a patching policy would produce is a population intervention question. Asking whether that same incident would have occurred with the patch requires linking the observed world to another that was never observed. More than a difference in rates is needed: a structure must connect both worlds.
Abduction, action, and prediction
A structural causal model assigns each variable an equation and a joint distribution of exogenous disturbances . The structural counterfactual is the value of after replacing the equation for with , retaining the unit’s same . Given evidence proceed in three steps:
- Abduction: update using the equations and probability model.
- Action: replace the equation for with the hypothetical value; do not change remaining equations or resample a new individual.
- Prediction: propagate values of compatible with the evidence through the intervened model and average if abduction leaves uncertainty.
For example, consider , and . If , and are observed, the equations fix and . Under , and . Seven is the total effect through both paths in this model. If only some variables are observed, evidence may leave a distribution of noise terms rather than one vector.
In discrete models multiple exogenous configurations may explain the same observation. Exact abduction weights them by posterior probability; sampling must condition on evidence and retain the same noise terms under intervention. Rejection with few accepted cases may be inefficient; it does not turn posterior uncertainty into a known individual value.
A network for two worlds
A twin network duplicates endogenous variables: one copy follows factual equations and the other follows intervened equations. Both share the same exogenous variables. Evidence enters the factual copy and replaces the relevant equation in the hypothetical copy. The shared connection lets us calculate, for example, under the specified SCM.
This construction links potential outcomes with structural equations: and use different fixed values of but the same . Twin-network independences are read from the augmented graph and also depend on observed variables; they must not be assumed because copies have different labels. A particular model determines cross-world coupling, but data may not determine that model.
In the preceding linear example, if noises are mutually independent and is nondegenerate, is independent of . Yet and still share even conditioning on : they are not independent because they belong to separate copies. Also knowing fixes by the equation and determines in that model.
Same interventions, another individual history
Counterfactual identification requires all models compatible with available information to answer identically. Let and independent of . In two SCMs, ; in the first and in the second . The factual outcome is .
Both models give and , and the same observational distribution if they use the same distribution of . Yet among treated units with , the probability of is in the first and in the second. Coupling of with changes, not their marginals. The first model satisfies monotonicity ; the second does not.
Monotonicity, independent noises, or an additive-noise structural family can restrict that coupling. These are mechanism assumptions, not general consequences of knowing both interventional distributions. Even when an assumption identifies a population mean, uncertainty can remain about one unit’s counterfactual with partial evidence.
Necessity and sufficiency
For binary , define as outcomes under treatment and control. The probabilities of causation are
PN asks about necessity among treated units with outcome; PS about sufficiency among controls without outcome; PNS about the fraction for whom treatment changes to . Conditions require positive denominators. They are not interchangeable and must be interpreted according to the meaning of .
Let and be identified here by interventions. With only these two marginals, sharp Tian–Pearl PNS bounds are
The lower bound follows because subtracts the harmed type from the benefited type; the upper bound cannot exceed either marginal forming the intersection. Interventional data alone generally do not determine PN or PS conditional on factual treatment.
With compatible observational data from the same population, , and , we also obtain
Data and interventions must be consistent and refer to the same population; otherwise an interval must not be forced. With jointly independent of , PN and PS equal PNS divided by and respectively. In the previous example, if , and , PN and PS lie between and , and PNS between and .
Observational information can also narrow PNS bounds. If and , sharp endpoints with both data sources are
The lab verifies these endpoints using linear programming over the unknown joint distribution of . The program imposes marginals, factual table, and consistency; it does not assume independence between and potential outcomes.
If for every unit, the harmed type disappears and . Monotonicity is a substantive assumption; observing a positive average effect does not verify it. These probabilities inform attribution under a defined model and population; they do not themselves turn a statistical conclusion into a legal or medical decision.
Direct and indirect effects
With mediator , write and for potential outcomes. The controlled direct effect fixes the same value for everyone:
Natural effects instead use the mediator each unit would take under another treatment. One decomposition of the total effect is
One can also first move from to holding fixed, then change with : this gives . Both sums yield the same total, but with interaction their components need not coincide. CDE fixes a chosen value; NDE uses the individual counterfactual distribution or .
For a discrete mediator and prior covariates , one version of Pearl’s mediation formula is
Identification requires consistency, positivity, and no-confounding conditions for treatment–outcome, treatment–mediator, and mediator–outcome given appropriate covariates, together with cross-world independence justifying combination of with . An acyclic SCM with independent noises, observed covariates blocking those confounding paths, and no treatment-affected mediator–outcome confounders provides a sufficient set of conditions. Randomizing alone does not guarantee them. If a mediator confounder is affected by , the simple natural formula may fail even when adjusting observed variables.
Interventional indirect effects replace the individual mediator from another world with a draw from a policy-defined mediator distribution; they change the estimand and may be identified under different assumptions. Semiparametric mediation estimators use outcome and assignment models and may include influence corrections, but robustness properties depend on the specific formulation: they do not replace causal assumptions.
For example, for , let , , and . Assume and where . A score whose expectation is under the true models is
The first residual corrects the outcome model among treated units and reweights their mediator toward the control distribution; the second corrects mediator integration using controls. Replace functions with estimates and average the score; with cross-fitting and regularity conditions, standard errors can be built from its influence. For example, if and are correct, both residuals have mean zero even if other denominator models are incorrect, provided denominators remain bounded away from zero and weights are integrable. The direct effect is minus the identified mean of . Full multiple robustness and inference conditions require specifying the estimator, as in Tchetgen Tchetgen and Shpitser (2012); no combination of statistical models by itself repairs a false causal assumption.
Lab: counterfactuals and mediation
Cells compute exact probabilities from explicit models alongside reproducible simulations. Queries answer within the given SCM; a program computing them does not prove the SCM describes the real system.
Start with exact noise abduction in a fully observed linear SCM; then intervene and propagate.
# Un SCM lineal con variables observadas sin error.
# X=U_X; Z=2X+U_Z; Y=3Z-X+U_Y.
def contrafactual_lineal(x, z, y, x_nuevo):
u_x = x
u_z = z - 2*x
u_y = y - 3*z + x
z_nuevo = 2*x_nuevo + u_z
y_nuevo = 3*z_nuevo - x_nuevo + u_y
return {'ruidos': (u_x, u_z, u_y), 'X': x_nuevo,
'Z': z_nuevo, 'Y': y_nuevo}
observado = (1., 5., 8.)
alternativo = contrafactual_lineal(*observado, 0.)
factual = contrafactual_lineal(*observado, observado[0])
assert alternativo['ruidos'] == (1., 3., -6.)
assert alternativo['Z'] == 3 and alternativo['Y'] == 3
assert (factual['X'], factual['Z'], factual['Y']) == observado
print('Ruidos inferidos:', alternativo['ruidos'])
print('Con do(X=0): Z =', alternativo['Z'], ', Y =', alternativo['Y'])Now build a binary engine with tables and uniform noises. Tables match the probability representation from the SCM lesson; threshold orientation specifies cross-world coupling.
import numpy as np
class SCMContrafactual:
"""SCM binario acíclico, tablas de l11 y ruido uniforme compartido.
specs contiene (nodo, padres, P(nodo=1|padres)) en orden topológico.
reverse contiene pares (nodo, índice de padres): allí se usa U>=1-p
en vez de U<p. Cambia el acoplamiento entre mundos, no las tablas.
Los ruidos de nodos distintos son independientes en este modelo.
"""
def __init__(self, specs, reverse=()):
self.specs, seen = [], set()
for name, parents, probabilities in specs:
parents, prob = tuple(parents), np.asarray(probabilities, float)
if (not isinstance(name,str) or not name or name in seen
or len(set(parents)) != len(parents)
or any(p not in seen for p in parents)
or prob.shape != (2**len(parents),)
or not np.isfinite(prob).all() or np.any((prob<0)|(prob>1))):
raise ValueError('Modelo o tabla inválidos')
self.specs.append((name, parents, prob))
seen.add(name)
if not self.specs:
raise ValueError('El modelo no puede estar vacío')
self.names = tuple(name for name, _, _ in self.specs)
valid = {(name, i) for name, _, probs in self.specs for i in range(len(probs))}
self.reverse = set(reverse)
if not self.reverse <= valid:
raise ValueError('Acoplamiento inverso no reconocido')
def ruido(self, n, seed):
if not isinstance(n, int) or n <= 0:
raise ValueError('n debe ser entero positivo')
rng = np.random.default_rng(seed)
return {name: rng.random(n) for name in self.names}
def evaluar(self, u, do=None):
do = {} if do is None else do
if not isinstance(do,dict) or not set(do)<=set(self.names) or any(v not in (0,1) for v in do.values()):
raise ValueError('Intervención inválida')
if not isinstance(u,dict) or set(u)!=set(self.names):
raise ValueError('Es necesario un ruido por nodo')
sizes = {len(v) for v in u.values()}
if len(sizes)!=1 or any(np.ndim(v)!=1 or not np.isfinite(v).all() or np.any((v<0)|(v>=1)) for v in u.values()):
raise ValueError('Los ruidos deben ser vectores uniformes válidos')
n = sizes.pop()
result = {}
for name, parents, prob in self.specs:
if name in do:
result[name] = np.full(n, do[name], dtype=int)
continue
idx = np.zeros(n,dtype=int)
for parent in parents:
idx = 2*idx + result[parent]
p = prob[idx]
reverse = np.isin(idx, [i for node,i in self.reverse if node==name])
result[name] = np.where(reverse, u[name]>=1-p, u[name]<p).astype(int)
return result
def abducir(self, evidencia, n, seed):
if not isinstance(evidencia,dict) or not set(evidencia)<=set(self.names) or any(v not in (0,1) for v in evidencia.values()):
raise ValueError('Evidencia inválida')
u = self.ruido(n, seed)
factual = self.evaluar(u)
mask = np.ones(n, dtype=bool)
for key, value in evidencia.items():
mask &= factual[key] == value
if not np.any(mask):
raise ValueError('Ninguna muestra compatible; comprueba soporte o aumenta n')
return {key:value[mask] for key,value in u.items()}, int(mask.sum())
def gemela(self, u, do):
"""Dos mundos, mismas realizaciones exógenas."""
return self.evaluar(u), self.evaluar(u, do)Use the same noise in the factual network and both intervened networks to compare models A and B. Simulated frequencies approximate known probabilities; they do not replace them.
# Mismas tablas y, por tanto, mismas marginales observadas e intervenidas.
# B invierte la orientación del umbral de Y cuando X=0.
specs = [('X', (), (.5,)), ('Y', ('X',), (.3, .7))]
modelo_a = SCMContrafactual(specs)
modelo_b = SCMContrafactual(specs, reverse={('Y', 0)})
for nombre, modelo in [('A',modelo_a), ('B',modelo_b)]:
u = modelo.ruido(120_000, 272123)
factual, y0_mundo = modelo.gemela(u, {'X':0})
_, y1_mundo = modelo.gemela(u, {'X':1})
factual1 = (factual['X']==1)&(factual['Y']==1)
pn_gemela = np.mean(y0_mundo['Y'][factual1]==0)
pns_gemela = np.mean((y0_mundo['Y']==0)&(y1_mundo['Y']==1))
# Abducción por rechazo, seguida de acción y predicción.
posterior, aceptadas = modelo.abducir({'X':1, 'Y':1}, 120_000, 272123)
pn_abduccion = np.mean(modelo.evaluar(posterior, {'X':0})['Y']==0)
assert pn_abduccion == pn_gemela
se = np.sqrt(pn_gemela*(1-pn_gemela)/aceptadas)
tabla_obs = np.array([[np.mean((factual['X']==x)&(factual['Y']==y))
for y in (0,1)] for x in (0,1)])
print(nombre, 'P(Y=1|do X=0):', round(y0_mundo['Y'].mean(),4),
'P(Y=1|do X=1):', round(y1_mundo['Y'].mean(),4),
'PN:', round(pn_gemela,4), 'PNS:', round(pns_gemela,4),
'aceptadas:', aceptadas, 'EE Monte Carlo:', round(se,5))
print('Tabla observacional P(X,Y), filas X y columnas Y:\n', np.round(tabla_obs,4))
np.testing.assert_allclose(tabla_obs,[[.35,.15],[.15,.35]],atol=.01,rtol=0)
exacto = 4/7 if nombre == 'A' else 1.
assert abs(pn_gemela-exacto) < 5*se + 1e-12
print('Valores exactos por longitudes de intervalo: PN A=4/7, B=1; PNS A=0,4, B=0,7.')Load the linear optimizer that will verify bounds.
from scipy.optimize import linprog
from itertools import productCalculate bounds with observational and interventional data and verify endpoints as linear programs. Probabilities are treated as exactly known, without sampling uncertainty.
def cotas_causacion(p0, p1, observada):
"""Cotas de Tian y Pearl y verificación con LP sobre (X,Y0,Y1).
observada[x,y]=P(X=x,Y=y). Ambos estudios apuntan a la misma población.
Las probabilidades de entrada se tratan como exactas, no como estimaciones
con incertidumbre muestral. Devuelve None para PN o PS si su condición
factual tiene probabilidad cero.
"""
obs = np.asarray(observada, dtype=float)
if (obs.shape != (2,2) or not np.isfinite(obs).all()
or np.any(obs<0) or not np.isclose(obs.sum(),1,atol=1e-12,rtol=0)
or not np.isfinite(p0) or not np.isfinite(p1)
or not 0<=p0<=1 or not 0<=p1<=1):
raise ValueError('Probabilidades inválidas')
p00,p01,p10,p11 = obs.ravel()
py = p01+p11
# P(X=x,Y=y) = P(X=x,Y_x=y), por consistencia.
states = list(product((0,1),repeat=3))
A = np.asarray([[1]*8, [y0 for x,y0,y1 in states],
[y1 for x,y0,y1 in states]] + [
[int(x==xx and (y0 if x==0 else y1)==yy) for x,y0,y1 in states]
for xx,yy in product((0,1),repeat=2)],float)
b = np.r_[1.,p0,p1,obs.ravel()]
feasible = linprog(np.zeros(8), A_eq=A, b_eq=b, bounds=(0,None), method='highs')
if not feasible.success:
raise ValueError('Datos experimentales y observados incompatibles')
formulas = {
'PNS': (max(0.,p1-p0,py-p0,p1-py),
min(p1,1-p0,p11+p00,p1-p0+p10+p01)),
'PN': None if p11==0 else (max(0.,(py-p0)/p11),min(1.,(1-p0-p00)/p11)),
'PS': None if p00==0 else (max(0.,(p1-py)/p00),min(1.,(p1-p11)/p00))}
objetivos = {
'PNS': [int(y0==0 and y1==1) for x,y0,y1 in states],
'PN': [int(x==1 and y0==0 and y1==1) for x,y0,y1 in states],
'PS': [int(x==0 and y0==0 and y1==1) for x,y0,y1 in states]}
denominadores = {'PNS':1.,'PN':p11,'PS':p00}
for key, formula in formulas.items():
if formula is None:
continue
obj = np.asarray(objetivos[key],float)
lo = linprog(obj,A_eq=A,b_eq=b,bounds=(0,None),method='highs')
hi = linprog(-obj,A_eq=A,b_eq=b,bounds=(0,None),method='highs')
if not lo.success or not hi.success:
raise RuntimeError('No se resolvió la comprobación de cotas')
lp = (lo.fun/denominadores[key], -hi.fun/denominadores[key])
np.testing.assert_allclose(formula,lp,atol=1e-8,rtol=0)
return formulas
# Tabla 2 hipotética de Tian y Pearl (2000), no un estudio real.
obs = np.array([[972,28],[998,2]],dtype=float)/2000
cotas = cotas_causacion(.014,.016,obs)
for nombre in ('PNS','PN','PS'):
print(nombre, 'cotas:', cotas[nombre])
np.testing.assert_allclose(cotas['PNS'], [.002,.016],atol=1e-10,rtol=0)
np.testing.assert_allclose(cotas['PN'], [1.,1.],atol=1e-10,rtol=0)
np.testing.assert_allclose(cotas['PS'], [.001/.486,.015/.486],atol=1e-10,rtol=0)
# Ejercicio adicional con selección: P(Y1=1)=0,7, P(Y0=1)=0,3.
obs_2 = np.array([[.15,.15],[.05,.65]])
cotas_2 = cotas_causacion(.3,.7,obs_2)
print('Ejemplo adicional:',cotas_2)
np.testing.assert_allclose(cotas_2['PN'], [10/13,11/13],atol=1e-10,rtol=0)
np.testing.assert_allclose(cotas_2['PNS'], [.5,.6],atol=1e-10,rtol=0)
np.testing.assert_allclose(cotas_2['PS'], [0,1/3],atol=1e-10,rtol=0)
# La primera tabla supone X independiente de (Y0,Y1) para los dos modelos A/B.
cotas_ab = cotas_causacion(.3,.7,[[.35,.15],[.15,.35]])
np.testing.assert_allclose(cotas_ab['PN'], [4/7,1],atol=1e-10,rtol=0)
print('Cotas PN de ambos modelos:',cotas_ab['PN'])
# Compatibilidad y condiciones de probabilidad cero.
try:
cotas_causacion(0.,0.,[[0.,0.],[0.,1.]])
raise AssertionError('Una tabla incompatible debe rechazarse')
except ValueError:
pass
assert cotas_causacion(.5,.5,[[.5,.5],[0.,0.]])['PN'] is None
print('Datos incompatibles rechazados y PN indefinida con P(X=1,Y=1)=0.')Implement the plug-in mediation formula for binary variables and compare with model-generated nested worlds. The reported standard error concerns paired differences, not a general causal interval.
import numpy as np
def mediacion_formula(a, m, y):
"""Fórmula plug-in de PNDE y TNIE para tratamiento y mediador binarios."""
a, m, y = np.asarray(a), np.asarray(m), np.asarray(y, float)
if a.ndim != 1 or m.shape != a.shape or y.shape != a.shape or len(a) == 0:
raise ValueError('Se requieren tres vectores de igual longitud')
if not np.isfinite(y).all() or not np.isin(a, [0,1]).all() or not np.isin(m, [0,1]).all():
raise ValueError('Tratamiento y mediador deben ser binarios y resultado finito')
p = np.empty(2)
ip = np.empty((2, len(a)))
q = np.empty((2, 2))
iq = np.empty((2, 2, len(a)))
for j in (0,1):
sel = a == j
if not sel.any():
raise ValueError('Falta un grupo de tratamiento')
p[j] = np.mean(m[sel])
ip[j] = sel * (m-p[j]) / sel.mean()
for k in (0,1):
cell = sel & (m == k)
if not cell.any():
raise ValueError('Falta soporte en una celda tratamiento-mediador')
q[j,k] = np.mean(y[cell])
iq[j,k] = cell * (y-q[j,k]) / cell.mean()
nde = (q[1,0]-q[0,0])*(1-p[0]) + (q[1,1]-q[0,1])*p[0]
nie = (q[1,1]-q[1,0])*(p[1]-p[0])
if_nde = ((1-p[0])*(iq[1,0]-iq[0,0]) + p[0]*(iq[1,1]-iq[0,1])
+ (q[1,1]-q[0,1]-q[1,0]+q[0,0])*ip[0])
if_nie = ((p[1]-p[0])*(iq[1,1]-iq[1,0])
+ (q[1,1]-q[1,0])*(ip[1]-ip[0]))
return {'nde':float(nde), 'nie':float(nie), 'p':p, 'q':q,
'if_nde':if_nde, 'if_nie':if_nie}
def comparar_mundos(estimado, directo, indirecto):
"""Compara en las mismas unidades; incluye la covarianza pareada."""
salida = []
for key, diff in [('nde', directo), ('nie', indirecto)]:
promedio = float(np.mean(diff))
dif_estimadores = estimado[key] - promedio
infl = estimado['if_'+key]-(diff-promedio)
se = float(np.std(infl, ddof=1)/np.sqrt(len(diff)))
salida.append((estimado[key], promedio, dif_estimadores, se))
return salida
def imprimir_comparacion(nombre, r, direct, indirect):
print(nombre)
for nombre_efecto, (formula, nested, dif, se) in zip(
('PNDE','TNIE'), comparar_mundos(r, direct, indirect)):
print(nombre_efecto, 'fórmula', round(formula,6),
'mundos', round(nested,6), 'diferencia', round(dif,6),
'EE Monte Carlo pareado', round(se,6))
print('TE fórmula:', round(r['nde']+r['nie'],6))In the first model change the treatment–mediator interaction. Without interaction on the linear scale, the coefficient product equals the relevant indirect effect; with interaction distinguish the decompositions.
# SCM lineal, dos versiones sobre el mismo ruido y las mismas unidades.
rg = np.random.default_rng(272123)
n = 12000
A = rg.integers(0, 2, n)
um = rg.random(n)
M0, M1 = (um < .2).astype(float), (um < .6).astype(float)
M = np.where(A == 1, M1, M0)
eps = rg.normal(0, .2, n)
for delta in (0., .5):
def f(a, m):
return 1 + .3*a + .4*m + delta*a*m + eps
Y = f(A, M)
r = mediacion_formula(A, M, Y)
directo = f(1, M0)-f(0, M0)
indirecto = f(1, M1)-f(1, M0)
imprimir_comparacion('Interacción delta = '+str(delta), r, directo, indirecto)
beta = np.linalg.lstsq(np.column_stack([np.ones(n), A, M]), Y, rcond=None)[0]
producto = (r['p'][1]-r['p'][0])*beta[2]
print('Producto de regresión sin interacción:', round(float(producto),6))
if delta == 0:
print('Población: PNDE 0,3; TNIE 0,16; TE 0,46; producto 0,16')
else:
print('Población: PNDE 0,4; TNIE 0,36; TE 0,76; producto omitido 0,28')
print('Alternativa: TNDE 0,6; PNIE 0,16; CDE(0) 0,3; CDE(1) 0,8')In the binary SCM retain the same noise across worlds and compare the formula with simulated counterfactuals. Complete knowledge is available only because we construct the model here.
# Modelo binario del plan general. Ambos ruidos uniformes son independientes;
# se comparten entre mundos, tal como especifica este SCM concreto.
rg_b = np.random.default_rng(272124)
n_b = 12000
Ab = rg_b.integers(0,2,n_b)
umb, uyb = rg_b.random(n_b), rg_b.random(n_b)
Mb0 = (umb < .25).astype(float)
Mb1 = (umb < .75).astype(float)
Mb = np.where(Ab == 1, Mb1, Mb0)
def q_bin(a,m):
return .1 + .2*a + .2*m + .3*a*m
def y_bin(a,m):
return (uyb < q_bin(a,m)).astype(float)
Yb = y_bin(Ab, Mb)
rb = mediacion_formula(Ab, Mb, Yb)
imprimir_comparacion('Resultado binario, interacción en riesgo', rb,
y_bin(1,Mb0)-y_bin(0,Mb0),
y_bin(1,Mb1)-y_bin(1,Mb0))
print('Población: PNDE 0,275; TNIE 0,25; TE 0,525')
print('Alternativa: TNDE 0,425; PNIE 0,1; CDE(m) 0,2+0,3m')
print('Producto de coeficientes a A=0: 0,5×0,2=0,1, es PNIE, no TNIE.')Finally use a logistic relationship without interaction in the index. Nonlinearity can make the coefficient product differ from the indirect effect on the probability scale.
# En escala logit no hay término A*M; en riesgo la relación es no lineal.
rg_l = np.random.default_rng(272125)
n_l = 12000
Al = rg_l.integers(0,2,n_l)
uml, uyl = rg_l.random(n_l), rg_l.random(n_l)
Ml0 = (uml < .2).astype(float)
Ml1 = (uml < .6).astype(float)
Ml = np.where(Al == 1, Ml1, Ml0)
sigmoid = lambda z: 1/(1+np.exp(-z))
def y_logit(a,m):
return (uyl < sigmoid(-2+.8*a+1.2*m)).astype(float)
Yl = y_logit(Al, Ml)
rl = mediacion_formula(Al, Ml, Yl)
imprimir_comparacion('Resultado Bernoulli con predictor logit', rl,
y_logit(1,Ml0)-y_logit(0,Ml0),
y_logit(1,Ml1)-y_logit(1,Ml0))
q = sigmoid(np.array([[-2., -.8], [-1.2, 0.]]))
truth_nde = (q[1]-q[0])@np.array([.8,.2])
truth_nie = (q[1,1]-q[1,0])*.4
print('Población en riesgo PNDE/TNIE/TE:',
round(float(truth_nde),6), round(float(truth_nie),6),
round(float(truth_nde+truth_nie),6))
print('Producto 0,4×1,2=0,48 es en índice logit, no una diferencia de riesgos.')In local Python install dowhy, numpy, pandas, networkx and scikit-learn. Fit an invertible additive model and compare counterfactual_samples with manual abduction of residuals from the fitted model. Agreement depends on the assumed graph and mechanisms; it does not prove they are the only ones compatible with data.
"""Comparación local de contrafactuales con DoWhy-GCM.
Instala dowhy, numpy, pandas, networkx y scikit-learn en tu entorno local.
El modelo ajustado es una suposición; conocer los datos no lo identifica por sí solo.
"""
import numpy as np
import pandas as pd
import networkx as nx
from dowhy import gcm
rg = np.random.default_rng(272123)
n = 4000
x = rg.normal(size=n)
m = 2*x + rg.normal(size=n)
y = .5*x + 3*m + rg.normal(size=n)
training = pd.DataFrame({'X':x, 'M':m, 'Y':y})
graph = nx.DiGraph([('X','M'),('X','Y'),('M','Y')])
model = gcm.InvertibleStructuralCausalModel(graph)
model.set_causal_mechanism('X',gcm.EmpiricalDistribution())
model.set_causal_mechanism('M',gcm.AdditiveNoiseModel(gcm.ml.create_linear_regressor()))
model.set_causal_mechanism('Y',gcm.AdditiveNoiseModel(gcm.ml.create_linear_regressor()))
gcm.fit(model,training)
observada = training.iloc[[3]].copy()
x_actual = float(observada['X'].iloc[0])
x_alterno = x_actual + 1
cf = gcm.counterfactual_samples(model, {'X':lambda _:x_alterno}, observed_data=observada)
# Abducción manual con los mecanismos ajustados, no con coeficientes verdaderos.
# Para Y, DoWhy ordena alfabéticamente los padres: M, X.
pm = model.causal_mechanism('M').prediction_model
py = model.causal_mechanism('Y').prediction_model
fm = lambda value: float(pm.predict(np.array([[value]])).ravel()[0])
fy = lambda mediator, value: float(py.predict(np.array([[mediator,value]])).ravel()[0])
m_actual = float(observada['M'].iloc[0])
y_actual = float(observada['Y'].iloc[0])
u_m = m_actual-fm(x_actual)
u_y = y_actual-fy(m_actual,x_actual)
m_alterno = fm(x_alterno)+u_m
y_alterno = fy(m_alterno,x_alterno)+u_y
np.testing.assert_allclose([m_alterno,y_alterno],cf[['M','Y']].to_numpy().ravel(),atol=1e-10,rtol=0)
print('Observación:', observada.to_dict(orient='records')[0])
print('Ruidos abducidos bajo los mecanismos ajustados:', u_m, u_y)
print('do(X =',x_alterno,'):',cf.to_dict(orient='records')[0])
print('Predicción manual M, Y:',m_alterno,y_alterno)
print('La coincidencia es condicional al grafo y a los mecanismos ajustados.')npm run lab and open the connection link.Exercises
Step 1 of 3. What value of U is compatible with the observation?
Step 1 of 3. Which potential-response types does monotonicity allow?
import numpy as np
def natural_effects(scm, x, x_prime):
"""Calcula NDE puro, NIE total y TE con la fórmula de mediación."""
raise NotImplementedError('Implementa la fórmula')Check the two numeric bounds after solving them:
p0, p1, q11, q00, r = .3, .7, .25, .25, .5
inferior = max(0., (r-p0)/q11)
superior = min(1., (1-p0-q00)/q11)
assert abs(inferior-.8)<1e-12 and abs(superior-1)<1e-12
print('Cotas de PN:', inferior, superior)