Module contents
Lesson 11 of 28Core 105 min

Structural causal models and causal graphs

Structural causal models encode mechanisms in causal DAGs. Derive the do operator and truncated factorization, distinguish intervention from conditioning, study colliders and the ladder of causation, and link graphs with potential outcomes using SWIGs.

After this lesson you can

  • Write an SCM, draw its graph, and sample observational and interventional distributions.
  • Compute P(Y | do(x)) by truncated factorization and compare it with P(Y | X = x) under confounding.
  • Explain Simpson’s and Berkson’s paradoxes with graphs and choose the table answering a causal question.
  • Classify real questions on the three rungs of the ladder of causation.
  • Translate potential-outcome ignorability assumptions into d-separation in a SWIG.

Before you start

One table, two explanations

Two teams use different tools to fix bugs. The aggregate rate favors one tool, but the reverse holds when separating by difficulty. Which should be adopted? The table alone is insufficient: difficulty may precede the choice and affect both tool and outcome, or it may be a downstream variable changed by the tool itself.

In the first case, comparing within difficulty categories and weighting by a common population can answer a causal question under suitable assumptions. In the second, artificially imposing the same distribution of the intermediate variable changes the intervention. A graph makes the difference between those stories explicit; observed data do not automatically decide which is correct.

If ZZ is a prior confounder, the common mixture is P(Z)P(Z). If ZZ is a mediator, treatment is unconfounded, and the other model assumptions hold, the total effect uses P(Z∣T=t)P(Z\mid T=t) because the intervention can also change the composition of ZZ. A comparison fixing ZZ asks a different question, which needs its own definition and identification.

InteractiveSimpson’s paradox reversed

Z=0 and Z=1 represent two case types. The table stays the same when switching graphs: conditional rates and the observed mixture alone do not tell us whether Z precedes treatment or is a consequence of it.

GroupSuccess T=0Success T=1P(Z|T=0)P(Z|T=1)
Z=090 %95 %90 %10 %
Z=150 %55 %10 %90 %
Total86.0 %59.0 %100 %100 %
Observed
86.0 %
59.0 %
Intervention
70.0 %
75.0 %
  • T=0
  • T=1

Model: first fix P(T=1) and the two mixtures P(Z=1|T). Success rates are 90.0 % and 50.0 % for T=0; T=1 adds 0.05 in each stratum. Each Y is Bernoulli at its corresponding rate. The observed aggregate uses P(Z|T=t), so it can reverse the common sign of the strata.

Graph Z→T, Z→Y, T→Y. The intervention cuts Z→T and retains P(Z=1)=50.0 %. With positivity and no additional confounding, P(Y|do(T=t)) averages treatment-specific rates using the same P(Z) weights, rather than observed P(Z|T=t). Bayes’ rule reconstructs P(T|Z) so the joint table remains the same.

Both constructions assume independent noise and the stated Y mechanism. They share the entire observational distribution but can yield different causal effects. Identifying the graph requires temporal and substantive knowledge, not just the table.

Causal role of Z
0.50
0.10
0.90
0.90
0.50
0.05
Observed difference−0.270
Identified causal difference0.050
Overall fraction Z=150.0 %
Explore the same table under two different causal assumptions.

Equations describing mechanisms

A structural causal model or SCM specifies for each endogenous variable ViV_i an equation

Vi=fi(pa⁡i,Ui),V_i=f_i(\operatorname{pa}_i,U_i),

where pa⁡i\operatorname{pa}_i are its parents and UiU_i captures exogenous causes. If the graph is acyclic, a topological order lets us solve equations one by one. Arrows represent causal inputs to mechanisms, not merely associations. A distribution requires both the equations and the joint distribution of noise terms.

The causal Markov condition, under appropriate assumptions for an acyclic SCM with independent noise, implies that each variable is independent of its nondescendants given its parents. In the discrete case this gives the observational factorization

P(v1,…,vd)=∏i=1dP(vi∣pa⁡i).P(v_1,\ldots,v_d)=\prod_{i=1}^d P(v_i\mid\operatorname{pa}_i).

A Bayesian network can factorize a distribution without its arrows having causal meaning. A single observational distribution may be compatible with several causal graphs: choosing between them requires substantive knowledge, additional restrictions, or interventions.

The Markov implication goes from model to independences. It does not claim every observed independence must appear through d-separation: particular parameter choices can produce cancellations. The additional faithfulness assumption rules out such coincidences but still does not by itself turn a distribution into a unique causal explanation.

Intervening is not conditioning

The do operator represents an external intervention. In do(X=x)do(X=x) the equation for XX is replaced by the constant xx, its incoming arrows are removed, and the remaining mechanisms are preserved. This autonomy is an assumption about the intervention; not every real action changes just one equation.

InteractiveGraph surgery

Tap a node or select it below. The intervention replaces its mechanism with a constant and cuts only its incoming arrows; the other mechanisms remain unchanged.

  • Active arrow
  • Cut arrow
  • Fixed node
CXMYS

Model equations: each U is uniform on [0,1] and independent of the others. The bracketed expression equals 1 if true and 0 otherwise.

C = 1[U_C < 0,5]
X = 1 (intervened)
M = 1[U_M < 0,1 + 0,6 X]
Y = 1[U_Y < 0,1 + 0,2 C + 0,35 X + 0,2 M]
S = 1[U_S < 0,1 + 0,35 X + 0,35 Y]

Marginals P(variable = 1), calculated by summing exactly over the 32 binary states:

  • Observational
  • Intervention
C0.50 / 0.50
X0.50 / 1.00
M0.40 / 0.70
Y0.45 / 0.69
S0.43 / 0.69

The bars show population marginals, not conditional distributions. The comparison below contrasts conditioning on the chosen node with fixing it by intervention. This model is an example: a graph alone does not determine these probabilities.

Fixed value
P(Y=1 | X=1)0.750
P(Y=1 | do(X=1))0.690
Intervene on a node and compare surgery with conditioning.

In a causally sufficient discrete acyclic SCM with independent exogenous noise and conditionals defined for the necessary configurations, the post-intervention distribution is the truncated factorization

P(v∣do(X=x))=1{vX=x}∏Vi≠XP(vi∣pa⁡i).P(v\mid do(X=x)) =\mathbf 1\{v_X=x\}\prod_{V_i\ne X}P(v_i\mid\operatorname{pa}_i).

The factor generating XX has been removed; the remaining parents are evaluated at the fixed value. An intervention on multiple nodes removes all their factors. With latent confounders or dependent noise, simply multiplying observed-variable conditionals may give an incorrect distribution; an expanded graph or suitable identification method must represent that dependence.

For example, in Z→XZ\to X, Z→YZ\to Y, X→YX\to Y, if ZZ is prior and consistency, absence of unmeasured confounding, and positivity hold,

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).

By contrast, P(Y=y∣X=x)P(Y=y\mid X=x) weights using P(Z=z∣X=x)P(Z=z\mid X=x). Observing X=xX=x selects units with different causes of XX; fixing it breaks that incoming dependence. Conditioning on suitable observed parents of XX can identify the total effect in the causally sufficient DAG, provided there is support for the required values.

A soft intervention changes a mechanism without necessarily fixing the variable. For example, it may replace P(X∣Z)P(X\mid Z) with a new probabilistic rule q(X∣Z)q(X\mid Z) and preserve the other factors. Its effect corresponds to that specific policy. Invariance of the other mechanisms must be justified: merely shifting a distribution does not prove which equation changed.

In practice, formulate the intervention before calculating: is a tool replaced for every incident, is its use offered, or is the probability of adopting it increased? Each changes a different rule. The analysis must also decide what happens with noncompliance and units for which the proposed action is impossible.

Chains, forks, and colliders

In a chain X→M→YX\to M\to Y, MM transmits part of the effect; conditioning on MM generally does not answer the total-effect question. In the fork X←Z→YX\leftarrow Z\to Y, ZZ is a common cause; under the previous assumptions adjusting for it can close the confounding path. In the collider X→C←YX\to C\leftarrow Y, conditioning on CC or certain descendants can open an association between its causes, even if they were independent before selection.

Collider bias appears, for example, when analyzing only accepted articles if acceptance depends on both novelty and rigor. It can also arise when studying only surviving companies or active customers if inclusion depends on variables related to exposure and outcome. The direction and size of bias depend on the mechanism; selection does not always imply negative correlation.

In the article example, if selection rewards the sum of novelty and rigor, an article with little novelty needs more rigor to exceed the same threshold. Among accepted articles a negative association can appear that does not exist in the generated population. This does not imply increasing novelty reduces rigor: dependence is created by restricting the sample.

InteractiveSelection creates correlation

Each point represents a fictional article, with novelty X and rigor Y generated independently. The filter accepts when X+Y exceeds the threshold: accepted points are blue and the rest are faded. The line marks the boundary.

  • Selected
  • Not selected
  • X+Y = threshold

Reproducible model: 1600 pairs of independent standard normals, seed 271102; C=X+Y and S=1 if C>threshold. In the full population correlation is zero, although a finite sample need not yield exactly zero. Conditioning on S means a small X requires a larger Y to pass the filter. S is a descendant of collider C in X→C←Y; selecting on it opens an association, not a causal arrow between X and Y.

For comparison with the population, take a=threshold/√2 and λ=φ(a)/[1−Φ(a)]. Since (X+Y)/√2 and (X−Y)/√2 are independent standard normals, truncating the first gives variance v=1+aλ−λ². The conditional correlation is (v−1)/(v+1), with Φ evaluated numerically. The sample fraction and correlation fluctuate; they are less certain with few selected. This is a simulation and does not establish a relationship in real articles.

0.8
Selected465 / 1600
Selected fraction29.1 %
Correlation in full sample−0.004
Correlation among selected−0.603
Approximate theoretical correlation−0.590
Change the selection threshold and observe how the point cloud changes.

In Berkson’s paradox, suppose X,Y∼indN(0,1)X,Y\stackrel{\mathrm{ind}}{\sim}N(0,1) and independent ϵ∼N(0,σ2)\epsilon\sim N(0,\sigma^2), with C=X+Y+ϵC=X+Y+\epsilon. The conditional normal distribution gives

Cov⁡(X,Y∣C=c)=−12+σ2,Corr⁡(X,Y∣C=c)=−11+σ2.\operatorname{Cov}(X,Y\mid C=c)=-\frac1{2+\sigma^2},\qquad \operatorname{Corr}(X,Y\mid C=c)=-\frac1{1+\sigma^2}.

Use Cov⁡(X,C)=Cov⁡(Y,C)=1\operatorname{Cov}(X,C)=\operatorname{Cov}(Y,C)=1 and Var⁡(C)=2+σ2\operatorname{Var}(C)=2+\sigma^2. These formulas condition on an exact value of CC using its conditional distribution; filtering by C>cC>c is another selection and needs another calculation. In this Gaussian model both mechanisms produce negative association, not a universal rule for every filter.

The birth-weight paradox illustrates the danger of conditioning on a variable affected by several causes: interpreting a comparison by weight requires specifying exposure, possible common causes, selection, and estimand. An observed reversal alone does not prove the mechanism.

Three kinds of questions

The ladder of causation distinguishes association P(Y∣X)P(Y\mid X), intervention P(Y∣do(X))P(Y\mid do(X)), and counterfactuals such as P(Y(0),Y(1))P(Y(0),Y(1)) or P(Y(0)∣X=1,Y=1)P(Y(0)\mid X=1,Y=1). The first question describes what is observed; the second changes a rule; the third combines outcomes from alternative worlds for the same units.

The causal hierarchy theorem formalizes conditions under which information at a lower level does not generically determine information at a higher level. It does not say every causal query is impossible to identify: a graph and additional assumptions can identify a particular intervention from observations.

Two examples clarify the limit. Let UU be equally likely Bernoulli. Models X:=U, Y:=XX:=U,\ Y:=X and X:=U, Y:=UX:=U,\ Y:=U have the same observational distribution X=YX=Y, but under do(X=1)do(X=1) their probabilities of Y=1Y=1 differ. Now take independent equally likely Bernoulli variables XX and UU and compare Y:=UY:=U with Y:=X⊕UY:=X\oplus U: their observational distributions and those of every intervention on XX agree, but in the first Y(0)=Y(1)Y(0)=Y(1) always and in the second never. These examples use different graphs and do not prove nonidentification under a known causal graph.

A bridge to potential outcomes: SWIG

A single-world intervention graph or SWIG represents a specific intervention by splitting the treated node into its random half and fixed value. In L→AL\to A, L→YL\to Y, A→YA\to Y, the graph for do(A=a)do(A=a) preserves the random half of AA, feeds the fixed value aa into the mechanism of YY, and labels the outcome Y(a)Y(a). Under the corresponding SWIG Markov property, d-separation leads to Y(a)⊥A∣LY(a)\perp A\mid L.

Moving from that independence to an observable formula also requires consistency and positivity in the relevant population. A SWIG for one value does not automatically represent the joint distribution of Y(0)Y(0) and Y(1)Y(1); claims combining both worlds may need additional assumptions. Richardson and Robins develop this connection between intervention graphs and potential outcomes.

The languages complement each other: an SCM defines Y(a)Y(a) by solving its equations after replacing that of AA with aa, while the SWIG encodes independences in that intervened world. Joint distributions across worlds may need additional restrictions; they do not follow from just any SWIG considered alone.

Probabilistic DAGs provide factorization and d-separation; the meaning of surgery adds causal assumptions. An acyclic graph allows mechanisms to be ordered. In distribution shift problems, distinguishing which mechanism changes helps formulate a transport hypothesis that can be tested.

Lab: build an SCM

This implementation represents binary variables with probability tables, independent uniform noise for each variable, and an explicit topological order. Exact enumeration multiplies the tables; a hard intervention creates a copy with the equation replaced and a soft intervention replaces a table without changing its parents.

[ ]Discrete SCM from scratchBrowser
import itertools
import numpy as np

class SCM:
    """Red binaria acíclica con un ruido uniforme independiente por nodo.

    specs es una lista ordenada de (nombre, padres, probabilidades). Padres
    aparecen antes que el nodo. La tabla sigue orden lexicográfico de bits,
    de modo que, con padres [A,B], índices 0,1,2,3 corresponden a 00,01,10,11.
    """
    def __init__(self, specs):
        self.specs = []
        visited = set()
        for name, parents, probabilities in specs:
            parents = tuple(parents)
            prob = np.asarray(probabilities, dtype=float)
            if (not isinstance(name, str) or not name or name in visited
                    or len(set(parents)) != len(parents)
                    or any(parent not in visited for parent in parents)
                    or prob.shape != (2**len(parents),)
                    or not np.isfinite(prob).all() or np.any((prob < 0) | (prob > 1))):
                raise ValueError('Especificación inválida o no ordenada topológicamente')
            self.specs.append((name, parents, tuple(float(p) for p in prob)))
            visited.add(name)
        if not self.specs:
            raise ValueError('El modelo no puede estar vacío')
        self.names = tuple(node[0] for node in self.specs)

    def intervene(self, assignments):
        """Devuelve una copia y sustituye cada ecuación intervenida por una constante."""
        if not isinstance(assignments, dict) or not set(assignments).issubset(self.names):
            raise ValueError('La intervención contiene nodos desconocidos')
        if any(value not in (0, 1) for value in assignments.values()):
            raise ValueError('Las intervenciones duras deben ser binarias')
        specs = [(name, (), (float(assignments[name]),)) if name in assignments
                 else (name, parents, prob) for name, parents, prob in self.specs]
        return SCM(specs)

    def soft(self, replacements):
        """Sustituye tablas conservando padres; no modifica el modelo original."""
        if not isinstance(replacements, dict) or not set(replacements).issubset(self.names):
            raise ValueError('La intervención contiene nodos desconocidos')
        return SCM([(name, parents, replacements.get(name, prob))
                    for name, parents, prob in self.specs])

    def sample(self, n, seed):
        if not isinstance(n, int) or n <= 0:
            raise ValueError('n debe ser un entero positivo')
        rng = np.random.default_rng(seed)
        data = {}
        for name, parents, prob in self.specs:
            index = np.zeros(n, dtype=int)
            for parent in parents:
                index = 2*index + data[parent]
            data[name] = (rng.random(n) < np.asarray(prob)[index]).astype(int)
        return data

    def probability(self, event):
        """Enumeración exacta del producto de tablas, sin regularización."""
        if not isinstance(event, dict) or not set(event).issubset(self.names) or any(v not in (0, 1) for v in event.values()):
            raise ValueError('Evento inválido')
        total = 0.0
        for values in itertools.product((0, 1), repeat=len(self.names)):
            row = dict(zip(self.names, values))
            if any(row[k] != v for k, v in event.items()):
                continue
            mass = 1.0
            for name, parents, prob in self.specs:
                index = 0
                for parent in parents:
                    index = 2*index + row[parent]
                p = prob[index]
                mass *= p if row[name] == 1 else 1-p
            total += mass
        return total

    def conditional(self, event, given):
        if set(event) & set(given):
            raise ValueError('Evento y condición deben usar nodos distintos')
        den = self.probability(given)
        if den <= 0:
            raise ValueError('Condición de probabilidad cero')
        return self.probability({**event, **given}) / den

scm = SCM([
    ('Z', (), (.4,)),
    ('X', ('Z',), (.2, .8)),
    ('Y', ('Z', 'X'), (.1, .6, .5, .9)),
    ('R', ('Y',), (.25, .75)),
])
print('Orden:', scm.names, '| masa total:', round(scm.probability({}), 12))
print('P(Y=1|X=1):', round(scm.conditional({'Y':1}, {'X':1}), 6))
print('P(Y=1|do(X=1)):', round(scm.intervene({'X':1}).probability({'Y':1}), 6))
print('P(Y=1|do(X=0)):', round(scm.intervene({'X':0}).probability({'Y':1}), 6))
np.testing.assert_allclose(scm.conditional({'Y':1}, {'X':1}), 9/11)
np.testing.assert_allclose(scm.intervene({'X':1}).probability({'Y':1}), .72)
np.testing.assert_allclose(scm.intervene({'X':0}).probability({'Y':1}), .26)

Compare truncated factorization and sampling after intervening. Monte Carlo error quantifies sample variation; a soft policy produces another distribution that must not be confused with fixing X.

[ ]Hard and soft interventionsBrowser
# La factorización truncada conserva el mecanismo de Z y de Y y elimina P(X|Z).
p_do1 = sum(scm.probability({'Z': z}) * scm.conditional({'Y': 1}, {'X': 1, 'Z': z}) for z in (0, 1))
assert np.isclose(p_do1, .72)
draw = scm.intervene({'X': 1}).sample(80_000, 2031)
observed = draw['Y'].mean()
mc_se = np.sqrt(p_do1*(1-p_do1)/len(draw['Y']))
assert abs(observed-p_do1) < 5*mc_se
print('Factorización truncada:', round(p_do1, 6))
print('Muestreo con do(X=1):', round(observed, 6), '| EE Monte Carlo:', round(mc_se, 6))
print('Diferencia causal media para Y binaria:', round(p_do1-scm.intervene({'X':0}).probability({'Y':1}), 6))

# Intervención blanda: cambia P(X=1|Z), conserva la dependencia de Z.
soft_scm = scm.soft({'X': (.35, .65)})
print('P(Y=1) observacional:', round(scm.probability({'Y':1}), 6))
print('P(Y=1) bajo política blanda:', round(soft_scm.probability({'Y':1}), 6))
np.testing.assert_allclose(soft_scm.probability({'Y':1}), .469)
np.testing.assert_allclose(scm.probability({'Y':1}), .448)
assert scm.specs[1][1] == ('Z',) and scm.intervene({'X':1}).specs[1][1] == ()
assert soft_scm.specs[1][1] == ('Z',) and scm.specs[1][2] == (.2, .8)
print('Modelo original intacto; la intervención blanda conserva los padres.')

In a local installation with NetworkX and Matplotlib you can check d-separation and draw the surgery. The graph is a starting assumption: a library finding a blocked path does not confirm the mechanism in data.

[ ]Graphs and surgery with NetworkXLocal GPU
# Comprobación de caminos con NetworkX 3.6.1 o una versión compatible.
import networkx as nx
import matplotlib.pyplot as plt

graph = nx.DiGraph([('Z', 'X'), ('Z', 'Y'), ('X', 'Y')])
assert nx.is_directed_acyclic_graph(graph)
backdoor = graph.copy()
backdoor.remove_edges_from(list(backdoor.out_edges('X')))
print('Camino trasero abierto sin Z:', not nx.is_d_separator(backdoor, {'X'}, {'Y'}, set()))
print('Camino trasero bloqueado al condicionar Z:', nx.is_d_separator(backdoor, {'X'}, {'Y'}, {'Z'}))

intervened = graph.copy()
intervened.remove_edges_from(list(intervened.in_edges('X')))
print('Flechas tras do(X):', sorted(intervened.edges()))

collider = nx.DiGraph([('A','C'), ('B','C')])
assert nx.is_d_separator(collider, {'A'}, {'B'}, set())
assert not nx.is_d_separator(collider, {'A'}, {'B'}, {'C'})
print('Colisionador bloqueado sin C y abierto al condicionar C:', True)

fig, axes = plt.subplots(1, 2, figsize=(8, 3))
pos = {'Z':(.5,1), 'X':(0,0), 'Y':(1,0)}
for ax, g, title in zip(axes, [graph, intervened], ['Modelo supuesto', 'Cirugía do(X)']):
    nx.draw_networkx(g, pos=pos, ax=ax, node_color='#c8ddf0', arrows=True)
    ax.set_title(title)
    ax.set_axis_off()
plt.tight_layout()
plt.show()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The following optional example uses locally installed DoWhy. The library was unavailable in the preparation environment, so this snippet was not run here. The model and graph are assumptions of the example, and the specific estimate varies with the sample.

# Ejemplo opcional para una instalación local que YA tenga DoWhy.
# No se instaló ni se ejecutó en el entorno de preparación de la lección.
import numpy as np
import pandas as pd
import networkx as nx
from dowhy import CausalModel

rng = np.random.default_rng(1011)
z = rng.normal(size=5000)
x = .8*z + rng.normal(size=5000)
y = 2*x + 1.4*z + rng.normal(size=5000)
data = pd.DataFrame({'Z':z, 'X':x, 'Y':y})
graph = nx.DiGraph([('Z', 'X'), ('Z', 'Y'), ('X', 'Y')])
model = CausalModel(data=data, treatment='X', outcome='Y',
                    graph='\n'.join(nx.generate_gml(graph)))
estimand = model.identify_effect()
estimate = model.estimate_effect(estimand, method_name='backdoor.linear_regression',
                                 control_value=0, treatment_value=1)
print(estimand)
print('Estimación ajustada del efecto de fijar X en 1 frente a 0:', estimate.value)
print('El SCM simulado tiene efecto poblacional 2; el ajuste depende del grafo supuesto.')

Lab: Simpson and selection

Data from Charig and colleagues compare kidney-stone treatments in historical cohorts. The table is reproduced with counts in Bottou and colleagues. Aggregate rates and those standardized by size answer different comparisons; cohorts come from different periods and size adjustment does not prove the absence of other differences.

In each size category the observed rate favors open surgery, while the aggregate rate favors the percutaneous procedure. Check denominators as well as percentages: the proportions of small and large cases differ between treatments. The following standardization applies the same mixture to both groups, but interpreting it as an intervention effect requires assumptions these counts do not guarantee.

[ ]Simpson’s paradox in the published tableBrowser
import numpy as np

# Tablas I y II de Charig et al. (1986), BMJ 292:879-882.
# Columnas: piedra <2 cm, piedra >=2 cm. Filas: abierta, percutánea.
exitos = np.array([[81, 192], [234, 55]])
pacientes = np.array([[87, 263], [270, 80]])
tasas = exitos / pacientes
pesos = pacientes.sum(axis=0) / pacientes.sum()
brutas = exitos.sum(axis=1) / pacientes.sum(axis=1)
estandarizadas = tasas @ pesos

print("Tasas por tamaño (filas abierta, percutánea):")
print(np.round(tasas, 6))
print("Pesos comunes (población conjunta):", np.round(pesos, 6))
print("Tasas brutas:", np.round(brutas, 6))
print("Abierta menos percutánea, bruto:", round(brutas[0] - brutas[1], 6))
print("Tasas estandarizadas:", np.round(estandarizadas, 6))
print("Abierta menos percutánea, estandarizado:",
      round(estandarizadas[0] - estandarizadas[1], 6))

Now generate a Gaussian collider and compare the full sample with the sample selected by a threshold. The theoretical correlation corresponds to filtering on a noisy sum, not to exact conditioning in the earlier proof.

[ ]Berkson: selection and regressionBrowser
import numpy as np

# Modelo explícito: X, Y y E son normales estándar independientes;
# U = X + Y + E y seleccionamos S = 1 si U > 0.
generador = np.random.default_rng(111)
n = 20_000
x, y, e = generador.normal(size=(3, n))
u = x + y + e
seleccion = u > 0

def pendiente(a, b):
    """Pendiente OLS con intercepto, desde sumas centradas."""
    ac, bc = a - a.mean(), b - b.mean()
    return ac @ bc / (ac @ ac)

def correlacion(a, b):
    ac, bc = a - a.mean(), b - b.mean()
    return (ac @ bc) / np.sqrt((ac @ ac) * (bc @ bc))

# Como Var(U)=3, E[U | U>0]^2=6/pi y
# Cov(X,Y | U>0)=-2/(3*pi), Var(X | U>0)=1-2/(3*pi).
rho_teorica = -2 / (3 * np.pi - 2)
# Ajustar U como regresor también abre el colisionador: por normalidad,
# E[Y | X,U] = (U-X)/2. La pendiente parcial de X es -1/2.
matriz = np.column_stack((np.ones(n), x, u))
coef = np.linalg.lstsq(matriz, y, rcond=None)[0]
print("N total y seleccionado:", n, int(seleccion.sum()))
print("Correlación completa:", round(correlacion(x, y), 4))
print("Correlación seleccionada:", round(correlacion(x[seleccion], y[seleccion]), 4))
print("Correlación teórica seleccionada:", round(rho_teorica, 4))
print("Pendiente completa Y~X:", round(pendiente(x, y), 4))
print("Pendiente seleccionada Y~X:", round(pendiente(x[seleccion], y[seleccion]), 4))
print("Pendiente teórica seleccionada:", round(rho_teorica, 4))
print("Coeficientes Y~1+X+U:", np.round(coef, 4))
print("Pendientes parciales teóricas de X y U: -0.5, 0.5")

Exercises

ProofDerive surgery
Prove: Consider a discrete acyclic SCM with mutually independent exogenous noise. The intervention fixes X=xX=x and leaves the other equations invariant. Derive its truncated factorization when relevant conditionals are defined.
The proof will appear here as you work.

Step 1 of 3. What changes when applying do(X=x)?

ProofCorrelation under conditioning
Prove: Let X,Y∼N(0,1)X,Y\sim N(0,1) be independent, ϵ∼N(0,σ2)\epsilon\sim N(0,\sigma^2) independent and C=X+Y+ϵC=X+Y+\epsilon. Derive the covariance and correlation of X,YX,Y conditional on C=cC=c.
The proof will appear here as you work.

Step 1 of 3. What are Cov(X,C), Cov(Y,C), and Var(C)?

In the next two numeric exercises use this binary SCM: Z∼Bernoulli⁡(0,5)Z\sim\operatorname{Bernoulli}(0{,}5), P(X=1∣Z=0)=0,2P(X=1\mid Z=0)=0{,}2, P(X=1∣Z=1)=0,8P(X=1\mid Z=1)=0{,}8 and P(Y=1∣X=x,Z=z)=0,1+0,3x+0,4zP(Y=1\mid X=x,Z=z)=0{,}1+0{,}3x+0{,}4z. Its noise terms are independent and ZZ precedes XX. Calculate both probabilities before running the checking cell.

NumericObserve X=1
In the specified binary SCM, what is P(Y=1 | X=1)?
NumericSet X=1
In the same SCM, what is P(Y=1 | do(X=1))?
[ ]Observe and act in the binary SCMBrowser
import numpy as np

p_z = np.array([0.5, 0.5])
p_x1 = np.array([0.2, 0.8])
p_y1_x1 = np.array([0.4, 0.8])
p_x = np.sum(p_z*p_x1)
p_z_given_x1 = p_z*p_x1/p_x
observado = np.sum(p_y1_x1*p_z_given_x1)
intervenido = np.sum(p_y1_x1*p_z)
print('P(Z | X=1):', p_z_given_x1)
print('P(Y=1 | X=1), P(Y=1 | do(X=1)):', observado, intervenido)
QuizPredicting churn
Which rung asks for the churn rate among customers who received an alert, without intervening?
QuizAn alert policy
Which rung corresponds to the churn rate if an alert were assigned to everyone through a defined intervention?
QuizThe customer who left
A person received an alert and left. Which rung asks whether the same person would have stayed without the alert?
QuizReturns and volatility
Asking for the historical distribution of returns on high-volatility days, without changing strategy, is a question of:
QuizChanging a portfolio rule
Estimating the loss distribution if a defined policy replaced one hedging rule with another mainly asks about:
QuizThe losing trade
For a particular losing trade, asking what would have happened with the same information and another decision is a query about:
QuizModel ablation
Comparing the performance distribution if an architecture is removed under a defined training recipe is a question of:
QuizThe same run with another component
For a particular run with observed loss, asking what loss would have resulted from changing only one component while keeping the same exogenous factors belongs to:
CodeIntervene in a discrete SCM
Implement intervene(scm, assignments) for a finite acyclic binary network. scm is a topologically ordered dictionary. Each key is a node name and each value is another dictionary with keys parents and probabilities: parents is a list of preceding node names and probabilities has length 2**len(parents). Its position is the binary integer obtained by reading parent values from left to right and contains P(node=1 | parents). You may assume scm is valid and contains no objects other than dictionaries, lists, strings, and numbers. assignments is a dictionary of simultaneous hard interventions: each value must be integer 0 or 1, without accepting booleans. Raise ValueError if assignments is not a dictionary, a name is not in scm, or a value is invalid. Return a new model without modifying scm or sharing any dictionary or list with it, even if assignments is empty. For each intervened node, replace its parents with [] and its table with [value]. Preserve all other mechanisms, especially equations of descendants. Tables without parents represent P(node=1), so [0] and [1] represent constants, not sample lists. Simultaneous interventions on ancestors and descendants are allowed.
def intervene(scm, assignments):
  # Crea una copia independiente y sustituye las ecuaciones intervenidas.
  raise NotImplementedError
Shift+Enter to run