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 , prior covariates , and potential outcomes . The average effect in the target population is . Assume consistency , no interference under the chosen treatment definition, integrability, conditional ignorability , and positivity almost surely in that population. Then, by iterated expectation,
Independence allows the second step and consistency the third. Thus, with ,
Positivity does not require equal probabilities: it requires both treatments to be possible at values of 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 and conditional on . 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 and averages predictions over the same covariate distribution:
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 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 with invertible covariance matrix : it corrects scales and correlations but can be unstable if 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 using neighbor , a regression correction is ; 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 is the closest available control, its mean outcome can differ from the treated unit’s counterfactual by . 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.
A score that balances distributions
The propensity score 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: .
The proof fits in a conditional expectation. Since is a function of ,
For binary , this establishes independence. If additionally , then
for integrable functions : first use ignorability, then balance of . Equality for both arms gives 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
Identity 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 , and . In the population, each weighted arm thus reproduces the original distribution of . 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 is never exactly zero or one.
For ATT, , treated units keep weight one and controls are weighted by ; their means are normalized separately. Controls then represent the distribution of among treated units, not the full population. Extreme weights amplify a few observations. Kish effective sample size,
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 as known omits estimation of the assignment model. A stacked equation or, for regular estimators, a bootstrap refitting that model can be used.
Overlap and a change of question
Examine score distributions by arm, maximum weights, and ESS. Overlap trimming with threshold set before examining outcomes retains and changes the target to the effect in the retained population. If 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 and . They target
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 , both and equal . 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.
Balance: examine covariates, not p-values
Balance diagnostics compare observed covariates between arms. A love plot summarizes standardized mean differences, for example , where is fixed before adjustment for a common scale. A rule of thumb such as 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.
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.
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).
# 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.
# 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.
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.
# 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.
# 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.
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
Step 1 of 2. Why is T independent of X given e(X)?
Step 1 of 2. What is the expectation of T·Y/e(X) conditional on X?
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')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.