Module contents
Lesson 10 of 28Core 110 min

Potential outcomes and randomized controlled trials

The Neyman–Rubin model defines causal effects through potential outcomes. Derive estimands and selection bias, then study randomized assignment, Neyman inference, Lin adjustment, and stratified and cluster designs.

After this lesson you can

  • Define causal effects using potential outcomes and explain SUTVA with interference examples.
  • Derive the decomposition of the difference in means into ATT and selection bias.
  • Prove unbiasedness of Neyman’s estimator and conservativeness of its variance estimator.
  • Apply Lin adjustment and assess precision through simulation.
  • Analyze stratified and cluster trials using the correct unit of inference.

Before you start

Two stories for the same incident

A team wants to know whether automated triage reduces the time needed to fix a vulnerability. For each incident it would like to compare the time taken with and without the tool under the same conditions. It observes only one story: the recorded time alone does not reveal what would have happened under the other decision.

Designing an experiment turns that impossible comparison for one unit into an informative comparison between groups, specifying which units are assigned, which intervention they receive, and the population the question concerns.

Potential outcomes and SUTVA

For each unit ii, define the potential outcomes Yi(1)Y_i(1) and Yi(0)Y_i(0) under treatment and control. If Ti∈{0,1}T_i\in\{0,1\} is the treatment received, consistency lets us write

Yi=TiYi(1)+(1−Ti)Yi(0),τi=Yi(1)−Yi(0).Y_i=T_iY_i(1)+(1-T_i)Y_i(0),\qquad \tau_i=Y_i(1)-Y_i(0).

We observe only one of each unit’s two outcomes. The individual difference τi\tau_i is a defined causal quantity, not one that is generally observable. SUTVA requires that a unit’s outcome not depend on the assignment of others and that each treatment state represent a sufficiently well-defined intervention, without relevant hidden versions.

In security, a treated team may share a solution with a control team: the latter’s outcome then depends on both assignments. In a two-sided market, treating suppliers can change the outcome for untreated buyers. One option is to define treatments and outcomes that include neighbors’ exposure; another is to assign clusters and formulate the effect under that new design. Neither automatically eliminates all interference between clusters.

InteractiveThe science table

Change each unit’s assignment. Only Y(1) is observed for treated units and Y(0) for controls; enable the full view to edit counterfactual cells too. In this simulated population we know both outcomes and can calculate its ATE.

UnitTreatY(0)Y(1)
1hidden
2hidden
3hidden
4hidden
5hidden
6hidden
7hidden
8hidden
9hidden
10hidden
11hidden
12hidden

All assignments with 6 treated and 6 controls are enumerated: 924 equally likely possibilities. Each draw uses the same treatment count and a distinct reproducible seed. The mean of this distribution equals the table ATE.

  • Possible assignments
  • Table ATE
  • Current assignment
−1.383.38

Synthetic initial data: for i=0,…,11, zᵢ=(i−5.5)/3, Yᵢ(0)=5+0.9zᵢ and Yᵢ(1)=Yᵢ(0)+1+0.25zᵢ, rounded to four decimal places; you can replace them. The randomization distribution treats these 12 pairs as fixed and assumes each assignment of the same size is equally likely.

Treated6
ATE of these units1.000
Observed difference0.658
Randomization mean1.000
Edit potential outcomes and compare assignments with the true average effect.

Which effect do you want to estimate?

Causal estimands are precise questions about a population or sample. In a population, if expectations exist,

ATE=E[Y(1)−Y(0)],ATT=E[Y(1)−Y(0)∣T=1],ATC=E[Y(1)−Y(0)∣T=0],ATE=E[Y(1)-Y(0)],\quad ATT=E[Y(1)-Y(0)\mid T=1],\quad ATC=E[Y(1)-Y(0)\mid T=0], CATE(x)=E[Y(1)−Y(0)∣X=x].CATE(x)=E[Y(1)-Y(0)\mid X=x].

The finite-population ATE for NN units is τ=N−1∑iτi\tau=N^{-1}\sum_i\tau_i. Its treated and control versions average over members of those groups, which depend on assignment. Superpopulation versions describe a distribution; extrapolating from available units requires justifying selection and transport. If effects are heterogeneous, policies affecting those already treated and the whole population may have different estimands.

The observed difference in means between groups admits the decomposition

E[Y∣T=1]−E[Y∣T=0]=ATT+E[Y(0)∣T=1]−E[Y(0)∣T=0]⏟sesgo de seleccioˊn.E[Y\mid T=1]-E[Y\mid T=0] =ATT+\underbrace{E[Y(0)\mid T=1]-E[Y(0)\mid T=0]}_{\text{sesgo de selección}}.

It is obtained by adding and subtracting E[Y(0)∣T=1]E[Y(0)\mid T=1]. The second term compares control outcomes for two different groups; with nonrandom assignment it can be positive, negative, or cancel the effect. It is not generally identified from observed outcomes without additional assumptions.

InteractiveEffect plus bias

The difference between treated and controls combines the average effect on those treated with a difference in potential outcomes under control. The first bar starts at zero; the second starts where the first ends and may move forwards or backwards.

  • ATT
  • Selection bias
  • Total difference
−0.3202.47Outcome difference

E[Y|T=1] − E[Y|T=0] = ATT + E[Y(0)|T=1] − E[Y(0)|T=0] = 1.140 + 1.007 = 2.147.

Model: twelve equally likely types, zᵢ=(i−5.5)/3, Yᵢ(0)=5+0.9zᵢ and Yᵢ(1)=Yᵢ(0)+1+0.25zᵢ, rounded to four decimal places. Assignment is Bernoulli with P(T=1|i)=1/[1+exp(−κzᵢ)]. Conditional means are calculated exactly by weighting each type by that probability; they are not a simulated sample.

If κ=0, treatment is independent of type and selection bias is zero. With negative κ, people with larger Y(0) are less likely to be treated: bias can hide or reverse a positive difference. ATT can change with κ as treated types change; it cannot simply be replaced by ATE.

1.0
ATT1.140
Selection bias1.007
Observational difference2.147
ATE1.000
Change selection and decompose the difference between groups.

Randomization specifies a mechanism

In a randomized controlled trial, the assignment mechanism is fixed before potential outcomes are seen. In Bernoulli assignment with known common probability p∈(0,1)p\in(0,1), each unit independently receives treatment. Arm sizes are random and the usual difference in means is undefined if either arm is empty; conditional on both being present, it is unbiased for the finite ATE. Alternatively, the Horvitz–Thompson estimator weights by known probabilities and permits individual probabilities strictly between zero and one.

In complete randomization exactly n1n_1 treated units are selected from NN units, with every assignment of that size equally likely; n0=N−n1n_0=N-n_1. In a stratified design assignment is repeated within groups defined before treatment. In a cluster design entire sets, such as teams or families, are assigned. The assignment unit determines the mechanism inference must reproduce.

Random assignment balances potential outcomes in expectation over assignments, not exactly in every draw. Nor does it guarantee absence of later losses, noncompliance, interference, or representativeness of the target population. The assignment estimand and the effect of actually receiving treatment are different questions when noncompliance occurs.

Neyman: unbiasedness and variance

Fix the potential outcomes of the NN units and treat only complete assignment as random. With n1,n0>0n_1,n_0>0,

τ^=Yˉ1obs−Yˉ0obs,ET[τ^]=Yˉ(1)−Yˉ(0)=τ.\hat\tau=\bar Y_1^{\mathrm{obs}}-\bar Y_0^{\mathrm{obs}}, \qquad E_T[\hat\tau]=\bar Y(1)-\bar Y(0)=\tau.

Each unit has probability nt/Nn_t/N of appearing in arm tt, so each observed mean is unbiased for its finite potential-outcome mean. For t=0,1t=0,1, define St2=(N−1)−1∑i(Yi(t)−Yˉ(t))2S_t^2=(N-1)^{-1}\sum_i(Y_i(t)-\bar Y(t))^2 and define Sτ2S_\tau^2 analogously for individual effects. Then

Var⁡T(τ^)=S12n1+S02n0−Sτ2N.\operatorname{Var}_T(\hat\tau) =\frac{S_1^2}{n_1}+\frac{S_0^2}{n_0}-\frac{S_\tau^2}{N}.

To derive this, each mean from a sample without replacement has variance (1/nt−1/N)St2(1/n_t-1/N)S_t^2 and the covariance between means of opposite arms is −S10/N-S_{10}/N, where S10S_{10} is the finite covariance of the two potential outcomes. Substitute Sτ2=S12+S02−2S10S_\tau^2=S_1^2+S_0^2-2S_{10}.

The covariance also follows from the mechanism: for i≠ji\ne j, P(Ti=1,Tj=0)=n1n0/[N(N−1)]P(T_i=1,T_j=0)=n_1n_0/[N(N-1)]; for i=ji=j it is zero. Thus Cov⁡(Ti,1−Tj)=n1n0/[N2(N−1)]\operatorname{Cov}(T_i,1-T_j)=n_1n_0/[N^2(N-1)] if i≠ji\ne j and −n1n0/N2-n_1n_0/N^2 if i=ji=j. Expand the two means as sums of indicators and divide by n1n0n_1n_0; the cross terms reduce the expression to −S10/N-S_{10}/N.

We do not observe both outcomes for each unit and, without further assumptions, cannot identify Sτ2S_\tau^2 from one trial. If each arm has at least two observations, the Neyman estimator uses the observed sample variances:

V^N=s12n1+s02n0,ET[V^N]=Var⁡T(τ^)+Sτ2N.\widehat V_N=\frac{s_1^2}{n_1}+\frac{s_0^2}{n_0},\qquad E_T[\widehat V_N]=\operatorname{Var}_T(\hat\tau)+\frac{S_\tau^2}{N}.

It is therefore conservative in expectation, not necessarily in every draw. With a constant individual effect Sτ2=0S_\tau^2=0 and the estimate is unbiased, although it can differ from the true variance in a particular assignment. In a regression of YY on an intercept and treatment, the squared HC2 standard error of the treatment coefficient equals V^N\widehat V_N. This equality assumes this design and a fit containing only intercept and treatment.

InteractiveThe variance we cannot estimate

Each point is one of the 924 equally likely assignments: the horizontal axis shows the difference in means and the vertical axis its Neyman variance estimator. The highlighted mark is the selected assignment. The population ATE is 1.

  • Assignments
  • Selected assignment
  • True variance
  • Neyman mean

Explicit population: for i=0,…,11 take aᵢ=i−5.5, centered and normalized to sample variance one. Take bᵢ=(i−5.5)² and center and normalize it likewise. They are orthogonal. Define Yᵢ(0)=aᵢ and Yᵢ(1)=1+ρaᵢ+√(1−ρ²)bᵢ: both variances are one and their finite-population correlation is exactly ρ.

With 6 treated and 6 controls, Var(Δ̂)=S₁²/6+S₀²/6−Sτ²/12. The observable estimator uses s₁²/6+s₀²/6. Its mean across assignments exceeds the true variance by Sτ²/12; they coincide if individual effects are constant, here with ρ=1. The inequality is in expectation: a particular assignment can underestimate variance, even with a constant effect. In a real application we cannot observe both potential outcomes and do not know the true line.

0.40
1
True variance0.233
Neyman mean0.333
Neyman for selected assignment0.141
Variance of effects1.200
Assignments that underestimate7.3 %
Compare true variance with the estimate in each assignment.

The figure’s model can be enumerated exactly. Also calculate how many particular assignments underestimate the variance, even when effects are constant:

[ ]Enumerate Neyman varianceBrowser
import numpy as np
from itertools import combinations

n, n1 = 12, 6
raw = np.arange(n, dtype=float) - (n-1)/2
a = raw / raw.std(ddof=1)
b = raw**2
b = (b-b.mean()) / b.std(ddof=1)
indices = list(combinations(range(n), n1))
t = np.zeros((len(indices), n), dtype=bool)
for i, selected in enumerate(indices):
    t[i, list(selected)] = True

for rho in (0.4, 1.0):
    y0 = a
    y1 = 1 + rho*a + np.sqrt(1-rho**2)*b
    ys1 = np.broadcast_to(y1, t.shape)[t].reshape(-1,n1)
    ys0 = np.broadcast_to(y0, t.shape)[~t].reshape(-1,n-n1)
    delta = ys1.mean(axis=1)-ys0.mean(axis=1)
    vhat = ys1.var(axis=1,ddof=1)/n1 + ys0.var(axis=1,ddof=1)/(n-n1)
    s_tau2 = (y1-y0).var(ddof=1)
    true_var = y1.var(ddof=1)/n1 + y0.var(ddof=1)/(n-n1) - s_tau2/n
    assert np.isclose(delta.var(),true_var)
    assert np.isclose(vhat.mean()-true_var,s_tau2/n)
    print('rho:',rho,'asignaciones:',len(delta),'ATE:',np.mean(y1-y0))
    print('Var verdadera:',true_var,'media Neyman:',vhat.mean(),
          'varianza efectos:',s_tau2,'Neyman en primera asignación:',vhat[0])
    print('Subestiman la varianza verdadera:',np.count_nonzero(vhat < true_var-1e-10))
print('Neyman es conservador en esperanza, no necesariamente en cada asignación.')

Fisher and Neyman answer different questions

Fisher’s randomization inference starts from a sharp null such as Yi(1)=Yi(0)Y_i(1)=Y_i(0) for every unit. Under it, all potential outcomes are known from those observed, assignments allowed by the design are enumerated or sampled, and the observed statistic is compared with that distribution. The weak null of zero average effect allows positive and negative individual effects and is not itself a sharp null that imputes all outcomes.

Neyman estimates an average effect and its uncertainty under repeated assignment; Fisher tests a null that specifies the missing potential outcomes. Both approaches use the actual mechanism but answer different questions. In strata or clusters, individuals must not be freely permuted if they were not assigned that way.

Adjusting for pretreatment covariates

Predictive covariates measured before assignment can improve precision. Adjusting for a post-treatment variable can block part of the effect or introduce bias. A regression without interactions imposes a common slope and, with unbalanced assignment and heterogeneous effects, can lose precision.

Lin’s adjustment centers covariates at the mean of all units and fits

Yi=α+τLTi+(Xi−Xˉ)⊤b+Ti(Xi−Xˉ)⊤c+ei.Y_i=\alpha+\tau_L T_i+(X_i-\bar X)^\top b +T_i(X_i-\bar X)^\top c+e_i.

The coefficient τ^L\hat\tau_L is equivalent to comparing predictions from both arm regressions at the same mean covariate vector. Under complete assignment and the asymptotic conditions of Lin, the fully interacted adjustment does not worsen asymptotic precision relative to the difference in means; it does not promise lower error in every finite sample. Use an appropriate robust covariance and examine ranks, leverage, and each arm’s size. The paper responds to Freedman’s concerns about adjustments not justified by the design.

InteractiveAdjust without fear

The figure covers the 220 possible assignments with that fixed number treated. Each curve shows the fraction per bin; the vertical line indicates the known ATE of the simulated population.

0.580−3.11.76.6ATE estimate
  • Difference in means
  • ANCOVA without interaction
  • Lin with interaction
MethodBiasVarianceMean squared error
Difference0.0000.3120.312
ANCOVA0.0252.4012.402
Lin−0.0730.0370.042

The population is explicit: X takes 12 equally spaced values from −1.5 to 1.5; q=X²−mean(X²). Define Y(0)=2X+0.4q and Y(1)=1+(2−4h)X+0.2q+0.15X³. Both potential outcomes are known here only because they are simulated. 3 treatments are assigned randomly without replacement and the remaining units are controls.

ANCOVA estimates a common slope for X. Lin centers X at the mean of the whole experimental population and includes a treatment-by-X interaction, equivalent to fitting a line in each group and comparing predictions at that mean. Both adjustments can have finite-sample bias. Equal or improved precision for Lin is an asymptotic result under suitable conditions, not a guarantee for every finite sample or assignment. The table shows both bias and variance; mean squared error is variance plus squared bias.

Number treated out of 12
1.00
Finite-population ATE1.000
Difference variance0.312
ANCOVA variance2.401
Lin variance0.037
Compare bias and precision of three estimators on the same assignments.

This cell reproduces the figure’s models and separates variance, bias, and mean squared error for two treatment sizes:

[ ]Enumerate Lin and ANCOVA adjustmentsBrowser
import numpy as np
from itertools import combinations

n, h = 12, 1.0
x = np.linspace(-1.5,1.5,n)
q = x*x-np.mean(x*x)
y0 = 2*x+0.4*q
y1 = 1+(2-4*h)*x+0.2*q+0.15*x**3
ate = np.mean(y1-y0)

for n1 in (3,6):
    rows = []
    for chosen in combinations(range(n),n1):
        t = np.zeros(n,dtype=bool)
        t[list(chosen)] = True
        y = np.where(t,y1,y0)
        diff = y[t].mean()-y[~t].mean()
        ancova = np.linalg.lstsq(np.column_stack((np.ones(n),t,x)),y,rcond=None)[0][1]
        lin = np.linalg.lstsq(np.column_stack((np.ones(n),t,x,t*x)),y,rcond=None)[0][1]
        rows.append((diff,ancova,lin))
    estimates = np.asarray(rows)
    bias = estimates.mean(axis=0)-ate
    variance = estimates.var(axis=0)
    mse = ((estimates-ate)**2).mean(axis=0)
    assert np.allclose(mse,variance+bias**2)
    print('Tratados:',n1,'asignaciones:',len(estimates),'ATE:',ate)
    for label, bias_j, var_j, mse_j in zip(('Diferencia','ANCOVA','Lin'),bias,variance,mse):
        print(label,'sesgo:',round(bias_j,6),'varianza:',round(var_j,6),'ECM:',round(mse_j,6))
print('Lin no garantiza mejora en cada muestra finita; los ajustes pueden tener sesgo finito.')

Strata, clusters, and sample size

If stratum hh contains NhN_h units and has both arms, the weighted difference τ^est=∑h(Nh/N)(Yˉ1h−Yˉ0h)\hat\tau_{\mathrm{est}}=\sum_h(N_h/N)(\bar Y_{1h}-\bar Y_{0h}) estimates the finite ATE. With independent assignment across strata, its variance adds the stratum variances multiplied by (Nh/N)2(N_h/N)^2; the conservative estimator substitutes each variance with its Neyman version. At least two units per arm within each stratum are needed for this direct variance estimate.

If clusters are assigned, their members are not independent treatment draws. With unequal sizes, the mean that weights each cluster equally and the mean over people are different estimands. For the person-level ATE in a finite population of clusters with known assignment probabilities, weight cluster totals by their probability and divide by the total number of people. Variance and randomization must reflect the cluster draw; a small number of clusters also makes asymptotic approximations difficult.

For sizing, what matters is how much independent information each assignment unit contributes. As a planning approximation with equal cluster size mm and intraclass correlation ρ\rho, the design effect for a mean is 1+(m−1)ρ1+(m-1)\rho; this does not replace a calculation that considers unequal sizes, strata, losses, and the specific test. Experimental design principles and randomized blocks connect assignment with that uncertainty.

Contextual bandits adapt assignment probabilities to available information and require that mechanism to be accounted for when evaluating policies. Ablations in machine learning also compare interventions: specifying what changes, how seeds or datasets are assigned, and the population of interest helps interpret their differences.

Lab: design-based inference

Implement the difference in means, Neyman variance, Lin adjustment with HC2, a stratified estimator, cluster Horvitz–Thompson, and a Fisher test. The population is simulated and held fixed; randomness comes from assignment. In Fisher’s test the sharp null and fixed number treated determine the possible assignments.

[ ]Estimators and exact test from scratchBrowser
import itertools
import numpy as np

# El vector t debe contener exactamente ceros y unos; ambas ramas necesitan
# dos observaciones para estimar varianzas muestrales.
def neyman(y, t):
    y = np.asarray(y, dtype=float)
    t = np.asarray(t)
    if y.ndim != 1 or t.shape != y.shape or not np.isfinite(y).all() or not np.isin(t, [0, 1]).all():
        raise ValueError('Datos o asignación inválidos')
    y1, y0 = y[t == 1], y[t == 0]
    if min(len(y1), len(y0)) < 2:
        raise ValueError('Se necesitan al menos dos unidades por brazo')
    return y1.mean() - y0.mean(), y1.var(ddof=1)/len(y1) + y0.var(ddof=1)/len(y0)

def lin(y, t, x):
    y, t, x = np.asarray(y, float), np.asarray(t), np.asarray(x, float)
    if x.ndim == 1:
        x = x[:, None]
    if y.ndim != 1 or t.shape != y.shape or x.ndim != 2 or x.shape[0] != len(y) or not np.isin(t, [0, 1]).all() or not np.isfinite(y).all() or not np.isfinite(x).all():
        raise ValueError('Datos o asignación inválidos')
    xc = x - x.mean(axis=0)
    z = np.column_stack((np.ones(len(y)), t, xc, t[:, None]*xc))
    if np.linalg.matrix_rank(z) != z.shape[1]:
        raise ValueError('Matriz sin rango completo')
    bread = np.linalg.inv(z.T @ z)
    beta = np.linalg.lstsq(z, y, rcond=None)[0]
    residual = y-z@beta
    h = np.einsum('ij,jk,ik->i', z, bread, z)
    if np.any(1-h <= 1e-10):
        raise ValueError('HC2 indefinido: apalancamiento igual a uno')
    covariance = bread @ (z.T @ ((residual**2/(1-h))[:, None]*z)) @ bread
    return beta[1], covariance[1, 1]

def stratified(y, t, strata):
    y, t, strata = np.asarray(y), np.asarray(t), np.asarray(strata)
    if strata.shape != y.shape:
        raise ValueError('Estratos incompatibles')
    estimate = variance = 0.0
    for s in np.unique(strata):
        mask = strata == s
        weight = mask.mean()
        diff, v = neyman(y[mask], t[mask])
        estimate += weight*diff
        variance += weight**2*v
    return estimate, variance

def cluster_ht(y, t, cluster):
    # Asignación completa de conglomerados; poblaciones y tamaños conocidos.
    # Totales/N dan el efecto medio por unidad, incluso con tamaños desiguales.
    y, t, cluster = np.asarray(y, float), np.asarray(t), np.asarray(cluster)
    ids, inverse = np.unique(cluster, return_inverse=True)
    group_t = np.array([t[inverse == j][0] for j in range(len(ids))])
    if not np.isin(t, [0, 1]).all() or not np.all(t == group_t[inverse]):
        raise ValueError('La asignación debe ser constante dentro de cada conglomerado')
    totals = np.bincount(inverse, weights=y)
    diff, var = neyman(totals, group_t)
    multiplier = len(ids)/len(y)
    return multiplier*diff, multiplier**2*var

def fisher_sharp(y, t):
    # Prueba bilateral exacta bajo H0: Y_i(1) = Y_i(0) para cada i.
    # La aleatorización completa fija el número de tratados.
    y, t = np.asarray(y, float), np.asarray(t)
    n, n1 = len(y), int(np.sum(t))
    if t.shape != y.shape or not np.isin(t, [0, 1]).all() or n1 == 0 or n1 == n:
        raise ValueError('Asignación inválida')
    def statistic(index):
        return y[index].mean() - (y.sum() - y[index].sum())/(n-n1)
    observed = statistic(np.flatnonzero(t))
    values = np.array([statistic(np.array(c)) for c in itertools.combinations(range(n), n1)])
    return observed, np.mean(np.abs(values) >= abs(observed)-1e-12), len(values)

rng = np.random.default_rng(1041)
n = 120
x = rng.normal(size=n)
y0 = 2 + 1.8*x + rng.normal(size=n)
y1 = y0 + 0.8 + 0.9*x
t = np.zeros(n, dtype=int)
t[rng.choice(n, 48, replace=False)] = 1
y = np.where(t == 1, y1, y0)
ate = (y1-y0).mean()
d, v = neyman(y, t)
l, lv = lin(y, t, x)
xc = x-x.mean()
z = np.column_stack((np.ones(n), t, xc, t*xc))
true_var = y1.var(ddof=1)/sum(t) + y0.var(ddof=1)/sum(1-t) - (y1-y0).var(ddof=1)/n
print('ATE finito:', round(ate, 4), '| Neyman:', round(d, 4), '| varianza estimada:', round(v, 5), '| varianza exacta:', round(true_var, 5))
print('Lin:', round(l, 4), '| EE HC2:', round(np.sqrt(lv), 4))
f_stat, f_p, f_m = fisher_sharp(np.array([0, 0, 1, 1, 1, 2, 2, 3]), np.array([0, 0, 0, 0, 1, 1, 1, 1]))
print('Fisher, estadístico, p bilateral, asignaciones:', round(f_stat, 4), round(f_p, 4), f_m)

Under the sharp null, enumerating all assignments also lets us directly check the test’s rejection rate in this discrete population:

[ ]Exact Fisher calibrationBrowser
# Calibración exacta de Fisher: todos los resultados son fijos bajo H0 aguda.
fixed_y = np.array([0, 0, 1, 1, 1, 2, 2, 3])
permutation_p = []
for chosen in itertools.combinations(range(8), 4):
    tt = np.zeros(8, dtype=int)
    tt[list(chosen)] = 1
    permutation_p.append(fisher_sharp(fixed_y, tt)[1])
rate = np.mean(np.array(permutation_p) <= 0.05)
assert rate <= 0.05 + 1e-12
print('Fisher: rechazo exacto bajo H0 aguda en 70 asignaciones =', round(rate, 4))
print('Con estadístico discreto la prueba exacta puede ser conservadora.')

To compare with a library, load its dependencies separately and check both coefficients and HC2 variances:

[ ]Set up pandasBrowser
import pandas as pd
print('Pandas disponible:', pd.__version__)
[ ]Set up SciPyBrowser
from scipy import stats, linalg, special
print('Funciones de SciPy disponibles.')
[ ]Check against statsmodelsBrowser
from statsmodels.regression.linear_model import OLS

ref = OLS(y, z).fit(cov_type='HC2')
np.testing.assert_allclose([l, lv], [ref.params[1], ref.cov_params()[1,1]], rtol=1e-10, atol=1e-10)
unadjusted = OLS(y, np.column_stack((np.ones(n), t))).fit(cov_type='HC2')
np.testing.assert_allclose([d, v], [unadjusted.params[1], unadjusted.cov_params()[1,1]], rtol=1e-10, atol=1e-10)
print('Lin y Neyman coinciden con OLS-HC2 de statsmodels: coeficientes y varianzas.')

Compare designs on the same known finite population. Normal intervals and coverage are summarized over simulated assignments: Monte Carlo error is reported and exact coverage is not guaranteed in this sample.

[ ]Coverage and precision by designBrowser
# Repetimos asignaciones sobre una sola población finita: el azar es el diseño.
# Los cinco conglomerados por estrato son equivalentes en tamaño aquí.
seed = np.random.default_rng(910)
n = 80
x = seed.normal(size=n)
y0 = 1.3*x + seed.normal(size=n)
y1 = y0 + 0.7 + 0.8*x
truth = (y1-y0).mean()
strata = np.repeat(np.arange(4), 20)
clusters = np.repeat(np.arange(20), 4)
truthvar = y1.var(ddof=1)/32 + y0.var(ddof=1)/48 - (y1-y0).var(ddof=1)/n
result = {name: [] for name in ('Neyman', 'Lin', 'Estratos', 'Conglomerados')}
for iteration in range(400):
    t = np.zeros(n, dtype=int)
    t[seed.choice(n, 32, replace=False)] = 1
    y = np.where(t, y1, y0)
    result['Neyman'].append(neyman(y, t))
    result['Lin'].append(lin(y, t, x))
    ts = np.zeros(n, dtype=int)
    for s in range(4):
        ts[seed.choice(np.flatnonzero(strata == s), 8, replace=False)] = 1
    ys = np.where(ts, y1, y0)
    result['Estratos'].append(stratified(ys, ts, strata))
    chosen = seed.choice(20, 8, replace=False)
    tc = np.isin(clusters, chosen).astype(int)
    yc = np.where(tc, y1, y0)
    result['Conglomerados'].append(cluster_ht(yc, tc, clusters))
print('ATE de la población fijada:', round(truth, 4), '| varianza Neyman exacta:', round(truthvar, 5))
for name, pairs in result.items():
    a = np.asarray(pairs)
    coverage = np.mean(np.abs(a[:,0]-truth) <= 1.95996398454*np.sqrt(a[:,1]))
    mcse = np.sqrt(coverage*(1-coverage)/len(a))
    print(f'{name:13} sesgo={np.mean(a[:,0]-truth):+.4f} var_empírica={np.var(a[:,0],ddof=1):.5f} media_var_est={np.mean(a[:,1]):.5f} cobertura={coverage:.3f} EE_MC={mcse:.3f}')
print('Con 400 asignaciones los resultados son aproximaciones Monte Carlo y los IC normales no tienen cobertura exacta garantizada.')

With unequal clusters, the difference between individual means has a random denominator. The following enumeration checks the person-level target of the weighted totals estimator:

[ ]Unequal cluster sizesBrowser
# Prueba independiente para tamaños de conglomerados desiguales.
# Se enumeran todas las asignaciones posibles y se valida la insesgadez HT.
sizes = np.array([2, 3, 4, 5, 6, 7])
groups = np.repeat(np.arange(len(sizes)), sizes)
xx = np.arange(len(groups), dtype=float)
yy0 = 0.1*xx + np.sin(xx)
yy1 = yy0 + np.repeat(np.array([0.1, 0.4, 0.6, 0.9, 1.2, 1.7]), sizes)
target = (yy1-yy0).mean()
hts, naive = [], []
for treated in itertools.combinations(range(6), 3):
    tt = np.isin(groups, treated).astype(int)
    observed = np.where(tt, yy1, yy0)
    hts.append(cluster_ht(observed, tt, groups)[0])
    naive.append(observed[tt == 1].mean()-observed[tt == 0].mean())
np.testing.assert_allclose(np.mean(hts), target, atol=1e-12)
print('Tamaños desiguales, ATE por unidad:', round(target, 5))
print('Media exacta sobre 20 asignaciones: HT =', round(np.mean(hts), 5), '| diferencia de medias individual =', round(np.mean(naive), 5))
print('La diferencia individual tiene denominadores aleatorios: no tiene insesgadez finita garantizada.')

Lab: the RAND experiment

The RAND health insurance experiment assigned insurance plans to families and compared, among other outcomes, use of medical services. The statsmodels randhie dataset is a useful extract for exploring visits and copayments, but does not include family identifiers needed to reconstruct the original design’s clustered inference. Therefore the following analysis is descriptive: a standard error treating all rows as independent is not the original trial’s uncertainty.

The extract defines mdvis as outpatient visits and lncoins as the logarithm of one plus coinsurance. The nominal zero-coinsurance category includes plans with an individual deductible, so it does not necessarily mean free care.

[ ]Set up NumPyBrowser
# Celda 1. Cargar NumPy.
import numpy as np
[ ]Set up pandasBrowser
# Celda 2. Cargar pandas antes del módulo de datos reparte la inicialización.
import pandas as pd
[ ]Load RAND dataBrowser
# Celda 3. Cargar el módulo de datos.
from statsmodels.datasets import randhie
[ ]Descriptive comparison of nominal coinsuranceBrowser
# Celda 4. Las filas no son necesariamente personas distintas.
rand = randhie.load_pandas().data
y = rand["mdvis"].to_numpy(dtype=float)
sin_coseguro_nominal = rand["lncoins"].to_numpy() == 0
print("Dimensiones:", rand.shape)
print("Columnas:", ", ".join(rand.columns))
print("Filas con coseguro nominal cero:", int(sin_coseguro_nominal.sum()))
print("Filas con coseguro nominal positivo:", int((~sin_coseguro_nominal).sum()))
print("Media de visitas con coseguro nominal cero:", round(y[sin_coseguro_nominal].mean(), 4))
print("Media de visitas con coseguro nominal positivo:", round(y[~sin_coseguro_nominal].mean(), 4))
print("Diferencia descriptiva:", round(y[sin_coseguro_nominal].mean() - y[~sin_coseguro_nominal].mean(), 4))
print("Planes con deducible individual por grupo:",
      int(rand.loc[sin_coseguro_nominal, "idp"].sum()), int(rand.loc[~sin_coseguro_nominal, "idp"].sum()))

The next fit reproduces the difference in means and the HC2 identity. Its standard error assumes independence between rows; it does not correct for family assignment or potential repeated observations and is not interpreted as trial uncertainty.

[ ]Set up regressionBrowser
# Celda 5. Importar la regresión por separado limita el coste de cada celda.
from statsmodels.regression.linear_model import OLS
[ ]Difference in means and hypothetical HC2Browser
# Celda 6. HC2 es una comparación de fórmulas, no una inferencia válida del ensayo.
x = np.column_stack((np.ones(len(y)), sin_coseguro_nominal.astype(float)))
reg = OLS(y, x).fit(cov_type="HC2")
naive_var = y[sin_coseguro_nominal].var(ddof=1) / sin_coseguro_nominal.sum() + y[~sin_coseguro_nominal].var(ddof=1) / (~sin_coseguro_nominal).sum()
print("Coeficiente OLS:", round(reg.params[1], 4))
print("Error estándar HC2 si las filas fueran independientes:", round(reg.bse[1], 4))
print("Error estándar con varianzas de grupo:", round(np.sqrt(naive_var), 4))
assert np.allclose(reg.params[1], y[sin_coseguro_nominal].mean() - y[~sin_coseguro_nominal].mean())
assert np.allclose(reg.bse[1] ** 2, naive_var)

On a reproducible subsample compare a regression with centered interactions and a Poisson count model. The extract’s documentation does not establish when physical limitations and chronic conditions were measured: the adjustment is descriptive, not a causal adjustment with pretreatment covariates. The Poisson coefficient describes a ratio of conditional means under the model, not the same additive contrast as the difference in means.

[ ]Descriptive interacted adjustmentBrowser
# Celda 7. Ajuste interactuado descriptivo sobre una submuestra reproducible.
# El extracto no documenta cuándo se midieron salud y limitación. No se afirma
# que sean basales, ni se interpreta el ajuste como un efecto causal de Lin.
rng_rand = np.random.default_rng(731)
indices_rand = rng_rand.choice(len(y), 4000, replace=False)
y_sub = y[indices_rand]
t_sub = sin_coseguro_nominal[indices_rand].astype(float)
cov_sub = rand[['physlm', 'disea']].to_numpy(dtype=float)[indices_rand]
cov_center = cov_sub - cov_sub.mean(axis=0)
mat_lin = np.column_stack((np.ones(len(y_sub)), t_sub, cov_center, t_sub[:, None]*cov_center))
ajuste_lin = OLS(y_sub, mat_lin).fit(cov_type='HC2')
print('Submuestra reproducible, n:', len(y_sub))
print('Diferencia descriptiva sin ajuste:', round(y_sub[t_sub == 1].mean()-y_sub[t_sub == 0].mean(), 4))
print('Coeficiente interactuado centrado, descriptivo:', round(ajuste_lin.params[1], 4))
print('HC2 bajo independencia hipotética de filas:', round(ajuste_lin.bse[1], 4))
[ ]Set up count modelBrowser
# Celda 8. Importar por separado el modelo de recuento.
from statsmodels.genmod.generalized_linear_model import GLM
from statsmodels.genmod.families import Poisson
[ ]Descriptive Poisson modelBrowser
# Celda 9. Poisson modela la media condicional mediante enlace logarítmico.
# Sus errores ordinarios exigen supuestos adicionales; no se interpretan como
# incertidumbre por familias. Mostramos únicamente asociaciones estimadas.
mat_pois = np.column_stack((np.ones(len(y_sub)), t_sub, cov_center))
ajuste_pois = GLM(y_sub, mat_pois, family=Poisson()).fit(maxiter=100)
print('Poisson convergió:', ajuste_pois.converged)
print('Razón de medias condicionales ajustada, descriptiva:', round(np.exp(ajuste_pois.params[1]), 4))
print('Media observada y ajustada en submuestra:', round(y_sub.mean(), 4), round(ajuste_pois.mu.mean(), 4))

Exercises

ProofWhat selection adds
Prove: Assume consistency and that both groups have positive probability. Show that E[Y∣T=1]−E[Y∣T=0]E[Y\mid T=1]-E[Y\mid T=0] is the sum of ATT and a difference in potential outcomes under control.
The proof will appear here as you work.

Step 1 of 3. Which potential outcomes replace the observed means?

ProofExpectation and variance under complete randomization
Prove: In a finite population of NN units with fixed potential outcomes, uniformly draw n1n_1 treated units and n0=N−n1n_0=N-n_1 controls. Let S12S_1^2, S02S_0^2 and S10S_{10} be their finite variances and covariance with denominator N−1N-1.
The proof will appear here as you work.

Step 1 of 3. Why is each observed mean unbiased for the corresponding potential-outcome mean?

In the simulated table below, Y(0)=(2,3,4,5,6,7,8,9)Y(0)=(2,3,4,5,6,7,8,9) and the individual effects are (1,2,0,2,1,−1,3,0)(1,2,0,2,1,-1,3,0). Units 2, 4, 7, and 8 are treated. Calculate the three estimands before running the checking cell.

NumericFinite-population ATE
For the eight units in the table, what is the average treatment effect ATE?
NumericATT of treated units
For the assignment in the table, what is the average effect ATT among the four treated units?
NumericSelection bias
For the indicated assignment, what is the mean of Y(0) among treated units minus its mean among controls?
[ ]Check the eight-unit tableBrowser
import numpy as np

y0 = np.array([2,3,4,5,6,7,8,9], dtype=float)
effect = np.array([1,2,0,2,1,-1,3,0], dtype=float)
y1 = y0 + effect
treated = np.array([False,True,False,True,False,False,True,True])
ate = effect.mean()
att = effect[treated].mean()
bias = y0[treated].mean()-y0[~treated].mean()
observed_difference = y1[treated].mean()-y0[~treated].mean()
assert np.isclose(observed_difference,att+bias)
print('ATE, ATT, sesgo, diferencia observada:',ate,att,bias,observed_difference)
QuizConnected users
A network assigns an alert to some users. Treated users forward it to control contacts, whose outcome changes with the number of treated neighbors. Which assumption fails for an individual binary treatment without network exposure?
QuizHidden versions
The label ‘treated’ combines two very different recommendations, whose mixture changes across teams and changes outcomes. Which part of SUTVA needs attention?
QuizTwo-sided market
A discount assigned to sellers changes the prices faced by buyers without a discount. If each buyer is considered untreated because they received no coupon, what is the concern?
QuizHeterogeneity or interference
An identical drug affects two patients differently because of a pre-existing characteristic. There is no contact or crossover effect and treatment is well defined. What follows?
QuizTeams assigned together
Whole teams are randomized, but members of different teams share information and exposure changes their outcomes. What can you conclude?
CodeImplement Lin adjustment with HC2
Implement lin_estimator(y, t, X). Outcome y and assignment t are length-n vectors; t is binary and both arms are present. X is a vector or matrix with one or more covariate columns. Reject non-finite values, incompatible shapes, and nonnumeric data. Center each column of X at the mean across all units and fit the matrix Z = [1, t, X_c, t*X_c] by least squares. Return (estimate, HC2 variance) of the coefficient of t, not its standard error. HC2 variance uses weights residual_i²/(1-h_ii), where h_ii is the diagonal of the projection onto Z. Raise ValueError for n <= number of columns of Z, incomplete rank, or any 1-h_ii <= 1e-10. Do not assume balanced treatment or equal slopes in both arms.
import numpy as np


def lin_estimator(y, t, X):
  pass
Shift+Enter to run