Module contents
Lesson 14 of 28Core 115 min

Adjustment under ignorability: standardization, matching, propensity scores and IPW

When backdoor adjustment and overlap identify an effect, estimate it through standardization, matching, or propensity weighting. Study balance and overlap diagnostics and reproduce the LaLonde benchmark.

After this lesson you can

  • Show how ignorability and positivity identify ATE and connect them to backdoor.
  • Prove the propensity-score balancing theorem.
  • Implement g-computation, bias-corrected matching, and Horvitz–Thompson and Hájek IPW.
  • Diagnose overlap and balance and choose trimming, another estimand, or abandoning the analysis.
  • Reproduce the LaLonde benchmark using NSW data and explain differences between methods.

Before you start

The comparison that did not happen

A company wants to know whether a security course reduces incidents. Workers who choose it may have more experience, have already suffered an incident, or hold riskier jobs. Comparing observed means mixes the course effect with those differences. Even with tenure and role records, you must justify that they contain the relevant common causes of training and outcome. The previous lesson’s causal calculus helps decide what to measure; now estimate, diagnose, and recognize when comparison is too fragile.

Write T∈{0,1}T\in\{0,1\}, prior covariates XX, and potential outcomes Y(0),Y(1)Y(0),Y(1). The average effect in the target population is τ=E[Y(1)−Y(0)]\tau=E[Y(1)-Y(0)]. Assume consistency Y=Y(T)Y=Y(T), no interference under the chosen treatment definition, integrability, conditional ignorability (Y(0),Y(1))⊥T∣X(Y(0),Y(1))\perp T\mid X, and positivity 0<e(X)=P(T=1∣X)<10<e(X)=P(T=1\mid X)<1 almost surely in that population. Then, by iterated expectation,

E[Y(t)]=E{E[Y(t)∣X]}=E{E[Y(t)∣T=t,X]}=E{E[Y∣T=t,X]}.E[Y(t)]=E\{E[Y(t)\mid X]\} =E\{E[Y(t)\mid T=t,X]\} =E\{E[Y\mid T=t,X]\}.

Independence allows the second step and consistency the third. Thus, with μt(x)=E[Y∣T=t,X=x]\mu_t(x)=E[Y\mid T=t,X=x],

τ=EX[μ1(X)−μ0(X)].\tau=E_X[\mu_1(X)-\mu_0(X)].

Positivity does not require equal probabilities: it requires both treatments to be possible at values of XX making up the target population. A value very close to zero satisfies the mathematical condition but leaves a highly uncertain empirical comparison. If certain jobs never receive training, their effect cannot be recovered without additional assumptions.

In a correctly specified causal DAG, a prior set satisfying the backdoor criterion implies the appropriate counterfactual independence under the causal model; the intervention SWIG represents it by separation between TT and Y(t)Y(t) conditional on XX. These are not logically equivalent claims without assumptions: backdoor is a sufficient graphical criterion, while independence can arise through other structures or distributional restrictions. Neither regression nor a balance plot proves no hidden confounding remains.

Standardization: model both outcomes

G-computation fits models μ^1,μ^0\widehat\mu_1,\widehat\mu_0 and averages predictions over the same covariate distribution:

τ^g=1n∑i=1n[μ^1(Xi)−μ^0(Xi)].\widehat\tau_g=\frac1n\sum_{i=1}^n[\widehat\mu_1(X_i)-\widehat\mu_0(X_i)].

A linear regression without interactions imposes a constant effect; one per arm or one with interactions allows heterogeneity, subject to its specification. If only treated workers have long tenure, the control model extrapolates there: a figure may be precise according to the model yet depend on an untested functional form. Identification does not guarantee a particular regression is correct.

Match before comparing

Exact matching finds controls with the same XX and compares within strata; exact matches are scarce for continuous covariates. Nearest-neighbor matching minimizes distance. With replacement one control can serve multiple treated units, improving some matches but concentrating information; without replacement each control is used at most once and ordering or a global assignment algorithm matters. A caliper discards overly distant pairs, changing the represented population.

Euclidean distance depends on units. Mahalanobis uses d2(x,x′)=(x−x′)⊤S−1(x−x′)d^2(x,x')=(x-x')^\top S^{-1}(x-x') with invertible covariance matrix SS: it corrects scales and correlations but can be unstable if SS is nearly singular. In coarsened exact matching, group each variable into intervals defined before looking at outcomes and match exactly within cells; granularity trades similarity for losses. No distance makes an omitted cause observed.

To impute the control outcome of treated unit ii using neighbor jj, a regression correction is Yj+μ^0(Xi)−μ^0(Xj)Y_j+\widehat\mu_0(X_i)-\widehat\mu_0(X_j); proceed symmetrically for controls when targeting ATE. It corrects observed within-pair differences only to the extent captured by the outcome model. Abadie and Imbens formally study the bias of matching continuous covariates and this correction. A small distance on one dimension does not guarantee similarity in all covariates:

The problem is geometric: in many dimensions distance to the nearest neighbor can decrease slowly as sample size increases. Although XjX_j is the closest available control, its mean outcome can differ from the treated unit’s counterfactual by μ0(Xj)−μ0(Xi)\mu_0(X_j)-\mu_0(X_i). The correction approximates that difference with the model but adds its own specification risk. With replacement, account for the same control contributing multiple times; treating pairs as independent observations would underestimate or alter uncertainty without justification.

InteractiveMatching in two dimensions

Each line joins one of the first 12 treated units to its nearest control. Controls can be reused. Both axes use the same visual scale.

-2-2-1-1001122X₁X₂
  • Selected treated
  • Controls
  • Last pair
  • Most separated propensity pair
12 of 12 pairs

Data from a reproducible model: X₁ is uniform from -2 to 2, X₂ = 0.65X₁ + U with U uniform from -1 to 1; T is Bernoulli with logistic propensity 0.8X₁ + 0.8X₂. The true propensity is used here to isolate the effect of distance. Mahalanobis uses the joint covariance of all 70 units. Similar scores do not imply similar covariates for a particular pair.

Pairs shown12 / 12
Euclidean distance of last pair0.431
Propensity difference of last pair0.063
Most separated propensity pair: distance1.628
Most separated propensity pair: score difference0.001
Change the distance and follow pairs: proximity in score does not mean proximity in each covariate.

A score that balances distributions

The propensity score e(X)=P(T=1∣X)e(X)=P(T=1\mid X) is the probability of receiving treatment given prior covariates. It is an assignment probability, not the probability treatment works. Rosenbaum and Rubin proved it is a balancing score: T⊥X∣e(X)T\perp X\mid e(X).

The proof fits in a conditional expectation. Since ee is a function of XX,

P(T=1∣X,e)=e(X)=e=P(T=1∣e).P(T=1\mid X,e)=e(X)=e=P(T=1\mid e).

For binary TT, this establishes independence. If additionally Y(t)⊥T∣XY(t)\perp T\mid X, then

E[f(Y(t))∣T=t,e]=E{E[f(Y(t))∣X,T=t,e]∣T=t,e}=E{E[f(Y(t))∣X]∣e}=E[f(Y(t))∣e]E[f(Y(t))\mid T=t,e] =E\{E[f(Y(t))\mid X,T=t,e]\mid T=t,e\} =E\{E[f(Y(t))\mid X]\mid e\} =E[f(Y(t))\mid e]

for integrable functions ff: first use ignorability, then balance of XX. Equality for both arms gives Y(t)⊥T∣eY(t)\perp T\mid e at values with support. Dimensionality reduction works for the true population score; it does not guarantee an estimated score yields perfect balance in a finite sample. In particular, units with the same score can have very different covariates: the theorem compares complete distributions, not every pair.

Weight toward a target population

Inverse probability weighting changes the distribution represented by each arm. With known score, the Horvitz–Thompson ATE estimator and its normalized Hájek version are

τ^HT=1n∑i[TiYiei−(1−Ti)Yi1−ei],τ^H=∑iTiYi/ei∑iTi/ei−∑i(1−Ti)Yi/(1−ei)∑i(1−Ti)/(1−ei).\widehat\tau_{\rm HT}=\frac1n\sum_i\left[\frac{T_iY_i}{e_i}-\frac{(1-T_i)Y_i}{1-e_i}\right],\qquad \widehat\tau_{\rm H}=\frac{\sum_iT_iY_i/e_i}{\sum_iT_i/e_i}-\frac{\sum_i(1-T_i)Y_i/(1-e_i)}{\sum_i(1-T_i)/(1-e_i)}.

Identity E[TY/e(X)∣X]=E[Y(1)∣X]E[TY/e(X)\mid X]=E[Y(1)\mid X] and its control analogue justify HT; with the true score it is finite-sample unbiased under the assumptions and suitable sampling. Hájek is a ratio: generally not finite-sample unbiased, although consistent under regularity conditions. Normalizing can reduce sensitivity to fluctuations in the sum of weights; it does not fix positivity or confounding.

The same identity explains the pseudopopulation. For any integrable function hh, E[Th(X)/e(X)]=E[h(X)]E[Th(X)/e(X)]=E[h(X)] and E[(1−T)h(X)/(1−e(X))]=E[h(X)]E[(1-T)h(X)/(1-e(X))]=E[h(X)]. In the population, each weighted arm thus reproduces the original distribution of XX. In a finite sample the weighted versions do not exactly coincide, and equality may fail with a misspecified score. Variance may be large even under strict positivity: ordinary inference requires additional moments of weighted contributions, not merely that ee is never exactly zero or one.

For ATT, E[Y(1)−Y(0)∣T=1]E[Y(1)-Y(0)\mid T=1], treated units keep weight one and controls are weighted by e/(1−e)e/(1-e); their means are normalized separately. Controls then represent the distribution of XX among treated units, not the full population. Extreme weights amplify a few observations. Kish effective sample size,

ESS(w)=(∑iwi)2∑iwi2,ESS(w)=\frac{(\sum_iw_i)^2}{\sum_iw_i^2},

is a concentration diagnostic by arm, not the exact variance or an actual number of independent observations. The variance estimator must account for design and estimation procedure: a sandwich treating eie_i as known omits estimation of the assignment model. A stacked equation or, for regular estimators, a bootstrap refitting that model can be used.

InteractiveThe IPW pseudopopulation

Each circle is a unit; within each treatment state its area is proportional to its weight. The area scale adapts if an extreme weight appears. Each group’s vertical line marks its weighted mean X and the dashed line marks the full-sample mean.

T = 0T = 1-2-1012Covariate X
  • Controls
  • Treated
  • Full sample mean

Generated data: 160 equally spaced X values from −2 to 2, with reproducible T draws according to e(X)=1/(1+exp(−aX)); a is the chosen strength. The propensity is known in this simulation. Weights are T/e(X)+(1−T)/(1−e(X)); without weighting they equal 1.

For each arm, ESS=(Σw)²/Σw². It measures weight concentration, not variance or the actual number of observations. Convergence to the whole population is a population property: in this finite sample means can remain apart and an extreme weight can dominate them. Observed balance does not prove absence of unmeasured confounding.

1.5
Treated ESS25.3
Control ESS35.0
Maximum weight20.71
Assignment and weights come from an explicit model; also observe effective sample size by arm.

Overlap and a change of question

Examine score distributions by arm, maximum weights, and ESS. Overlap trimming with threshold aa set before examining outcomes retains a≤e(X)≤1−aa\le e(X)\le1-a and changes the target to the effect in the retained population. If e^\widehat e is used the region is estimated as well. No universal threshold or bias-removal guarantee exists: aggressive trimming can leave a small, different population. Without convincing support, narrow the question or acknowledge it cannot be answered.

Another option is bounded overlap weights w1=1−ew_1=1-e and w0=ew_0=e. They target

τATO=E[e(X)(1−e(X))(Y(1)−Y(0))]E[e(X)(1−e(X))],\tau_{\rm ATO}=\frac{E[e(X)(1-e(X))(Y(1)-Y(0))]}{E[e(X)(1-e(X))]},

the effect in a population giving more weight to those who could receive either treatment. Li, Morgan and Zaslavsky study these weights and their efficiency under specific assumptions, not universal superiority over all estimators. ATO, ATT, and ATE may differ under heterogeneous effects.

The overlap population arises because, conditional on XX, both E[T(1−e)∣X]E[T(1-e)\mid X] and E[(1−T)e∣X]E[(1-T)e\mid X] equal e(1−e)e(1-e). After normalizing weights both arms have the same covariate distribution. Among other conditions, equal and constant conditional arm variances are essential to the authors’ efficiency result. Bounding weights may help even if those conditions fail, but ATO remains a different question.

InteractiveIs there anyone to compare?

Each bar counts units in the full sample. Shaded regions lie outside the trim; the horizontal axis is the estimated propensity.

00.250.50.751
  • Treated
  • Controls

Reproducible simulation: X is uniform from -2 to 2; T is Bernoulli with logistic probability based on strength × X; Y = 1 + 1.2X + T(1 + 0.35X) + standard normal noise. A logistic model of T on X is fitted. The interval uses 1.96 standard errors from a robust variance for weighted means, treating fitted propensity and trimming as fixed; it omits their estimation and does not guarantee coverage. Trimming changes the target population.

1.2
0.00
Units retained500 / 500
Treated / controls266 / 234
Maximum IPW weight9.39
Hájek effect1.20
Approximate interval[0.76, 1.64]
Trimming changes the retained population; the illustrative interval treats estimated scores and trimming as fixed.

Balance: examine covariates, not p-values

Balance diagnostics compare observed covariates between arms. A love plot summarizes standardized mean differences, for example SMDk=(Xˉ1k,w−Xˉ0k,w)/sk,ref\mathrm{SMD}_k=(\bar X_{1k,w}-\bar X_{0k,w})/s_{k,\rm ref}, where sk,refs_{k,\rm ref} is fixed before adjustment for a common scale. A rule of thumb such as ∣SMD∣<0,1|SMD|<0{,}1 is not a theorem of no bias; also inspect distributions, interactions, and tails. A large p-value may reflect a small sample, and a small one can detect an irrelevant difference in a large sample. AUC measures treatment discrimination, not causal quality: near-perfect separation warns of poor common support.

King and Nielsen show successive pruning by score matching can worsen balance and efficiency, especially when approaching a completely randomized design and losing blocking advantages. It does not follow that every use of propensity or every matching method always worsens. Check the balance of the actual procedure applied.

InteractiveDiagnose balance

Each point is the absolute mean difference between treated and controls divided by the same pooled standard deviation before adjustment. The dashed line marks 0.1 as a descriptive reference, not proof of validity.

0.1X₁X₂X₁ × X₂0.001.40|Standardized difference|
  • Unadjusted
  • Matching
  • IPW
  • Trimmed IPW

Simulated sample: 800 units, with 200 in each binary combination of X₁ and X₂; T is drawn independently with logit e=−0.6+1.5X₁−X₂+2.5X₁X₂. Logistic regression estimates e with intercept and main effects, optionally including the interaction. The seed is fixed.

Matching uses the nearest-propensity control for each treated unit, with replacement and no caliper: it describes the treated. IPW uses 1/e for treated and 1/(1−e) for controls; trimming removes both arms outside [c,1−c] and weights within it. Its target population excludes regions and can change with the model. Means are normalized within each arm.

The fixed denominator is the square root of the average of X variances in the two unadjusted arms, using denominator n. The interaction is also a diagnostic covariate. Good balance on these variables does not rule out unmeasured confounding, lack of support or imbalance in other functions of X.

0.10
Units retained after trimming800
Maximum IPW SMD0.475
Maximum trimmed SMD0.475
Compare SMD before and after adjustment and see what happens when the interaction enters the propensity model.

Lab: four paths in a known world

Generate two observed confounders, logistic assignment, and a heterogeneous effect. Mean true effects printed by the cell are for this simulated sample; ATO uses the true score only to describe its target. Estimators use the fitted score and do not know that answer.

[ ]synthetic setupBrowser
import numpy as np

def expit_stable(v):
    # Esta restricción evita desbordamientos numéricos, no recorta los pesos.
    return 1 / (1 + np.exp(-np.clip(v, -35, 35)))

def simular(n, strength, seed):
    """SCM con confundidores observados, efecto heterogéneo y score verdadero."""
    rng = np.random.default_rng(seed)
    x = rng.normal(size=(n,2))
    e = expit_stable(-.2 + strength*x[:,0] - .65*x[:,1])
    t = (rng.random(n) < e).astype(int)
    tau = 1 + .3*x[:,0]
    y0 = 1 + x[:,0] + .5*x[:,1] + .3*x[:,0]*x[:,1] + rng.normal(size=n)
    y = y0 + t*tau
    return x,t,y,e,tau

def modelo_logit(x, t):
    """Newton para un logit con intercepto; falla explícitamente si no converge."""
    x,t = np.asarray(x,float),np.asarray(t,int)
    D = np.column_stack((np.ones(len(t)),x))
    if set(np.unique(t)) != {0,1} or np.linalg.matrix_rank(D) < D.shape[1]:
        raise ValueError('Tratamiento o diseño inválido')
    beta = np.zeros(D.shape[1])
    for _ in range(60):
        prop = expit_stable(D@beta)
        gradient = D.T@(t-prop)
        information = D.T@((prop*(1-prop))[:,None]*D)
        if np.linalg.cond(information)>1e12:
            raise ValueError('Información singular o separación')
        step = np.linalg.solve(information, gradient)
        beta += step
        if np.max(np.abs(step)) < 1e-9:
            e = expit_stable(D@beta)
            if np.any((e<=0)|(e>=1)):
                raise ValueError('Propensión sin soporte numérico')
            return e,beta
    raise ValueError('El logit no convergió')

def basis(x):
    return np.column_stack((np.ones(len(x)),x,x[:,0]*x[:,1]))

def outcomes(x,t,y):
    D=basis(x)
    out=[]
    for arm in (0,1):
        if np.sum(t==arm)<D.shape[1] or np.linalg.matrix_rank(D[t==arm])<D.shape[1]:
            raise ValueError('El modelo de resultado no tiene rango completo')
        out.append(np.linalg.lstsq(D[t==arm],y[t==arm],rcond=None)[0])
    return out

def estimates(x,t,y,e):
    if np.any((e<=0)|(e>=1)):
        raise ValueError('Positividad requerida')
    beta0,beta1=outcomes(x,t,y)
    D=basis(x)
    gcomp = np.mean(D@(beta1-beta0))
    w1=t/e
    w0=(1-t)/(1-e)
    if w1.sum()==0 or w0.sum()==0:
        raise ValueError('Falta un brazo')
    ht=np.mean(w1*y-w0*y)
    hajek=np.sum(w1*y)/w1.sum()-np.sum(w0*y)/w0.sum()
    # ATO corresponde a la población con densidad proporcional a e(1-e)f(x).
    ow1=t*(1-e); ow0=(1-t)*e
    ato=np.sum(ow1*y)/ow1.sum()-np.sum(ow0*y)/ow0.sum()
    return np.array([gcomp,ht,hajek,ato])

def matching_ate(x,t,y):
    """1 vecino con reemplazo para cada unidad y corrección de sesgo por brazo.

    Las distancias se calculan tras escalar cada covariable por su desviación.
    El promedio se toma sobre todas las unidades, de manera que apunta al ATE.
    """
    beta0,beta1=outcomes(x,t,y)
    D=basis(x)
    scale=x.std(axis=0,ddof=1)
    if np.any(scale<=0):
        raise ValueError('Covariable de distancia constante')
    tr,co=np.flatnonzero(t==1),np.flatnonzero(t==0)
    distances=((x[tr,None,:]-x[co][None,:,:])/scale)**2
    distances=distances.sum(axis=2)
    control_for_t=co[distances.argmin(axis=1)]
    treatment_for_c=tr[distances.argmin(axis=0)]
    m0_match=y[control_for_t]+(D[tr]-D[control_for_t])@beta0
    m1_match=y[treatment_for_c]+(D[co]-D[treatment_for_c])@beta1
    return np.r_[y[tr]-m0_match,m1_match-y[co]].mean()

def kish(w):
    w=np.asarray(w,float)
    if np.any(w<0) or not np.isfinite(w).all() or w.sum()<=0:
        raise ValueError('Pesos inválidos')
    return w.sum()**2/(w@w)

x_s,t_s,y_s,e_true_s,tau_s=simular(800,1.1,14140)
e_hat_s,beta_s=modelo_logit(x_s,t_s)
est_s=estimates(x_s,t_s,y_s,e_hat_s)
match_s=matching_ate(x_s,t_s,y_s)
print('n, tratados, controles:',len(t_s),int(t_s.sum()),int((1-t_s).sum()))
print('ATE medio de la muestra:',round(tau_s.mean(),4))
print('ATO medio de la muestra con e verdadero:',round(np.average(tau_s,weights=e_true_s*(1-e_true_s)),4))
print('G-computación, HT, Hájek, overlap:',np.round(est_s,4))
print('Matching 1-NN con corrección, ATE:',round(match_s,4))
print('Peso IPW máximo y ESS por brazo:',round(max((t_s/e_hat_s+(1-t_s)/(1-e_hat_s))),2),round(kish(t_s/e_hat_s),1),round(kish((1-t_s)/(1-e_hat_s)),1))

The following bootstrap refits models in every replicate. Percentile intervals are approximations under independent sampling and regularity, not coverage guarantees. Any failed replicate is reported: discarding failures can bias the distribution. The ordinary bootstrap is not generally valid for fixed-neighbor matching with replacement, although it may be for other regular estimators. For that estimator retain the point estimate and use an appropriate analytic variance or subsampling under their assumptions; see Abadie and Imbens (2008).

[ ]synthetic bootstrapBrowser
# Bootstrap de estimadores suaves: se reestiman propensión y modelos de resultado
# en cada réplica. NO aplicarlo al matching de 1 vecino con reemplazo: el
# bootstrap ordinario no es válido en general para ese estimador.
bootstrap_rng=np.random.default_rng(14141)
draws=[]
failures=0
for _ in range(120):
    indices=bootstrap_rng.integers(0,len(y_s),len(y_s))
    try:
        e_boot,_=modelo_logit(x_s[indices],t_s[indices])
        draws.append(estimates(x_s[indices],t_s[indices],y_s[indices],e_boot))
    except (ValueError,np.linalg.LinAlgError):
        failures+=1
if len(draws)<80:
    raise ValueError('Demasiadas réplicas sin estimación')
draws=np.asarray(draws)
intervals=np.quantile(draws,[.025,.975],axis=0)
for i,name in enumerate(('G-computación ATE','HT ATE','Hájek ATE','Solapamiento ATO')):
    print(name,'estimación',round(est_s[i],4),'IC percentil aproximado',np.round(intervals[:,i],4))
print('Réplicas bootstrap válidas:',len(draws),'| fallidas:',failures)
print('Son intervalos Monte Carlo aproximados, sujetos a supuestos y con 120 réplicas.')
print('Matching: solo estimación puntual; usa inferencia apropiada para vecinos fijos.')

Now increase assignment strength: the model remains known in the simulation, but some weights concentrate and intervals may worsen. A score near zero is not a license to divide without examining the consequence.

[ ]synthetic overlapBrowser
# Compara fuerza de asignación, colas de pesos y ESS sin seleccionar muestras.
for strength in (.4,1.1,2.):
    x,t,y,e,tau=simular(1200,strength,14142)
    fit,_=modelo_logit(x,t)
    values=estimates(x,t,y,fit)
    print('fuerza',strength,'min e/max e:',round(fit.min(),4),round(fit.max(),4),
          '| ESS tratados/controles:',round(kish(t/fit),1),round(kish((1-t)/(1-fit)),1),
          '| HT/Hájek/ATO:',np.round(values[1:],3))
print('ESS es un diagnóstico de concentración de pesos, no una varianza exacta.')

Lab: NSW versus PSID controls

LaLonde compared observational methods with a training experiment. Here we use the Dehejia and Wahba NSW variant, with 1974 pre-treatment earnings, and their PSID-1 controls; this is not LaLonde’s complete original cohort. Data come from the original files, available in the browser through the DAAG CSV mirror. A connection is required. Cells download real data: if networking fails they do not invent a substitute.

[ ]nsw 01 downloadBrowser
import asyncio
import io
import numpy as np
import pandas as pd
from pyodide.http import pyfetch

BASE_NSW = "https://vincentarelbundock.github.io/Rdatasets/csv/DAAG/"

async def leer_nsw(nombre):
    url = BASE_NSW + nombre
    try:
        respuesta = await pyfetch(url)
        if not respuesta.ok:
            raise RuntimeError(f"HTTP {respuesta.status}")
        return pd.read_csv(io.StringIO(await respuesta.string()))
    except Exception as error:
        raise RuntimeError(
            f"No se pudo descargar {nombre}. Comprueba la conexión y vuelve a ejecutar la celda."
        ) from error

ensayo, comparacion = await asyncio.gather(
    leer_nsw("nsw74demo.csv"), leer_nsw("nsw74psid1.csv")
)
columnas = ["trt", "age", "educ", "black", "hisp", "marr", "nodeg", "re74", "re75", "re78"]
ensayo, comparacion = ensayo[columnas], comparacion[columnas]
assert ensayo.shape == (445, 10) and comparacion.shape == (2675, 10)
assert ensayo.trt.sum() == 185 and comparacion.trt.sum() == 185
tratados = ensayo.loc[ensayo.trt == 1].sort_values(columnas).reset_index(drop=True)
tratados_psid = comparacion.loc[comparacion.trt == 1].sort_values(columnas).reset_index(drop=True)
assert np.allclose(tratados, tratados_psid)
assert not ensayo.isna().any().any() and not comparacion.isna().any().any()
print("Ensayo NSW: 185 tratados y 260 controles")
print("Comparación NSW-PSID: 185 tratados y 2490 controles")
print("Mismas personas tratadas en los dos archivos; ingresos reales en dólares de 1982.")

The trial compares treated and randomized NSW controls. Their difference is an experimental estimate with uncertainty, not a known true effect. The observational comparison contrasts those treated with PSID and needs ignorability, consistency, and support; neither PSID controls nor observed balance prove absence of omitted confounders.

[ ]nsw 02 benchmarkBrowser
# El ensayo y la comparación observacional comparten las 185 personas tratadas.
y_rct = ensayo.re78.to_numpy(dtype=float)
t_rct = ensayo.trt.to_numpy(dtype=int)
benchmark = y_rct[t_rct == 1].mean() - y_rct[t_rct == 0].mean()
se_rct = np.sqrt(y_rct[t_rct == 1].var(ddof=1) / (t_rct == 1).sum()
                 + y_rct[t_rct == 0].var(ddof=1) / (t_rct == 0).sum())
y = comparacion.re78.to_numpy(dtype=float)
t = comparacion.trt.to_numpy(dtype=int)
print(f"Ensayo: {benchmark:.2f} dólares; error estándar simple {se_rct:.2f}")
print(f"Sin ajustar con PSID: {y[t == 1].mean() - y[t == 0].mean():.2f} dólares")
print("La cifra experimental es una estimación incierta, no el ATT verdadero conocido.")

We fix covariates, logistic regression, and trimming in advance. OLS imposes its outcome model; matching and weights target the ATT of retained treated units. The score is fitted on the full sample before trimming. Untrimmed estimates share treated units with the trial and are not independent. After trimming, ATT concerns another population: its difference from the full benchmark is not an exact bias measure.

[ ]nsw 03 attBrowser
# Especificación fijada antes de mirar RE78. No se elige por cercanía al ensayo.
# Incluye únicamente covariables previas; el modelo logístico no usa RE78.
covariables = ["age", "educ", "black", "hisp", "marr", "nodeg", "re74", "re75"]
x = comparacion[covariables].to_numpy(dtype=float)
media, escala = x.mean(axis=0), x.std(axis=0)
z = (x - media) / escala
X = np.column_stack((np.ones(len(z)), z))

def sigmoid(v):
    return 1 / (1 + np.exp(-np.clip(v, -30, 30)))

def propensity(X, t):
    # Logística por Newton con penalización L2 pequeña, salvo el intercepto.
    penalizacion = np.diag([0.0] + [1e-6] * (X.shape[1] - 1))
    beta = np.zeros(X.shape[1])
    for _ in range(50):
        e = sigmoid(X @ beta)
        gradiente = X.T @ (t - e) - penalizacion @ beta
        hessiano = X.T @ ((e * (1 - e))[:, None] * X) + penalizacion
        paso = np.linalg.solve(hessiano, gradiente)
        beta += paso
        if np.max(np.abs(paso)) < 1e-8:
            break
    else:
        raise RuntimeError("La regresión logística no convergió")
    return sigmoid(X @ beta)

e = propensity(X, t)
assert np.all((e > 0) & (e < 1))

def resumen_att(mascara):
    ids = np.flatnonzero(mascara)
    tt, yy, xx, ee = t[ids], y[ids], X[ids], e[ids]
    it, ic = np.flatnonzero(tt == 1), np.flatnonzero(tt == 0)
    # Regresión con efecto común: bajo esa especificación, coeficiente de T.
    matriz = np.column_stack((xx, tt))
    ols = np.linalg.lstsq(matriz, yy, rcond=None)[0][-1]
    # Un vecino en propensity con reemplazo y desempate por índice.
    vecinos = np.argmin(np.abs(ee[it, None] - ee[None, ic]), axis=1)
    pareja = ic[vecinos]
    matching = np.mean(yy[it] - yy[pareja])
    # ATT de Hájek: tratados peso 1, controles odds del propensity.
    w0 = ee[ic] / (1 - ee[ic])
    ipw = yy[it].mean() - np.average(yy[ic], weights=w0)
    ess0 = w0.sum() ** 2 / np.square(w0).sum()
    # Misma desviación de referencia no ponderada en ambas comparaciones.
    diferencia = x[ids[it]].mean(axis=0) - x[ids[ic]].mean(axis=0)
    ponderada = x[ids[it]].mean(axis=0) - np.average(x[ids[ic]], axis=0, weights=w0)
    emparejada = x[ids[it]].mean(axis=0) - x[ids[pareja]].mean(axis=0)
    return it, ic, ols, matching, ipw, ess0, w0.max(), len(np.unique(pareja)), diferencia, emparejada, ponderada

# Desviación de referencia común a todos los gráficos, antes de recortar.
den = np.sqrt((x[t == 1].var(axis=0, ddof=1) + x[t == 0].var(axis=0, ddof=1)) / 2)
assert np.all(den > 0)
for nombre, mascara in [("Sin recorte", np.ones(len(t), dtype=bool)),
                         ("Recorte predefinido 0,05 <= e <= 0,95", (e >= 0.05) & (e <= 0.95))]:
    it, ic, ols, matching, ipw, ess0, max_peso, controles_usados, antes, pareja, despues = resumen_att(mascara)
    print(f"\n{nombre}: {len(it)} tratados, {len(ic)} controles")
    print(f"OLS efecto común={ols:.2f}; vecino={matching:.2f}; IPW ATT={ipw:.2f}")
    print(f"Kish de controles IPW: {ess0:.1f}; peso máximo: {max_peso:.2f}; "
          f"controles distintos emparejados: {controles_usados}")
    print("Covariable: SMD sin ajustar / matching / IPW")
    for variable, a, m, b in zip(covariables, antes / den, pareja / den, despues / den):
        print(f"{variable:>6}: {a:+.3f} / {m:+.3f} / {b:+.3f}")
print(f"Rango de propensity: tratados {e[t == 1].min():.3g} a {e[t == 1].max():.3g}; "
      f"controles {e[t == 0].min():.3g} a {e[t == 0].max():.3g}")
print("El recorte cambia la población; la referencia experimental completa no cambia con él.")

Trimming need not move each method closer to the benchmark. In this run, matching moves away from the experimental reference after trimming, although other results move differently. Examine how many treated and control units remain and weight concentration before deciding which comparison is credible.

The cell gives the trial a difference of 1,794.34 dollars with simple standard error 671.00; it is not a known counterfactual without uncertainty. Without trimming, the raw NSW–PSID contrast is -15,204.78, while regression, matching, and IPW give 751.95, 2,125.71, and 1,758.85. Different specifications and support limitations can yield different results; proximity to the trial alone does not identify the cause of discrepancy. Matching reuses controls: only 69 distinct controls represent 185 treated units. Weighted-control ESS is 42.6, despite 2,490 controls before weighting.

After trimming, 177 treated units and 241 controls remain. Matching gives 2,384.38 and IPW control ESS falls to 38.6. The plot also shows that, before trimming, matching retains standardized differences for age and marital status above 0.1 in absolute value. It would be incorrect to declare adjustment achieved merely because one number is near the trial or some covariates improve. The full trial includes the eight treated units excluded by trimming, so it does not estimate exactly the same restricted target either.

[ ]nsw 04 graficosBrowser
import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 5), constrained_layout=True)
bins = np.linspace(0, 1, 21)
ax1.hist(e[t == 1], bins=bins, density=True, histtype="step", linewidth=2, label="Tratados NSW")
ax1.hist(e[t == 0], bins=bins, density=True, histtype="step", linewidth=2, label="Controles PSID")
ax1.axvline(0.05, color="black", linestyle=":", label="Recorte predefinido")
ax1.axvline(0.95, color="black", linestyle=":")
ax1.set(xlabel="Propensity estimado", ylabel="Densidad", title="Solapamiento")
ax1.legend(fontsize=8)

it, ic, ols, matching, ipw, ess, max_peso, usados, antes, emparejada, ponderada = resumen_att(
    np.ones(len(t), dtype=bool)
)
posicion = np.arange(len(covariables))
ax2.axvline(0, color="black", linewidth=0.7)
ax2.axvline(-0.1, color="black", linestyle=":", linewidth=0.7)
ax2.axvline(0.1, color="black", linestyle=":", linewidth=0.7)
ax2.scatter(antes / den, posicion - 0.15, label="Sin ajustar", marker="o")
ax2.scatter(emparejada / den, posicion, label="Matching", marker="s")
ax2.scatter(ponderada / den, posicion + 0.15, label="IPW ATT", marker="^")
ax2.set_yticks(posicion, covariables)
ax2.set(xlabel="Diferencia de medias estandarizada", title="Balance antes del recorte")
ax2.legend(fontsize=8)
plt.show()

Exercises

ProofWhy the score balances
Prove: Assume joint ignorability, positivity, and e(X)=P(T=1∣X)e(X)=P(T=1\mid X). Show that the score balances covariates and that Y(t)⊥T∣e(X)Y(t)\perp T\mid e(X).
The proof will appear here as you work.

Step 1 of 2. Why is T independent of X given e(X)?

ProofHorvitz–Thompson expectation
Prove: Assume i.i.d. sampling, consistency, ignorability, and 0<e(X)<10<e(X)<1, with finite expectations. The true score is known. Prove unbiasedness of the HT estimator of ATE.
The proof will appear here as you work.

Step 1 of 2. What is the expectation of T·Y/e(X) conditional on X?

NumericWeight concentration
The weights of ten observations are 1, 1, 1, 1, 1, 2, 2, 2, 2 and 6. Calculate Kish effective sample size to three decimal places.
CodeIPW and variance with known propensity
Implement ipw_ate(y, t, e, normalized=True). Return (estimate, variance) for ATE: with normalized=False use Horvitz–Thompson; with True normalize weights by arm, as in Hájek. Variance must be the empirical M-estimation sandwich divided by sample size: use n and no degrees-of-freedom correction. Assume independent observations and known fixed propensities with 0 < e < 1. This variance does not include uncertainty from fitting propensity to the same data. Raise ValueError for non-one-dimensional inputs, unequal lengths, non-finite values, nonbinary treatment, propensities outside the open interval, or absence of either arm. Do not trim weights. Tests include manual variances, extreme weights, and a coverage simulation. Individual intervals need not cover the true ATE: coverage is a property of independent repetitions under the stated assumptions. Hint 1: define q1 = ty/e, q0 = (1-t)y/(1-e), and weights w1, w0. HT is mean(q1-q0), with influences q1-q0-estimate. Hint 2: for Hájek compute weighted means mu1, mu0 separately and influences w1(y-mu1)/mean(w1) - w0(y-mu0)/mean(w0). Variance is sum(influence2)/n2.
import numpy as np

def ipw_ate(y, t, e, normalized=True):
  """Devuelve estimación del ATE y varianza sandwich para propensity conocido."""
  raise NotImplementedError('Implementa el estimador y su varianza')
Shift+Enter to run
QuizA decision for the whole population
A policy would apply to all workers in the original population and you want its average effect. Which target and weights apply under ignorability and support?
QuizThose already trained
You want the average effect among those who already received training. Which comparison answers the question?
QuizA decision with plausible options
The decision is restricted to a population where both treatments are plausible and a smoothly weighted target population is accepted. Which estimand and weights correspond?
QuizBalance diagnosis
After weighting, a test of equal means has p=0.4 for one covariate. What can you conclude?

Continue learning

Weighting changes distributions using a probability ratio, as in self-normalized importance sampling; policy evaluation applies a related idea to actions. Identifying an effect requires assumptions about what is unobserved, while estimation also requires support, models, and uncertainty suited to the procedure.