Module contents
Lesson 12 of 28Core 105 min

Identification by adjustment: the backdoor and frontdoor criteria

Identification expresses an interventional quantity using the observational distribution. Derive backdoor and frontdoor criteria, find minimal and optimal adjustment sets, and classify good and bad controls.

After this lesson you can

  • Define identification and prove nonidentification with observationally equivalent models.
  • Prove that the backdoor criterion implies the adjustment formula.
  • Derive the frontdoor formula and apply it with a latent confounder.
  • Implement a backdoor-set checker and enumerate minimal sets in a DAG.
  • Classify candidate controls and simulate the bias and variance of including each.

Before you start

Choosing controls starts with the question

You want to estimate the effect of deploying a triage system on resolution time. You have prior difficulty, team characteristics, later metrics, and variables determining who adopts the tool. Adding all of them to a regression can block part of the effect or open a spurious association.

An assumed causal graph permits a reproducible decision: find sets that block confounding paths without destroying the effect of interest. The algorithm checks consequences of the graph; it does not prove the graph describes the world.

Identification: a property of models, not a table

A query is identified in a class of models if any two admissible models producing the same observational distribution also produce the same query value. Identification differs from precision: an identified quantity can be estimated with considerable uncertainty if data or overlap are limited.

To show a query is not identified, find two admissible models with the same observational distribution but different effects. Let U∼Bernoulli⁡(1/2)U\sim\operatorname{Bernoulli}(1/2). SCMs X:=U, Y:=XX:=U,\ Y:=X and X:=U, Y:=UX:=U,\ Y:=U both produce P(X=Y)=1P(X=Y)=1, but under do(X=1)do(X=1) give P(Y=1)=1P(Y=1)=1 and 1/21/2 respectively. If the class allows both graphs, the observed joint distribution does not determine the effect. A known graph may exclude one model and change the conclusion.

Backdoor paths and adjustment

A path between XX and YY is backdoor if its first arrow enters XX. The classical backdoor criterion requires that ZZ contain no descendants of XX and block all such paths by d-separation. Equivalently, XX and YY must be d-separated by ZZ in the graph removing outgoing arrows from XX. The directed path representing the causal effect must not be blocked.

InteractiveBackdoor path finder

C confounds X and Y. M mediates part of the effect of X and descends from X. This description uses X as treatment and Y as outcome, although you can choose other endpoints below. Dashed outlines mark latent nodes, which cannot be included in the adjustment.

  • Treatment
  • Outcome
  • Adjustment
CXMY

Adjustment set ∅

Simple paths between X and Y. Only those entering X count for the backdoor criterion.

X ← C → Y · backdoor · open
No internal nodes block the path.
X → M → Y · not backdoor · open
No internal nodes block the path.
X → Y · not backdoor · open
No internal nodes block the path.

The classical criterion requires blocking all backdoor paths and excluding treatment descendants. It is sufficient, not necessary, for identification by adjustment; the graph’s causal structure is an assumption.

Open backdoor paths1
Classical criterionNot satisfied
Explore paths and check whether the chosen set satisfies backdoor.

If the graph is causally correct, adjustment nodes are observed, consistency holds, and there is positivity P(X=x∣Z=z)>0P(X=x\mid Z=z)>0 for relevant strata, the criterion implies the adjustment formula

P(Y=y∣do(X=x))=∑zP(Y=y∣X=x,Z=z)P(Z=z).P(Y=y\mid do(X=x)) =\sum_z P(Y=y\mid X=x,Z=z)P(Z=z).

The proof connects to potential outcomes. Because XX descendants are excluded, intervention does not change the distribution of ZZ. Blocking backdoor paths implies Y(x)⊥X∣ZY(x)\perp X\mid Z under the SCM and its Markov property; by consistency, among those receiving X=xX=x, Y=Y(x)Y=Y(x). Therefore,

P(Y(x)=y)=∑zP(Y(x)=y∣Z=z)P(z)=∑zP(Y=y∣X=x,Z=z)P(z).P(Y(x)=y) =\sum_z P(Y(x)=y\mid Z=z)P(z) =\sum_z P(Y=y\mid X=x,Z=z)P(z).

Positivity makes the needed conditionals estimable. The criterion is sufficient, not necessary, and concerns the total effect of the specified intervention. D-separation is a graphical condition; unmeasured confounding, misclassification, or selective loss can invalidate the applied graph.

Minimal, generalized, and optimal

A set is inclusion-minimal if valid and none of its proper subsets is valid. Checking only single-element removals is insufficient: adding or removing several controls can change which paths are open by activating colliders. An inclusion-minimal set need not be the valid set with fewest elements or lowest variance. Enumerating subsets and testing d-separation works for small graphs; its cost grows exponentially with candidate count.

The complete adjustment criterion is broader than classical backdoor. For one treatment and outcome in a fully observed causal DAG, it forbids descendants, including the nodes themselves, of variables other than XX on directed paths from XX to YY; it also requires blocking all noncausal paths. Under its assumptions, it characterizes valid sets for the adjustment formula. For example, if X→YX\to Y and X→DX\to D with no other arrows, DD is a descendant of XX and the classical criterion rejects it, although adjustment may be valid with overlap. Partially oriented graphs or latent variables require the additional definitions and conditions of the generalized criterion.

The O set answers a different question: among valid adjustments, which yields the best asymptotic precision in a linear causal model? For a fully observed DAG with a causal path from XX to YY, take causal nodes cncn on directed paths from XX to YY, excluding XX and including YY, and let Forb={X}∪De(cn)Forb=\{X\}\cup De(cn), with reflexive descendants. Then

O(X,Y)=Pa(cn)∖Forb.O(X,Y)=Pa(cn)\setminus Forb.

Under the assumptions of Henckel, Perković and Maathuis, this set is valid whenever a valid adjustment exists and minimizes asymptotic variance of the OLS estimator among those adjustments. It promises neither lower error in every finite sample nor automatic validity for every estimator or graph with latent variables.

Good and bad controls depend on the graph

Controls cannot be classified solely by being measured before treatment. An observed confounder can close a backdoor path. A prior outcome predictor that introduces no new paths may improve precision. A mediator can block part of the total effect; a collider or its descendant can open a previously closed path.

In the M graph, A→XA\to X, A→ZA\to Z, B→ZB\to Z, B→YB\to Y, X→YX\to Y, path X←A→Z←B→YX\leftarrow A\to Z\leftarrow B\to Y is closed by collider ZZ. Adjusting for ZZ opens it. An imperfect proxy for a confounder does not guarantee elimination of all confounding; a descendant of the outcome can introduce selection. Classification requires the graph and estimand, not a universal list.

An instrument affecting XX but not YY by other paths does not by itself introduce population bias under those conditions. It can reduce precision by consuming treatment variation and, in certain models with omitted confounding, amplify residual bias. Direction and magnitude depend on mechanisms; they do not follow merely from the label “instrument”. Cinelli, Forney and Pearl show how a covariate’s role changes with the graph.

InteractiveThe control zoo

Each curve groups 250 regressions on independent samples of size 180. Both regressions use the same samples; the dashed line marks the true total effect. The chosen curve is drawn thicker.

0.3400.41.32.1Estimated slope of X
  • Unadjusted
  • Adjusting for Z

Selected model: Z=A; X=0,8A+Eₓ; Y=X+0,8A+Eᵧ. Z is an observed common cause. Adjusting blocks the backdoor path.

A, B, Eₓ, Eᵧ and E𝓏 are mutually independent standard normals for each unit and replication. Regressions include an intercept. The seed is 271202; only the equation indicated by the scenario changes. The population coefficient uses model covariances, while the mean and variance come from finite replications.

Bias here is measured against the total effect, which changes from 1 to 1.04 in the mediator scenario. Variance differences are results of this simulation, not guarantees for all samples. The graph and estimand determine whether a control is valid; an imperfect proxy or an instrument does not automatically replace the confounder.

True total effect1.000
Mean of selected estimator1.389
Monte Carlo bias0.389
Variance across replications0.0051
Population coefficient1.390
Compare the effect of including each variable on bias and variance.

Frontdoor: identifying through a mediator

The frontdoor criterion can identify an effect even if XX and YY share an unobserved confounder. For mediator MM, the simple version requires:

  1. Every directed path from XX to YY passes through MM.
  2. There are no open backdoor paths from XX to MM.
  3. All backdoor paths from MM to YY are blocked by adjustment for XX.

Support is also needed for the formula’s conditionals. Under these assumptions,

P(y∣do(x))=∑mP(m∣x)∑x′P(y∣m,x′)P(x′).P(y\mid do(x)) =\sum_m P(m\mid x)\sum_{x'}P(y\mid m,x')P(x').

The first condition decomposes the total effect through intervention on MM. The second identifies P(m∣do(x))P(m\mid do(x)) with P(m∣x)P(m\mid x). The third allows adjustment of the effect of intervening on MM by XX, giving P(y∣do(m))=∑x′P(y∣m,x′)P(x′)P(y\mid do(m))=\sum_{x'}P(y\mid m,x')P(x'). Summing over mm gives the formula. The inner average uses P(x′)P(x'), not P(x′∣m)P(x'\mid m): XX blocks the backdoor path between mediator and outcome. Pearl presents the criterion and derivation.

InteractiveFrontdoor in two steps

The graph is U→X, U→Y, X→M→Y: U is hidden and there is no X→Y arrow. Probabilities for both formulas are obtained by exactly summing the joint distribution, without sampling.

Chain both steps
Step 1. X changes the distribution of M
P(M=1|X)
20.0 %
80.0 %

Because there is no confounding between X and M, this distribution is also P(M=1|do(X)).

Step 2. Adjust the effect of M for X
P(Y=1|do(M))
26.0 %
61.0 %

For each m, calculate Σₓ P(Y=1|M=m,X=x)P(X=x), weighting by the overall distribution of X.

Step 3. Chain the links
P(Y=1|do(X))
33.0 %
54.0 %

Σₘ P(M=m|X)P(Y=1|do(M=m)). Direct intervention on the known model gives the same result.

  • Value 0
  • Value 1

Explicit model: U is Bernoulli with P(U=1)=0.4; P(X=1|U=u)=0.5+c(u−0.5); P(M=1|X=0)=0.2 and P(M=1|X=1) is the second control; P(Y=1|M=m,U=u)=0.1+0.35m+gu. Exogenous draws are independent. c and g are the first and third controls; all necessary probabilities are positive in the shown ranges.

The assumptions are substantive: M intercepts all directed paths from X to Y, there is no unblocked confounding between X and M, and X blocks backdoor paths between M and Y. Without these or adequate support the formula can fail even if the calculation runs. Agreement here follows from the SCM; it does not prove the assumptions hold in real data.

0.60
0.80
0.40
Observed difference0.444
Frontdoor0.210
Actual intervention in the model0.210
Follow the two identification steps in an SCM with a latent confounder.

To reproduce the initial figures for controls and frontdoor, this cell implements the generator and explicit models. Replicates are simulated; the final enumeration is exact for the binary SCM shown:

[ ]Reproduce the figuresBrowser
import numpy as np
import math

# Reproduce mulberry32 y Box-Muller de los interactivos a partir de la semilla.
mask = 0xffffffff
class Generador:
    def __init__(self, semilla): self.estado, self.guardado = semilla, None
    def uniforme(self):
        self.estado = (self.estado + 0x6d2b79f5) & mask
        t = self.estado
        t = ((t ^ (t >> 15)) * (t | 1)) & mask
        t ^= (t + ((t ^ (t >> 7)) * (t | 61))) & mask
        return ((t ^ (t >> 14)) & mask) / 4294967296
    def normal(self):
        if self.guardado is not None:
            valor, self.guardado = self.guardado, None
            return valor
        u, v = self.uniforme(), self.uniforme()
        radio = math.sqrt(-2*math.log(u))
        self.guardado = radio*math.sin(2*math.pi*v)
        return radio*math.cos(2*math.pi*v)

g = Generador(271202)
ruidos = np.array([g.normal() for _ in range(250*180*5)]).reshape(250,180,5)
A, B, Ex, Ey, Ez = (ruidos[:,:,i] for i in range(5))
def resumir(x,y,z,verdad):
    x = x-x.mean(axis=1,keepdims=True)
    y = y-y.mean(axis=1,keepdims=True)
    z = z-z.mean(axis=1,keepdims=True)
    xx, xy = np.sum(x*x,axis=1), np.sum(x*y,axis=1)
    xz, yz, zz = np.sum(x*z,axis=1), np.sum(y*z,axis=1), np.sum(z*z,axis=1)
    pendientes = [xy/xx,(xy-xz*yz/zz)/(xx-xz*xz/zz)]
    return [(round(float(v.mean()),4),round(float(v.mean()-verdad),4),
             round(float(v.var(ddof=1)),5)) for v in pendientes]

casos = []
x=.8*A+Ex; z=A; y=x+.8*A+Ey; casos.append(('confusor',x,y,z,1))
x=A; z=.8*x+Ez; y=.4*x+.8*z+Ey; casos.append(('mediador',x,y,z,1.04))
x=A; y=x+Ey; z=x+y+Ez; casos.append(('colisionador',x,y,z,1))
z=A; x=.8*z+Ex; y=x+Ey; casos.append(('instrumento puro',x,y,z,1))
z=A; x=.8*z+B+Ex; y=x+B+Ey; casos.append(('instrumento con confusión',x,y,z,1))
z=A; x=Ex; y=x+1.2*z+Ey; casos.append(('precisión',x,y,z,1))
z=A+.8*B; x=.8*A+Ex; y=x+.8*A+Ey; casos.append(('proxy',x,y,z,1))
x=A; y=x+Ey; z=y+Ez; casos.append(('descendiente',x,y,z,1))
x=.8*A+Ex; y=x+.8*B+Ey; z=.8*A+.8*B+Ez; casos.append(('M-bias',x,y,z,1))
for nombre,x,y,z,efecto in casos:
    print(nombre,'media, sesgo y varianza sin/con ajuste:',resumir(x,y,z,efecto))

# Frontdoor: enumeración exacta del SCM binario mostrado en la figura.
pu=[.6,.4]; px1=[.2,.8]; pm1=[.2,.8]; conjunta=np.zeros((2,2,2,2))
for u in (0,1):
 for x in (0,1):
  for m in (0,1):
   for y in (0,1):
    p=.1+.35*m+.4*u
    conjunta[u,x,m,y]=pu[u]*(px1[u] if x else 1-px1[u])*(pm1[x] if m else 1-pm1[x])*(p if y else 1-p)
px=conjunta.sum(axis=(0,2,3))
ymx=np.array([[conjunta[:,x,m,1].sum()/conjunta[:,x,m,:].sum() for x in (0,1)] for m in (0,1)])
paso2=ymx@px
front=np.array([(1-pm1[x])*paso2[0]+pm1[x]*paso2[1] for x in (0,1)])
observada=np.array([conjunta[:,x,:,1].sum()/px[x] for x in (0,1)])
verdad=np.array([sum(pu[u]*((1-pm1[x])*(.1+.4*u)+pm1[x]*(.45+.4*u)) for u in (0,1)) for x in (0,1)])
assert np.allclose(front,verdad) and np.min(conjunta)>0
print('Frontdoor: P(M=1|X):',pm1,'P(Y=1|do(M)):',paso2)
print('Observada:',observada,'frontdoor:',front,'intervención:',verdad)

The example of tobacco, tar, and cancer is often used to illustrate the structure: exposure, mediator, and outcome with unmeasured common causes between exposure and outcome. It is a teaching graph, not empirical proof that every effect of tobacco passes through a particular tar measure or that no common causes of mediator and outcome exist. An omitted direct path or unblocked confounding between MM and YY violates the assumptions.

From graph to estimator

Once the estimand is identified, the formula can be approximated by stratification, a correctly specified regression model, or weights based on treatment probability. These estimators have different modeling and support requirements; a valid set does not guarantee a particular linear regression is correctly specified. Predictive variable selection and selection for a causal effect have different goals: a predictive variable may be a bad control.

D-separation drives the graphical checks; feature selection and importance attributions do not automatically become effects of intervention.

Lab: checking adjustment sets

The checker applies the original criterion to a DAG: it removes outgoing edges from X, builds the moralized ancestral graph, and checks whether Z separates treatment and outcome. The search only proposes observed covariates; if a latent confounder is known in the graph, it is not offered as an available control.

[ ]Backdoor criterion and O setBrowser
import itertools
import networkx as nx

def separated_by_moralization(graph, source, target, conditioned):
    """D-separación de tres conjuntos disjuntos mediante grafo ancestral moral."""
    if not nx.is_directed_acyclic_graph(graph):
        raise ValueError('El grafo debe ser acíclico')
    source, target, conditioned = set(source), set(target), set(conditioned)
    if ((source & target) or (source & conditioned) or (target & conditioned)
            or not (source | target | conditioned).issubset(graph.nodes)):
        raise ValueError('Conjuntos incompatibles')
    ancestors = set(source | target | conditioned)
    for node in tuple(ancestors):
        ancestors.update(nx.ancestors(graph, node))
    subgraph = graph.subgraph(ancestors)
    moral = subgraph.to_undirected()
    for node in subgraph:
        moral.add_edges_from(itertools.combinations(subgraph.predecessors(node), 2))
    moral.remove_nodes_from(conditioned)
    return all(not nx.has_path(moral, x, y) for x in source for y in target)

def is_backdoor_set(graph, treatment, outcome, adjustment):
    """Criterio original de Pearl para dos nodos y DAG completo observado."""
    if not isinstance(graph, nx.DiGraph) or not nx.is_directed_acyclic_graph(graph):
        raise ValueError('El grafo debe ser un DAG dirigido')
    if treatment == outcome or treatment not in graph or outcome not in graph:
        raise ValueError('Tratamiento y resultado deben ser nodos distintos')
    adjustment = set(adjustment)
    if not adjustment.issubset(graph.nodes) or adjustment & {treatment, outcome}:
        raise ValueError('Conjunto de ajuste inválido')
    if adjustment & nx.descendants(graph, treatment):
        return False
    backdoor = graph.copy()
    backdoor.remove_edges_from(list(backdoor.out_edges(treatment)))
    return separated_by_moralization(backdoor, {treatment}, {outcome}, adjustment)

def minimal_backdoor_sets(graph, treatment, outcome, observed=None):
    """Enumeración exhaustiva mínima por inclusión, no por cardinalidad."""
    if observed is None:
        observed = set(graph)
    observed = set(observed)
    if not observed.issubset(graph.nodes) or not {treatment, outcome}.issubset(observed):
        raise ValueError('Nodos observados incompatibles')
    candidates = sorted(observed - {treatment, outcome} - nx.descendants(graph, treatment))
    valid_minimal = []
    for size in range(len(candidates)+1):
        for subset in itertools.combinations(candidates, size):
            z = set(subset)
            if not any(previous.issubset(z) for previous in valid_minimal) and is_backdoor_set(graph, treatment, outcome, z):
                valid_minimal.append(z)
    return valid_minimal

def optimal_o_set(graph, treatment, outcome):
    """O del DAG completamente observado; error si no hay camino causal."""
    if not isinstance(graph, nx.DiGraph) or not nx.is_directed_acyclic_graph(graph):
        raise ValueError('Se requiere DAG')
    if treatment == outcome or treatment not in graph or outcome not in graph:
        raise ValueError('Tratamiento y resultado incompatibles')
    if outcome not in nx.descendants(graph, treatment):
        raise ValueError('Se requiere un camino causal hacia el resultado')
    causal_nodes = nx.descendants(graph, treatment) & (nx.ancestors(graph, outcome) | {outcome})
    forbidden = {treatment} | causal_nodes
    for node in causal_nodes:
        forbidden.update(nx.descendants(graph, node))
    parents = set()
    for node in causal_nodes:
        parents.update(graph.predecessors(node))
    optimum = parents - forbidden
    if not is_backdoor_set(graph, treatment, outcome, optimum):
        raise ValueError('No se obtuvo un ajuste backdoor válido en este DAG')
    return optimum

G = nx.DiGraph([('C','X'), ('C','Y'), ('I','X'), ('P','Y'), ('X','Y')])
print('Grafo ejemplo:', sorted(G.edges()))
print('Mínimos por inclusión:', [sorted(z) for z in minimal_backdoor_sets(G,'X','Y')])
print('O(X,Y) en DAG observado:', sorted(optimal_o_set(G,'X','Y')))
assert minimal_backdoor_sets(G,'X','Y') == [{'C'}]
assert optimal_o_set(G,'X','Y') == {'C','P'}

butterfly = nx.DiGraph([('A','X'), ('A','Z'), ('B','Z'), ('B','Y'), ('X','Y')])
assert is_backdoor_set(butterfly, 'X', 'Y', set())
assert not is_backdoor_set(butterfly, 'X', 'Y', {'Z'})
print('M-bias: sin ajustar válido:', is_backdoor_set(butterfly,'X','Y',set()), '| ajustar colisionador válido:', is_backdoor_set(butterfly,'X','Y',{'Z'}))

Gproxy = nx.DiGraph([('U','X'),('U','Y'),('U','W'),('X','Y')])
assert minimal_backdoor_sets(Gproxy, 'X','Y', observed={'X','Y','W'}) == []
print('Proxy W con causa U no observada: no hay conjunto backdoor observado válido.')

Compare the implemented d-separation with NetworkX on graphs generated using a fixed seed:

[ ]Check d-separation in DAGsBrowser
import numpy as np

# Validación independiente mediante la d-separación implementada por NetworkX.
rng_graph = np.random.default_rng(1212)
checked = 0
for _ in range(60):
    dag = nx.DiGraph()
    dag.add_nodes_from(range(6))
    for i in range(6):
        for j in range(i+1, 6):
            if rng_graph.random() < .32:
                dag.add_edge(i, j)
    for ztuple in itertools.chain.from_iterable(itertools.combinations(range(1,5), k) for k in range(5)):
        z = set(ztuple)
        got = separated_by_moralization(dag, {0}, {5}, z)
        expected = nx.is_d_separator(dag, {0}, {5}, z)
        assert got == expected
        checked += 1
print('D-separación ancestral moral coincide con NetworkX en', checked, 'consultas.')

Now simulate a linear SCM with confounder C, instrument I, and precision predictor P. The same samples let us compare coefficient distributions. The stated asymptotic variances are properties of the model defined in the cell, not guarantees for every sample.

[ ]Bias and variance of controlsBrowser
# Modelo lineal: C,I,P,eX,eY normales estándar mutuamente independientes.
# X=C+I+eX; Y=2X+C+2P+eY. El efecto causal total de X es 2.
# I es instrumento de X y P es causa adicional del resultado.
rng_sim = np.random.default_rng(1213)
n, repetitions = 300, 400
estimates = {'sin ajustar': [], 'C': [], 'C,P': [], 'C,I,P': []}
for _ in range(repetitions):
    C, I, P, ex, ey = rng_sim.normal(size=(5, n))
    X = C + I + ex
    Y = 2*X + C + 2*P + ey
    for label, covariates in [('sin ajustar', ()), ('C', (C,)), ('C,P', (C,P)), ('C,I,P', (C,I,P))]:
        design = np.column_stack((np.ones(n), X, *covariates))
        estimates[label].append(np.linalg.lstsq(design, Y, rcond=None)[0][1])

print('Muestras:', repetitions, '| n:', n, '| efecto verdadero:', 2)
for label, values in estimates.items():
    v = np.asarray(values)
    print(f'{label:12} media={v.mean():.4f} sesgo={v.mean()-2:+.4f} n*var={n*v.var(ddof=1):.4f} EE_MC_media={v.std(ddof=1)/np.sqrt(repetitions):.4f}')
print('Límites teóricos: media sin ajustar 7/3; n*var ajustada con C, C+P, C+I+P: 2,5; 0,5; 1.')
print('O mejora varianza asintótica en este modelo lineal; no garantiza mejora en cada muestra.')

To check the first graph in DAGitty, replace the contents of “Model code” with the following, click “Update DAG”, and inspect “Causal effect identification” with “Adjustment (total effect)”:

dag {
  X [exposure]
  Y [outcome]
  C -> X
  C -> Y
  I -> X
  P -> Y
  X -> Y
}

In the DAGitty 3.1 check, the minimal sufficient set for the total effect is {C}, as in our cell. The O set in that example is {C,P} and targets precision, not inclusion-minimality. Comparison depends on choosing the same graph, treatment, outcome, and observed variables; the tool does not validate causal arrows.

In a local DoWhy installation, create the model with the same DAG and call model.identify_effect(method_name="minimal-adjustment"). Compare its returned set with the cell’s minima: DoWhy seeks a minimum-cardinality set, while our function enumerates all inclusion-minimal sets, which may differ. The previous lesson’s installation and graph example shows how to build the model; DoWhy was not run here because it is not installed in the preparation environment.

Lab: estimate and compare

In the following discrete model, U is a latent confounder between X and Y, but there is no direct path X→Y. The cell enumerates the distribution using exact fractions, computes the frontdoor formula from observed X, M, and Y, and compares it with surgery in the complete model. Simulation checks what happens with a finite sample.

[ ]Frontdoor in a binary SCMBrowser
from fractions import Fraction as F
from itertools import product
from random import Random

# U no se observa. Cada variable se genera a partir de su distribución
# condicional y de una fuente de ruido independiente.
p_x1_u = (F(1, 4), F(3, 4))
p_m1_x = (F(1, 5), F(4, 5))

def p_binary(value, p_one):
    return p_one if value else 1 - p_one

def joint(u, x, m, y):
    p_y1 = F(1, 10) + F(2, 5) * m + F(2, 5) * u
    return (F(1, 2) * p_binary(x, p_x1_u[u])
            * p_binary(m, p_m1_x[x]) * p_binary(y, p_y1))

prob = {(u, x, m, y): joint(u, x, m, y)
        for u, x, m, y in product(range(2), repeat=4)}
assert sum(prob.values()) == 1

def p(**conditions):
    names = ('u', 'x', 'm', 'y')
    return sum((mass for values, mass in prob.items()
                if all(values[names.index(k)] == v
                       for k, v in conditions.items())), F(0))

def mean_y(x, m):
    return p(x=x, m=m, y=1) / p(x=x, m=m)

def frontdoor(x):
    # P(m | x) sum_x' E[Y | m, x'] P(x').
    return sum((p(x=x, m=m) / p(x=x)
                * sum((mean_y(xp, m) * p(x=xp) for xp in range(2)), F(0))
                for m in range(2)), F(0))

def intervene(x):
    # Corta U -> X y conserva la distribución original de U.
    return sum((F(1, 2) * p_binary(m, p_m1_x[x])
                * (F(1, 10) + F(2, 5) * m + F(2, 5) * u)
                for u, m in product(range(2), repeat=2)), F(0))

observed = [p(x=x, y=1) / p(x=x) for x in range(2)]
effects = [intervene(x) for x in range(2)]
front = [frontdoor(x) for x in range(2)]
naive = sum((p(m=m) * (mean_y(1, m) - mean_y(0, m))
             for m in range(2)), F(0))

print('P(X=x, M=m):', [[str(p(x=x, m=m)) for m in range(2)] for x in range(2)])
print('P(M=1 | X):', [str(p_m1_x[x]) for x in range(2)])
print('E[Y | X]:', [str(v) for v in observed])
print('E[Y | do(X)]:', [str(v) for v in effects])
print('Frontdoor:', [str(v) for v in front])
print('Diferencia observacional:', observed[1] - observed[0])
print('Efecto total:', effects[1] - effects[0])
print('Contraste ajustado ingenuo por M:', naive)
assert front == effects
assert min(p(x=x, m=m) for x, m in product(range(2), repeat=2)) > 0

# Comprueba por simulación que el estimador usa únicamente X, M, Y.
rng = Random(1729)
n = 30000
counts = [[0, 0] for _ in range(2)]
successes = [[0, 0] for _ in range(2)]
for _ in range(n):
    u = int(rng.random() < 0.5)
    x = int(rng.random() < float(p_x1_u[u]))
    m = int(rng.random() < float(p_m1_x[x]))
    y = int(rng.random() < 0.1 + 0.4 * m + 0.4 * u)
    counts[x][m] += 1
    successes[x][m] += y
x_counts = [sum(row) for row in counts]
estimate = []
for x in range(2):
    estimate.append(sum((counts[x][m] / x_counts[x])
                        * sum((successes[xp][m] / counts[xp][m])
                              * (x_counts[xp] / n) for xp in range(2))
                        for m in range(2)))
print('Muestra: n =', n, '; mínimo de observaciones por celda =', min(map(min, counts)))
print('Frontdoor empírico:', [round(v, 4) for v in estimate],
      '; efecto =', round(estimate[1] - estimate[0], 4))

In a particular linear model, the total effect is the product of the effect of X on M and the coefficient of M in a regression of Y on M and X. This simplification depends on the linear equations and frontdoor assumptions; the general formula is the sum of distributions above.

[ ]Frontdoor in a linear SCMBrowser
import numpy as np

# SCM lineal, sin efecto directo X -> Y: todas las normales son independientes.
rng = np.random.default_rng(1729)
n = 30000
u, ruido_x, ruido_m, ruido_y = rng.normal(size=(4, n))
x = 0.8 * u + ruido_x
m = 0.7 * x + ruido_m
y = 1.3 * m + 0.9 * u + ruido_y

# Las dos regresiones son diferentes: M ~ X y Y ~ M + X.
a = np.linalg.lstsq(np.column_stack((np.ones(n), x)), m, rcond=None)[0][1]
coef = np.linalg.lstsq(np.column_stack((np.ones(n), x, m)), y, rcond=None)[0]
b = coef[2]
crudo = np.linalg.lstsq(np.column_stack((np.ones(n), x)), y, rcond=None)[0][1]

efecto_exacto = 0.7 * 1.3
crudo_exacto = efecto_exacto + 0.9 * 0.8 / (0.8**2 + 1)
print('a estimado:', round(a, 4), '; b estimado:', round(b, 4))
print('Producto estimado:', round(a * b, 4), '; efecto exacto:', round(efecto_exacto, 4))
print('Pendiente cruda estimada:', round(crudo, 4), '; exacta:', round(crudo_exacto, 4))
print('Coeficiente de X al ajustar M:', round(coef[1], 4),
      '; exacto:', round(crudo_exacto - efecto_exacto, 4))

Finally, in a model with observed confounder and known effect, compare stratification, propensity weighting, and regression. In this binary example the first two coincide because propensities are estimated saturately by stratum; that equality is not general.

[ ]Stratification, IPW, and regressionBrowser
import numpy as np

# Z es confusor previo; se supone observado. Los tres ruidos uniformes son
# independientes. La política P(X=1|Z)=(0,25;0,75) cumple positividad.
# P(Y=1|X,Z)=0,1+0,3 X+0,4 Z no tiene interacción. Bajo do(X=x),
# E(Y)=0,1+0,3x+0,4*0,4 = 0,26+0,3x; el efecto poblacional es 0,3.
rg_adj = np.random.default_rng(12121)
n_adj = 20000
z_adj = (rg_adj.random(n_adj) < .4).astype(int)
x_adj = (rg_adj.random(n_adj) < np.where(z_adj == 1, .75, .25)).astype(int)
p_y_adj = .1 + .3*x_adj + .4*z_adj
y_adj = (rg_adj.random(n_adj) < p_y_adj).astype(int)

# Todas las celdas se comprueban antes de dividir. Estandarizamos las medias
# observadas en cada (X,Z) con la distribución empírica común de Z.
counts_adj = np.array([[np.sum((x_adj == x) & (z_adj == z))
                        for z in (0, 1)] for x in (0, 1)])
if np.any(counts_adj == 0):
    raise ValueError('Falta una combinación tratamiento-confusor')
means_adj = np.array([[y_adj[(x_adj == x) & (z_adj == z)].mean()
                       for z in (0, 1)] for x in (0, 1)])
weights_adj = np.array([(z_adj == z).mean() for z in (0, 1)])
strata_adj = means_adj @ weights_adj

# IPW Horvitz-Thompson con propensión estimada por estrato. La coincidencia con
# estandarización es exacta aquí por saturar propensión y resultado en Z binaria;
# no implica que los dos estimadores coincidan con modelos generales.
e_by_z_adj = np.array([x_adj[z_adj == z].mean() for z in (0, 1)])
if np.any((e_by_z_adj <= 0) | (e_by_z_adj >= 1)):
    raise ValueError('No hay solapamiento empírico en algún estrato')
e_adj = e_by_z_adj[z_adj]
ipw_adj = np.mean(x_adj*y_adj/e_adj - (1-x_adj)*y_adj/(1-e_adj))
assert np.isclose(ipw_adj, strata_adj[1]-strata_adj[0])

# La regresión binaria lineal está correctamente especificada en esta DGP
# porque la probabilidad condicional es afín y sin interacción X*Z.
design_adj = np.column_stack((np.ones(n_adj), x_adj, z_adj))
beta_adj = np.linalg.lstsq(design_adj, y_adj, rcond=None)[0]
naive_adj = y_adj[x_adj == 1].mean()-y_adj[x_adj == 0].mean()
print('Celdas observadas (X filas, Z columnas):', counts_adj.tolist())
print('Propensión estimada por Z:', np.round(e_by_z_adj, 5))
print('Diferencia bruta:', round(naive_adj, 5))
print('Medias estandarizadas bajo tratamiento 0 y 1:', np.round(strata_adj, 5))
print('ATE estratificación:', round(strata_adj[1]-strata_adj[0], 5))
print('ATE IPW con propensión estimada por estrato:', round(ipw_adj, 5))
print('ATE regresión Y~1+X+Z:', round(beta_adj[1], 5))
print('ATE poblacional del SCM:', .3)
print('La identificación presupone el grafo, ausencia de confusión no medida, consistencia y positividad.')

Exercises

ProofProve the adjustment formula
Prove: In a causal SCM compatible with the DAG, suppose ZZ satisfies the backdoor criterion for (X,Y)(X,Y), with consistency and positivity in relevant strata. Derive P(Y=y∣do(X=x))P(Y=y\mid do(X=x)).
The proof will appear here as you work.

Step 1 of 3. Why can we weight by P(Z=z)?

ProofChain the two frontdoor steps
Prove: Suppose M intercepts all directed paths X→Y, there is no open backdoor path X→M, X blocks all backdoor paths M→Y, and the required probabilities have support.
The proof will appear here as you work.

Step 1 of 3. How do you identify the mediator distribution after fixing X=x?

QuizThe pretreatment collider
In A→X, A→Z, B→Z, B→Y and X→Y, there are no other arrows or hidden variables. Should we adjust for Z to estimate the total effect of X on Y?

In the following exercise, XX and MM are binary. A population compatible with frontdoor has P(X=0)=P(X=1)=1/2P(X=0)=P(X=1)=1/2, P(M=1∣X=0)=1/5P(M=1\mid X=0)=1/5, P(M=1∣X=1)=4/5P(M=1\mid X=1)=4/5 and P(Y=1∣M=m,X=x)=1/5+(2/5)m+(1/5)xP(Y=1\mid M=m,X=x)=1/5+(2/5)m+(1/5)x. A latent confounder affects XX and YY, there is no direct path X→YX\to Y and frontdoor and support conditions hold.

NumericApply frontdoor
With those tables and conditions, what is P(Y=1 | do(X=1)) − P(Y=1 | do(X=0))?

The lab’s frontdoor cell computes these quantities using exact fractions and checks that they agree with intervention in the complete SCM.

CodeCheck the backdoor criterion
Implement is_backdoor_set(G, X, Y, Z) for Pearl’s original backdoor criterion on a causal networkx.DiGraph DAG. X and Y are distinct nodes and Z is an iterable of nodes distinct from X and Y. The graph may contain latent variables: the caller must ensure all nodes proposed in Z are observable. The function decides whether Z satisfies both conditions: 1. No member of Z is a descendant of X in the original DAG. 2. Z blocks every path between X and Y starting with an arrow into X. Equivalently, Z d-separates X and Y in the graph obtained by removing from a copy every outgoing arrow from X. Return a bool, do not mutate G or Z, and raise ValueError if the graph is not a simple directed DAG, nodes are missing, X == Y, or Z contains X or Y. You are not asked to implement a generalized adjustment criterion: a set this criterion rejects might be valid under another identification result.
import networkx as nx

def is_backdoor_set(G, X, Y, Z):
  raise NotImplementedError("Implementa el criterio original de puerta trasera")
Shift+Enter to run