Module contents
Lesson 24 of 28Advanced 110 min

Time-varying treatments: g-formula, marginal structural models and dynamic regimes

Time-varying confounders affected by prior treatment require careful sequential methods. Derive the g-formula, stabilized marginal structural models, dynamic regimes, and offline policy evaluation.

After this lesson you can

  • Use a temporal DAG to explain confounding affected by prior treatment.
  • Derive the g-formula under sequential exchangeability and positivity.
  • Implement parametric g-computation by Monte Carlo simulation.
  • Estimate a marginal structural model with stabilized weights and diagnose them.
  • Learn a two-stage dynamic regime with Q-learning and relate it to offline RL.

Before you start

One decision changes the next situation

A team decides each week whether to escalate alerts. Accumulated workload influences the next decision and outcome; prior decisions also change that workload. Comparing only observed decision histories can confound a strategy’s effect with the situation that led to its selection.

A time-varying confounder has a double role. In a DAG with A0→L1→A1→YA_0\to L_1\to A_1\to Y, L1→YL_1\to Y and a cause UU of L1L_1 and YY, L1L_1 helps explain later assignment but also mediates part of the effect of A0A_0. Conditioning on L1L_1 can block that mediation and open A0→L1←U→YA_0\to L_1\leftarrow U\to Y; omitting it can leave confounding of A1A_1. Bias depends on estimand and model: if A0A_0 is random, its marginal comparison is not necessarily biased merely by omitting L1L_1.

InteractiveThe double role of workload

We compare setting (A₀,A₁)=(1,1) with (0,0). In regressions, the readout sums the A₀ and A₁ coefficients: it is a projection of the chosen model, not necessarily that causal contrast.

A₀L₁A₁YUunobserved
  • Highlighted path
  • Other arrows

Omitting L₁ from the regression containing both treatments leaves confounding for A₁ via A₁←L₁→Y. The sum of coefficients is 1.806 in this distribution.

Exact model: U∼Bernoulli(0.3), independent A₀∼Bernoulli(0.5), L₁=A₀ XOR U, P(A₁=1|L₁)=0.2+0.6L₁ and Y=A₁+L₁+U. The A₁ decision has independent innovation. Enumerating eight states gives E[Y⁰⁰]=0.6 and E[Y¹¹]=2.0. These are not real observations.

Lack of adjustment does not bias every question: A₀ is randomized and its marginal effect allowing A₁ to act naturally is 0.64. The dilemma above concerns joint regimes. The g-formula and IPW require consistency, sequential ignorability and positivity. See Hernán y Robins.

Method
Method contrast1.806
True causal contrast1.400
E[Y⁰⁰] / E[Y¹¹]0.6 / 2.0
Compare the regime contrast with two regressions and observe which paths adjustment opens or blocks.

The question and available history

Fix the order L0,A0,L1,A1,YL_0,A_0,L_1,A_1,Y, where each action is chosen after observing history H0=L0H_0=L_0 and H1=(L0,A0,L1)H_1=(L_0,A_0,L_1). For static regime aˉ=(a0,a1)\bar a=(a_0,a_1), YaˉY^{\bar a} is the potential outcome if those actions are fixed. Dynamic regime d=(d0,d1)d=(d_0,d_1) assigns At=dt(Ht)A_t=d_t(H_t) and has value E[Yd]E[Y^d].

Sequential exchangeability requires, at each time, no unmeasured confounding of the current action with future regime outcomes conditional on available history. Consistency, no interference, and positivity are also needed: every action prescribed by the regime must have positive probability in histories it can reach. A temporal SWIG separates intervention-fixed values from observed random values and helps represent those conditions; it does not verify them.

Positivity is relative to population and strategy: if a regime-compatible history has positive probability, the prescribed action must be possible there. A rare pattern in a finite sample can create a practical problem even with positive population probability. In a SWIG under (a0,a1)(a_0,a_1), fixed action parts enter descendant equations and L1a0L_1^{a_0} precedes the second decision; later variables are not conditioned on to justify its assignment.

The g-formula

For discrete variables, the g-formula for a static two-decision strategy is

E[Ya0,a1]=∑l0,l1E[Y∣l0,a0,l1,a1] P(l1∣l0,a0)P(l0).E[Y^{a_0,a_1}]= \sum_{l_0,l_1} E[Y\mid l_0,a_0,l_1,a_1]\, P(l_1\mid l_0,a_0)P(l_0).

The proof uses iterated expectation twice: first relate the potential outcome to the observed conditional mean under the later action, then relate the intervened distribution of L1L_1 to that observed under A0=a0A_0=a_0. Exchangeability at each step permits substitution; consistency links the regime to corresponding observations. For continuous variables integrate instead of summing.

For example, fixing L0=l0L_0=l_0, the first application decomposes the mean over possible values of L1a0L_1^{a_0}. Within each, exchangeability of A1A_1 allows replacing the potential-outcome mean by the mean among those with that history receiving a1a_1. Exchangeability of A0A_0 replaces the distribution of L1a0L_1^{a_0} with P(L1∣L0=l0,A0=a0)P(L_1\mid L_0=l_0,A_0=a_0). Finally average over P(L0)P(L_0). Every replacement needs support: there is no observed mean to substitute when the relevant action never occurs in that history.

A dynamic regime substitutes ata_t with dt(Ht)d_t(H_t) in each factor. To estimate by simulation, generate L0L_0, fix A0A_0, generate L1L_1 under that action, apply d1d_1 to the simulated history, and generate or average YY. Do not simply reuse factual L1L_1 for a unit whose first action changed: it belongs to another history. Parametric estimation approximates conditional distributions with models and is sensitive to misspecification.

InteractiveSimulate histories under a policy

We generate 3,000 individuals with L₀ ∼ Bernoulli(0.4) and set A each period according to the strategy. We then sample Lₜ₊₁ with probability 0.12 + 0.65 Lₜ − 0.10 Aₜ. Here the outcome is Yₜ = Lₜ: the graph shows prevalence, not survival.

  • Never
  • Always
  • Only if L=1
0 %15 %30 %45 %60 %0123456Period t
t = 6

One g-formula step. At t=5, exact prevalence is 27.3 %. For the chosen strategy, P(Lₜ₊₁=1 | Lₜ=0)=12 % and P(Lₜ₊₁=1 | Lₜ=1)=67 %. Averaging transitions using prior-period proportions gives 27.0 %.

First 24 individuals, strategy “Only if L=1”, at t=6: filled square means L=1; empty means L=0. Readouts and curves use all 3,000.

The transition is known by construction, not estimated. Strategies share random numbers for easier comparison; this simulated coupling does not identify joint individual effects. With observational data, identifying each curve requires consistency, sequential exchangeability and positivity; estimating it also requires appropriate models.

Highlighted strategy
Period6 / 6
Simulation27.7 %
Exact value27.0 %
Seed2724
Generate trajectories under three rules with a known mechanism and compare the sample with the exact distribution.

The g-null paradox describes a specification difficulty: in certain models with treatment-affected confounders, causal-null restrictions and ordinary parametric families can be incompatible. It does not mean the g-formula is algebraically false or every test always rejects. See the review by McGrath and colleagues.

Weights along a trajectory

For a particular static strategy define

Waˉ=∏t=011{At=at}P(At=at∣Ht).W^{\bar a}=\prod_{t=0}^1 \frac{1\{A_t=a_t\}}{P(A_t=a_t\mid H_t)}.

With true probabilities, consistency, sequential exchangeability, and positivity, E[WaˉY]=E[Yaˉ]E[W^{\bar a}Y]=E[Y^{\bar a}]. This population identity reconstructs the distribution under fixed action for each history using the indicator and denominator. A Horvitz–Thompson mean with known probabilities is unbiased under suitable sampling; estimating propensities or dividing by observed weight sum generally does not preserve exact finite-sample unbiasedness.

Marginal structural models describe a family of potential means and are often fitted in a weighted pseudopopulation. For the observed trajectory, one possible stabilized weight is

SW=∏t=01P(At∣Aˉt−1)P(At∣Ht).SW=\prod_{t=0}^1 \frac{P(A_t\mid \bar A_{t-1})} {P(A_t\mid H_t)}.

Each probability corresponds to the action actually observed: for At=0A_t=0 it is one minus the probability of At=1A_t=1. The numerator defines a normalized reference mechanism; if it includes baseline covariates, the MSM and standardization must agree with that choice. With true mechanisms and support, E[SW]=1E[SW]=1. The unstabilized product of inverse observed-trajectory probabilities does not have mean one: with two positive actions at each of KK decisions, its expectation is 2K2^K. It differs from the indicator weight for a fixed strategy.

An empirical mean near one is a diagnostic, not proof of exchangeability or positivity. Examine extremes, distribution by history, and effective sample size ESS=(∑iwi)2/∑iwi2ESS=(\sum_iw_i)^2/\sum_iw_i^2. Truncating weights changes the estimator and may reduce spread at the cost of bias; it does not guarantee lower mean squared error in every setting. Stabilization does not guarantee ESS increases in every DGP. See Robins, Hernán and Brumback and Cole and Hernán.

If there is attrition, define Ct=0C_t=0 as “remains observed” and when it is measured. Under conditional censoring independence and positivity among those still observed, incorporate inverse probability of remaining uncensored into the product, with the corresponding stabilizing numerator if used. A missing outcome does not become zero; censoring requires its own models and assumptions.

InteractiveAccumulated weights

Each bar sums the probability of trajectories whose weight falls in that interval. Blue: uncapped; orange: chosen cap. The horizontal scale is log₁₀(weight), making the tails visible.

32 %0 %−1.32.7log₁₀(weight)
  • Original weight
  • Capped weight

Exact model: L₀∼Bernoulli(0.4), P(Aₜ=1|Lₜ=0)=0.15, P(Aₜ=1|Lₜ=1)=0.85 and P(Lₜ₊₁=1|Lₜ,Aₜ)=0.12+0.65Lₜ−0.10Aₜ. All trajectories and their probabilities are enumerated; there are no real data or censoring.

The unstabilized weight multiplies 1/P(Aₜ|Lₜ); the stabilized weight multiplies P(Aₜ|A₀,…,Aₜ₋₁)/P(Aₜ|Lₜ), with numerator obtained by filtering history. Their uncapped population means are 2ᵀ and 1, respectively. ESS/N=(EW)²/E[W²] is a population concentration measure, the limit of relative ESS with many trajectories; stabilization need not increase it.

To measure truncation bias we separately use the Horvitz-Thompson estimator for “always treat”, with Y=Lₜ at the end and N=400. Its true value is 0.1183 and its capped expectation is 0.0932. This calculation caps the final unstabilized weight at c, even when the histogram shows stabilized weights. The standard deviation is exact under this model; a finite estimator may leave [0,1]. Truncation changes bias and does not guarantee improved mean squared error.

Causal validity of IPW in an application requires sequential consistency, ignorability and positivity, as well as suitable probability models. See Robins, Hernán y Brumback (2000).

4
Displayed weight
2
Cap c30
Uncapped mean1.000
ESS/N with cap0.1394
HT bias−0.0252
HT standard deviation, N=4000.0310
Compare weights and effective sample size as horizon, stabilization, and cap vary.

Choose and evaluate a rule

Dynamic treatment regimes answer “what to do given the history.” With two decisions, Q-learning estimates backward

Q1(h1,a1)=E[Y∣H1=h1,A1=a1],d1(h1)∈arg⁡max⁡aQ1(h1,a),Q_1(h_1,a_1)=E[Y\mid H_1=h_1,A_1=a_1], \quad d_1(h_1)\in\arg\max_a Q_1(h_1,a), Q0(h0,a0)=E[max⁡aQ1(H1,a)∣H0=h0,A0=a0],d0(h0)∈arg⁡max⁡aQ0(h0,a).Q_0(h_0,a_0)=E[\max_a Q_1(H_1,a)\mid H_0=h_0,A_0=a_0], \quad d_0(h_0)\in\arg\max_a Q_0(h_0,a).

The maximum defines the decision objective; a rule learned from finite data need not be truly optimal. Separate policy-learning and evaluation data or use cross-fitting. Near ties, the maximum operator can cause nonregular inference. A-learning models action contrasts and needs its own conditions; Q-learning is not automatically doubly robust.

In a binary stage, the A-learning contrast or blip is the difference between values of the two actions for a given history under a specified continuation. Its sign selects the action when maximizing the outcome. Instead of fitting the whole mean as in Q-learning, one can model this contrast with assignment and outcome nuisance models; guarantees depend on formulation and cannot be transferred unchecked. The connection to Q-learning in RL is the same value recursion, but actions in an observational record were not necessarily random and off-policy evaluation needs justification.

To evaluate fixed policy dd in another sample, define πt=1{At=dt(Ht)}\pi_t=1\{A_t=d_t(H_t)\}, pt=P(At∣Ht)p_t=P(A_t\mid H_t), Vt(Ht)=Qt(Ht,dt(Ht))V_t(H_t)=Q_t(H_t,d_t(H_t)) and V2=YV_2=Y. An augmented longitudinal score is

V0(H0)+π0p0{V1(H1)−Q0(H0,A0)}+π0π1p0p1{Y−Q1(H1,A1)}.V_0(H_0)+\frac{\pi_0}{p_0}\{V_1(H_1)-Q_0(H_0,A_0)\} +\frac{\pi_0\pi_1}{p_0p_1}\{Y-Q_1(H_1,A_1)\}.

In this evaluation, Q0Q_0 is the conditional mean value of continuing with rule d1d_1, not necessarily the maximum if evaluating a nonoptimal rule. With true models and the causal assumptions above, the score expectation is policy value. Robustness depends on which sequential models are correct and how they are estimated; it is not enough to declare any “one model” correct. This connects to offline policy evaluation in reinforcement learning: histories are states only if the chosen representation retains information relevant to transitions, assignment, and outcome.

Before fitting, emulate a target trial: define eligibility, time zero, strategies, follow-up, outcome, contrast, and uncertainty. Specifying order avoids, for example, assigning a strategy using information available only after initiation.

In the alert example the trial might include eligible services at the start of week zero and compare “always escalate” with “escalate when observed load exceeds a threshold.” Decide how load is measured before each action, follow-up duration, how attrition and rule deviations are handled, and final outcome. If services affect each other, no interference is doubtful and the design must change or an intervention accounting for it be defined.

NHEFS and the limits of a real comparison

Causal Inference: What If uses NHEFS to study smoking cessation and weight change. That extract represents one cessation decision in the study window and later observation; it does not contain our example’s weekly longitudinal decisions. The real-data cell estimates a one-decision comparison and separates treatment from final-observation weights. Exchangeability and selection assumptions remain substantive; the example does not by itself prove a causal conclusion.

Lab: strategies, weights, and policies

The synthetic panel has an explicit mechanism, known truth, and reproducible seed. Separate the policy-learning sample from value evaluation. NHEFS comparisons are complementary, not purported validation of repeated treatment in those data.

The first cell calculates four true means by enumeration; subsequent cells estimate transitions and average simulated outcomes. That simulation’s Monte Carlo error measures only draw noise with fixed models, not uncertainty from estimating them. The saturated MSM permits a different mean for every action pair; a marginal model without interaction would impose an additional restriction.

Longitudinal experiment with known truth

Each stage’s treatment depends on observed history; unobserved U affects workload and outcome but does not directly enter assignment after conditioning on that history. The experiment uses saturated transition and outcome tables. Truth is calculated by enumerating mechanism variables, not from estimates. Run cells in order.

[ ]Generate the panel and calculate truthBrowser
import numpy as np

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def generate(n, seed):
    """L0=B; U afecta a L1 e Y, pero no decide el tratamiento dada la historia."""
    rng = np.random.default_rng(seed)
    B = rng.binomial(1, .5, n)
    U = rng.binomial(1, .5, n)
    A0 = rng.binomial(1, sigmoid(-.2 + .5 * B))
    L = rng.binomial(1, sigmoid(-1 + .6 * B + .9 * A0 + U))
    A1 = rng.binomial(1, sigmoid(-.8 + .2 * B + .4 * A0 + 1.4 * L))
    Y = 2 + .3 * B + .8 * L + (.4 - .9 * B) * A0 + (.8 - 1.6 * L) * A1 + 1.2 * U + rng.normal(0, .4, n)
    return dict(B=B, U=U, A0=A0, L=L, A1=A1, Y=Y)

train = generate(16000, 272401)
test = generate(20000, 272402)

def true_value(rule0, rule1):
    """Enumera B, U y L en el régimen; integra el error de media cero."""
    result = 0.
    for b in (0, 1):
        for u in (0, 1):
            a0 = int(rule0(b))
            pl = float(sigmoid(-1 + .6 * b + .9 * a0 + u))
            for l in (0, 1):
                a1 = int(rule1(b, a0, l))
                mean = 2 + .3*b + .8*l + (.4-.9*b)*a0 + (.8-1.6*l)*a1 + 1.2*u
                result += .25 * (pl if l else 1-pl) * mean
    return result

truth = {(a0, a1): true_value(lambda b, a=a0: a, lambda b, a, l, v=a1: v)
         for a0 in (0, 1) for a1 in (0, 1)}
optimal = true_value(lambda b: 1-b, lambda b, a0, l: 1-l)
print('Valor verdadero por estrategia fija:', {k: round(v, 4) for k, v in truth.items()})
print('Regla óptima: A0=1−B, A1=1−L; valor:', round(optimal, 4))
print('Muestras independientes: entrenamiento', len(train['Y']), 'evaluación', len(test['Y']))
assert np.isclose(optimal, 3.75)
[ ]Fit transitions, propensities, and outcomeBrowser
def fitted_tables(data):
    """Probabilidades y medias saturadas, estimadas en entrenamiento."""
    b,a0,l,a1,y = [data[k] for k in ('B','A0','L','A1','Y')]
    e0 = np.empty(2)
    e1 = np.empty((2,2,2))
    pL = np.empty((2,2))
    outcome = np.empty((2,2,2,2))
    for B in (0,1):
        e0[B] = a0[b==B].mean()
        for A in (0,1):
            mask = (b==B)&(a0==A)
            if mask.sum() < 10: raise ValueError('Falta soporte de entrenamiento')
            pL[B,A] = l[mask].mean()
            for L in (0,1):
                m = mask & (l==L)
                if m.sum() < 10: raise ValueError('Falta soporte de entrenamiento')
                e1[B,A,L] = a1[m].mean()
                for A1 in (0,1):
                    m2 = m & (a1==A1)
                    if m2.sum() < 10: raise ValueError('Falta soporte de entrenamiento')
                    outcome[B,A,L,A1] = y[m2].mean()
    if np.any((e0<=0)|(e0>=1)) or np.any((e1<=0)|(e1>=1)):
        raise ValueError('Probabilidad estimada fuera del soporte')
    return e0,e1,pL,outcome

e0,e1,pL,m = fitted_tables(train)
print('Propensión A0=1 por B:', np.round(e0, 4))
print('Rango de P(A1=1|B,A0,L):', round(e1.min(), 4), round(e1.max(), 4))
print('Los modelos se ajustan sin U, no observada; A1 depende solo de la historia medida.')
[ ]Simulate the g-formulaBrowser
rg = np.random.default_rng(272403)
n_mc = 80000
bmc = rg.choice(train['B'], n_mc, replace=True)
g_est = {}
for a0 in (0,1):
    lmc = rg.binomial(1, pL[bmc,a0])
    for a1 in (0,1):
        predictions = m[bmc,a0,lmc,a1]
        g_est[a0,a1] = float(predictions.mean())
        mcse = float(predictions.std(ddof=1)/np.sqrt(n_mc))
        print('Estrategia', (a0,a1), 'verdad', round(truth[a0,a1],4),
              'g-fórmula', round(g_est[a0,a1],4), 'EE Monte Carlo', round(mcse,4))
print('El EE Monte Carlo no incluye la incertidumbre de estimar los modelos.')
[ ]Fit the weighted MSMBrowser
b,a0,l,a1,y = [test[k] for k in ('B','A0','L','A1','Y')]
p0 = np.where(a0==1,e0[b],1-e0[b])
p1 = np.where(a1==1,e1[b,a0,l],1-e1[b,a0,l])
train_a0,train_a1 = train['A0'],train['A1']
num0_one = train_a0.mean()
num1_one = np.array([train_a1[train_a0==a].mean() for a in (0,1)])
num0 = np.where(a0==1,num0_one,1-num0_one)
num1 = np.where(a1==1,num1_one[a0],1-num1_one[a0])
sw = num0*num1/(p0*p1)
design = np.column_stack([np.ones(len(y)),a0,a1,a0*a1])
coef = np.linalg.lstsq(design * np.sqrt(sw)[:,None], y*np.sqrt(sw), rcond=None)[0]
print('Peso estabilizado medio:', round(sw.mean(),4), '| ESS:', round(sw.sum()**2/np.sum(sw**2),1))
print('Percentiles 1, 50, 99:', np.round(np.quantile(sw,[.01,.5,.99]),3))
for aa0 in (0,1):
    for aa1 in (0,1):
        estimate = np.array([1,aa0,aa1,aa0*aa1]) @ coef
        print('MSM', (aa0,aa1), 'estimado', round(float(estimate),4), 'verdad', round(truth[aa0,aa1],4))
print('El MSM saturado tiene cuatro medias; los pesos y el modelo se estimaron fuera de evaluación.')
[ ]Compare working regressionsBrowser
# Dos regresiones de trabajo: ilustran contrastes condicionados diferentes.
# Ninguna está definida automáticamente como efecto de pasar de (0,0) a (1,0).
def regression_coefficient(data, adjust_l):
    B,A0,A1,L,Y = [data[k] for k in ('B','A0','A1','L','Y')]
    cols = [np.ones(len(Y)),B,A0,A1]
    if adjust_l: cols.append(L)
    return np.linalg.lstsq(np.column_stack(cols),Y,rcond=None)[0][2]

print('Contraste verdadero de regímenes (1,0) − (0,0):', round(truth[1,0]-truth[0,0],4))
print('Coeficiente A0 sin ajustar L:', round(regression_coefficient(test,False),4))
print('Coeficiente A0 ajustando L:', round(regression_coefficient(test,True),4))
print('Son contrastes de regresión, no efectos totales automáticamente comparables.')

Learn and evaluate a policy

The linear implementation uses explicit basis functions and the second uses boosting. In code q2 denotes the last decision and q1 the first: they correspond respectively to Q1Q_1 and Q0Q_0 in earlier formulas. Both train on one sample and evaluate on another, with propensities fitted in training. Each learned rule’s truth is enumerated from the known mechanism; reported standard error concerns evaluation conditional on trained models.

[ ]Learn the last decisionBrowser
from sklearn.ensemble import HistGradientBoostingRegressor

def features2(B,A0,L,A1):
    # Función base saturada en B,A0,L, más contraste A1 que depende de L.
    return np.column_stack([np.ones(len(B)),B,A0,L,B*A0,B*L,A0*L,B*A0*L,A1,A1*L])

def features1(B,A0):
    return np.column_stack([np.ones(len(B)),B,A0,B*A0])

tb,ta0,tl,ta1,ty = [train[k] for k in ('B','A0','L','A1','Y')]
q2_coef = np.linalg.lstsq(features2(tb,ta0,tl,ta1), ty, rcond=None)[0]
def q2_linear(B,A0,L,A1):
    return features2(B,A0,L,A1) @ q2_coef

q2_boost = HistGradientBoostingRegressor(max_iter=50, max_leaf_nodes=7,
                                        learning_rate=.12, random_state=272404)
q2_boost.fit(np.column_stack([tb,ta0,tl,ta1]),ty)
def q2_tree(B,A0,L,A1):
    return q2_boost.predict(np.column_stack([B,A0,L,A1]))

print('Q2 lineal y boosting ajustados solo en entrenamiento.')
[ ]Learn the first decisionBrowser
zeros,ones = np.zeros_like(ta1),np.ones_like(ta1)
target_linear = np.maximum(q2_linear(tb,ta0,tl,zeros),q2_linear(tb,ta0,tl,ones))
q1_coef = np.linalg.lstsq(features1(tb,ta0),target_linear,rcond=None)[0]
def q1_linear(B,A0): return features1(B,A0) @ q1_coef

target_tree = np.maximum(q2_tree(tb,ta0,tl,zeros),q2_tree(tb,ta0,tl,ones))
q1_boost = HistGradientBoostingRegressor(max_iter=50, max_leaf_nodes=7,
                                        learning_rate=.12, random_state=272405)
q1_boost.fit(np.column_stack([tb,ta0]),target_tree)
def q1_tree(B,A0): return q1_boost.predict(np.column_stack([B,A0]))
print('Q1 ajustado hacia atrás, con máximo de Q2 y sin usar datos de evaluación.')
[ ]Evaluate policies out of sampleBrowser
def evaluate_policy(q1,q2):
    B,A0,L,A1,Y = [test[k] for k in ('B','A0','L','A1','Y')]
    z,o = np.zeros_like(B),np.ones_like(B)
    d0 = (q1(B,o)>q1(B,z)).astype(int)
    d1 = (q2(B,A0,L,o)>q2(B,A0,L,z)).astype(int)
    prop0 = np.where(A0==1,e0[B],1-e0[B])
    prop1 = np.where(A1==1,e1[B,A0,L],1-e1[B,A0,L])
    w0 = (A0==d0)/prop0
    w01 = w0*(A1==d1)/prop1
    v0 = q1(B,d0)
    v1 = q2(B,A0,L,d1)
    score = v0 + w0*(v1-q1(B,A0)) + w01*(Y-q2(B,A0,L,A1))
    ipw = w01*Y
    def rule0(b):
        arr=np.array([b]); return int(q1(arr,np.ones(1,dtype=int))[0] > q1(arr,np.zeros(1,dtype=int))[0])
    def rule1(b,a,l):
        B0,A00,L0=np.array([b]),np.array([a]),np.array([l])
        return int(q2(B0,A00,L0,np.ones(1,dtype=int))[0] > q2(B0,A00,L0,np.zeros(1,dtype=int))[0])
    actual = true_value(rule0,rule1)
    return dict(ipw=float(ipw.mean()), aipw=float(score.mean()),
                se=float(score.std(ddof=1)/np.sqrt(len(score))), true=actual,
                d0=[rule0(b) for b in (0,1)],
                d1=[rule1(b,a,l) for b in (0,1) for a in (0,1) for l in (0,1)])

for name,q1,q2 in [('lineal',q1_linear,q2_linear),('boosting',q1_tree,q2_tree)]:
    result = evaluate_policy(q1,q2)
    print(name, 'regla A0 por B:', result['d0'], 'reglas A1 por B,A0,L:', result['d1'])
    print('Valor verdadero de la regla:', round(result['true'],4),
          '| IPW:', round(result['ipw'],4), '| AIPW:', round(result['aipw'],4),
          '| EE de evaluación condicional a la regla:', round(result['se'],4))
print('El óptimo del modelo vale', round(optimal,4), '; su comparación no demuestra optimalidad general.')
print('La puntuación AIPW longitudinal usa el producto de propensiones y residuos en ambas etapas.')

One observed decision: NHEFS

Download the NHEFS extract from a versioned mirror of the book’s data. The comparison includes one-window treatments, not repeated decision histories. Treatment and observation models use baseline covariates; causal interpretation needs additional assumptions. Weighted differences depend on specification and are not a randomized trial.

[ ]Download NHEFSBrowser
import io
import pandas as pd
from pyodide.http import pyfetch

# Espejo de causallib fijado a un commit; datos del libro What If.
url = ('https://raw.githubusercontent.com/BiomedSciAI/causallib/'
       'de64cf65d0e2fa1cc5a12d2cc847c970fc43a717/'
       'causallib/datasets/data/nhefs/NHEFS.csv')
respuesta = await pyfetch(url)
if not respuesta.ok:
    raise RuntimeError(f'Descarga NHEFS: HTTP {respuesta.status}')
nhefs = pd.read_csv(io.StringIO(await respuesta.string()))
assert nhefs.shape == (1629, 64)
assert nhefs.seqn.is_unique
print('Participantes:', len(nhefs), 'peso final observado:', nhefs.wt82_71.notna().sum())
print('Cambio de peso observado por qsmk:')
print(nhefs.groupby('qsmk').wt82_71.agg(['count', 'mean']).round(4))
[ ]Prepare logistic fittingBrowser
import numpy as np
from scipy.special import expit

def logistica_newton(X, y):
    X, y = np.asarray(X, float), np.asarray(y, float)
    beta = np.zeros(X.shape[1])
    for it in range(100):
        p = expit(X @ beta)
        paso = np.linalg.solve(X.T @ ((p*(1-p))[:, None]*X), X.T @ (y-p))
        beta += paso
        if np.max(np.abs(paso)) < 1e-9:
            return beta, it+1
    raise RuntimeError('La regresión logística no convergió')

print('NumPy y función logística cargados')
[ ]Estimate treatment propensityBrowser
# Restricción inicial explícita: las variables pretratamiento usadas aquí
# están completas en este extracto. El resultado final falta en 63 filas.
campos = ['qsmk', 'sex', 'race', 'age', 'wt71', 'smokeintensity',
          'smokeyrs', 'education', 'exercise', 'active']
assert not nhefs[campos].isna().any().any()
L = pd.DataFrame({'constante': np.ones(len(nhefs)),
                  'sex': nhefs.sex, 'race': nhefs.race})
for nombre in ['age', 'wt71', 'smokeintensity', 'smokeyrs']:
    # Reescalar no cambia el espacio lineal del modelo cuadrático.
    z = (nhefs[nombre] - nhefs[nombre].mean()) / nhefs[nombre].std()
    L[nombre] = z
    L[nombre + '_2'] = z*z
for nombre, niveles in [('education', [2, 3, 4, 5]),
                        ('exercise', [1, 2]), ('active', [1, 2])]:
    for nivel in niveles:
        L[f'{nombre}_{nivel}'] = (nhefs[nombre] == nivel).astype(float)
assert np.linalg.matrix_rank(L.to_numpy()) == L.shape[1]
A = nhefs.qsmk.to_numpy(dtype=float)
R = nhefs.wt82_71.notna().to_numpy(dtype=int)
coef_a, iter_a = logistica_newton(L, A)
e = expit(L.to_numpy() @ coef_a)
Lc = L.copy()
Lc['qsmk'] = A
assert np.all((e > 0) & (e < 1))
print('Propensión estimada: min, mediana, max', np.round(np.quantile(e, [0, .5, 1]), 4))
print('Iteraciones Newton tratamiento:', iter_a)
[ ]Estimate observation probabilityBrowser
coef_r, iter_r = logistica_newton(Lc, R)
r = expit(Lc.to_numpy() @ coef_r)
assert np.all((r > 0) & (r < 1))
print('Probabilidad de peso observado: min, mediana, max', np.round(np.quantile(r, [0, .5, 1]), 4))
print('Iteraciones Newton observación:', iter_r)
[ ]Compare weighted meansBrowser
observados = R == 1
Y = nhefs.wt82_71.to_numpy()
# Numerador del tratamiento: distribución marginal en la muestra completa.
p = A.mean()
wa = np.where(A == 1, p/e, (1-p)/(1-e))
# Numerador de observación dado tratamiento, para conservar su distribución.
pr = np.array([R[A == a].mean() for a in (0, 1)])
wc = pr[A.astype(int)]/r

def medias_ponderadas(w):
    return np.array([np.average(Y[observados & (A == a)],
                                weights=w[observados & (A == a)])
                     for a in (0, 1)])

for nombre, w in [('Sin ajustar', np.ones(len(A))),
                  ('Solo tratamiento', wa), ('Tratamiento y observación', wa*wc)]:
    medias = medias_ponderadas(w)
    wo = w[observados]
    ess = wo.sum()**2 / (wo @ wo)
    print(nombre, 'medias control/tratamiento:', np.round(medias, 4),
          'diferencia:', round(medias[1]-medias[0], 4),
          'ESS observados:', round(ess, 1))
print('Pesos tratamiento, media/min/max:', np.round([wa.mean(), wa.min(), wa.max()], 4))
print('Peso combinado entre observados, media/min/max:',
      np.round([(wa*wc)[observados].mean(), (wa*wc)[observados].min(),
                (wa*wc)[observados].max()], 4))

# WLS saturada en tratamiento coincide con diferencia de medias ponderadas.
X = np.column_stack([np.ones(observados.sum()), A[observados]])
W = (wa*wc)[observados]
beta_wls = np.linalg.solve(X.T @ (W[:, None]*X), X.T @ (W*Y[observados]))
assert np.allclose(beta_wls[1], np.diff(medias_ponderadas(wa*wc))[0], atol=1e-9)
print('Contraste WLS igual a diferencia ponderada:', round(beta_wls[1], 4))

Comparison with statsmodels checks both logistic fits on the same design. Numerical agreement verifies implementation, not validity of causal assumptions.

[ ]Load statsmodelsBrowser
from statsmodels.discrete.discrete_model import Logit
print('Modelo logístico de statsmodels disponible')
[ ]Check treatmentBrowser
ref_a = Logit(A, L).fit(disp=False, maxiter=100)
if not ref_a.mle_retvals['converged']:
    raise RuntimeError('El ajuste de tratamiento de statsmodels no convergió')
np.testing.assert_allclose(e, ref_a.predict(L), atol=1e-9, rtol=0)
print('Coinciden las propensiones de tratamiento con statsmodels.')
[ ]Check observationBrowser
ref_r = Logit(R, Lc).fit(disp=False, maxiter=100)
if not ref_r.mle_retvals['converged']:
    raise RuntimeError('El ajuste de observación de statsmodels no convergió')
np.testing.assert_allclose(r, ref_r.predict(Lc), atol=1e-9, rtol=0)
print('Coinciden las probabilidades de observación con statsmodels.')

Exercises

ProofTwo uses of iterated expectation
Prove: Consider the order L0,A0,L1,A1,YL_0,A_0,L_1,A_1,Y, consistency, sequential exchangeability, and positivity for (a0,a1)(a_0,a_1). Derive the g-formula for E[Ya0,a1]E[Y^{a_0,a_1}].
The proof will appear here as you work.

Step 1 of 3. Which distribution of L₁ is needed under the fixed first action?

ProofReconstruct a fixed strategy
Prove: With true probabilities pt=P(At=at∣Ht)>0p_t=P(A_t=a_t\mid H_t)>0, consistency, and sequential exchangeability, prove E[Y∏t1{At=at}/pt]=E[Ya0,a1]E[Y\prod_t1\{A_t=a_t\}/p_t]=E[Y^{a_0,a_1}].
The proof will appear here as you work.

Step 1 of 3. What does the last-decision factor do inside an expectation conditional on H₁?

NumericThree observed decisions
For a trajectory matching a fixed strategy, conditional probabilities of observed actions are 0.8, 0.5, and 0.25. Calculate the product of their inverses.
NumericAdd the numerator
For the same trajectory, the reference mechanism assigns probabilities 0.6, 0.5, and 0.4 to the observed actions. Calculate the stabilized weight.
CodeWeight trajectories
Implement stabilized_weights(df, id, time, treatment, confounders). df has one row per decision, a unique index, and unique id-time pairs; each person has consecutive integer times from 0, binary treatment, and finite numeric confounders observed before deciding. Column names are distinct and confounders is a nonempty list. Return a Series with the original index and cumulative stabilized product through each row. Fit two pooled logistic regressions: the numerator uses an intercept, time indicators from 1, and previous treatment (0 at time 0); the denominator adds confounders. If there is only one stage omit the constant lag. Use observed-action probability, order each person temporally, and restore original order. Raise ValueError for invalid inputs, histories with gaps, rank-deficient matrices, nonconvergent fits, or excessively extreme probabilities; do not silently clip. Confounders may include the necessary summarized history: this particular one-lag model does not guarantee causal exchangeability.
def stabilized_weights(df, id, time, treatment, confounders):
  """Ajusta propensiones binarias y devuelve el peso acumulado por fila."""
  raise NotImplementedError
Shift+Enter to run
QuizIntermediate workload
An initial decision changes workload, which affects the next decision and outcome. What method can model its distribution under each treatment history?
QuizHistory-related attrition
Follow-up ends earlier for people with a certain observed history. What does censoring weighting require?
QuizExtreme weights
An MSM has a few very large weights. What is the more careful interpretation?
QuizA learned policy
An algorithm selects a rule using all data and evaluates the same people, using later information to define eligibility. What is the problem?

Check both products after attempting the exercises:

[ ]Check weights for three decisionsBrowser
from math import prod
denominador = [.8, .5, .25]
numerador = [.6, .5, .4]
peso_no_estabilizado = 1 / prod(denominador)
peso_estabilizado = prod(numerador) / prod(denominador)
assert abs(peso_no_estabilizado-10) < 1e-12
assert abs(peso_estabilizado-1.2) < 1e-12
print('Pesos de la trayectoria:', peso_no_estabilizado, peso_estabilizado)