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
- 27Descriptive versus causal regressionHeteroskedasticity-consistent standard errors (HC0 to HC3)Cluster-robust inference
- 05Randomization inferenceFisher's principles: randomization, replication and blockingRandomized block designs and Latin squaresA/B testing and online controlled experimentsCovariate adjustment (ANCOVA and CUPED)Sample size calculation and minimum detectable effectPower and power function
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 , define the potential outcomes and under treatment and control. If is the treatment received, consistency lets us write
We observe only one of each unit’s two outcomes. The individual difference 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.
Which effect do you want to estimate?
Causal estimands are precise questions about a population or sample. In a population, if expectations exist,
The finite-population ATE for units is . 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
It is obtained by adding and subtracting . 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.
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 , 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 treated units are selected from units, with every assignment of that size equally likely; . 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 units and treat only complete assignment as random. With ,
Each unit has probability of appearing in arm , so each observed mean is unbiased for its finite potential-outcome mean. For , define and define analogously for individual effects. Then
To derive this, each mean from a sample without replacement has variance and the covariance between means of opposite arms is , where is the finite covariance of the two potential outcomes. Substitute .
The covariance also follows from the mechanism: for , ; for it is zero. Thus if and if . Expand the two means as sums of indicators and divide by ; the cross terms reduce the expression to .
We do not observe both outcomes for each unit and, without further assumptions, cannot identify from one trial. If each arm has at least two observations, the Neyman estimator uses the observed sample variances:
It is therefore conservative in expectation, not necessarily in every draw. With a constant individual effect and the estimate is unbiased, although it can differ from the true variance in a particular assignment. In a regression of on an intercept and treatment, the squared HC2 standard error of the treatment coefficient equals . This equality assumes this design and a fit containing only intercept and treatment.
The figure’s model can be enumerated exactly. Also calculate how many particular assignments underestimate the variance, even when effects are constant:
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 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
The coefficient 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.
This cell reproduces the figure’s models and separates variance, bias, and mean squared error for two treatment sizes:
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 contains units and has both arms, the weighted difference estimates the finite ATE. With independent assignment across strata, its variance adds the stratum variances multiplied by ; 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 and intraclass correlation , the design effect for a mean is ; 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.
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:
# 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:
import pandas as pd
print('Pandas disponible:', pd.__version__)from scipy import stats, linalg, special
print('Funciones de SciPy disponibles.')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.
# 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:
# 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.
# Celda 1. Cargar NumPy.
import numpy as np# Celda 2. Cargar pandas antes del módulo de datos reparte la inicialización.
import pandas as pd# Celda 3. Cargar el módulo de datos.
from statsmodels.datasets import randhie# 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.
# Celda 5. Importar la regresión por separado limita el coste de cada celda.
from statsmodels.regression.linear_model import OLS# 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.
# 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))# Celda 8. Importar por separado el modelo de recuento.
from statsmodels.genmod.generalized_linear_model import GLM
from statsmodels.genmod.families import Poisson# 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
Step 1 of 3. Which potential outcomes replace the observed means?
Step 1 of 3. Why is each observed mean unbiased for the corresponding potential-outcome mean?
In the simulated table below, and the individual effects are . Units 2, 4, 7, and 8 are treated. Calculate the three estimands before running the checking cell.
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)import numpy as np
def lin_estimator(y, t, X):
pass