Heterogeneous effects and policy learning: meta-learners and causal forests
Estimate treatment-effect heterogeneity using S, T, X, R, and DR learners and honest causal forests. Evaluate ranking, calibration, and policy value without observing individual treatment effects.
After this lesson you can
- Implement S, T, X, R, and DR meta-learners and discuss regularization and arm variance.
- Explain honest causal trees and construct a simplified forest with intervals.
- Evaluate CATE ranking with RATE, QINI, and group calibration.
- Learn a shallow treatment policy using AIPW scores.
- Compare implementations with EconML and assess sample size and overlap.
Before you start
- 27Causal estimands: ATE, ATT and CATEAugmented inverse probability weighting estimatorNeyman orthogonalityCross-fittingDouble/debiased machine learningPartially linear model
- 11Decision tree (CART)Random forestGradient boosting machineROC curve and AUCPrecision-recall curve
- 13Uniform convergenceVC generalization bound
Who benefits from an intervention?
A team can offer a tool to some services. Its average offer effect may be positive even if some services do not improve and others improve greatly. Predicting which service has more incidents does not answer which service will change most if given the tool.
Let be assignment and potential outcomes. The conditional average treatment effect is
This is an average for units with covariates , not an observed individual effect. With consistency, no interference, joint exchangeability , and overlap ,
These assumptions identify the estimand from observational data; the subsequent algorithm does not prove them. Examine overlap in decision regions, not just the overall treated proportion.
Five ways to learn heterogeneity
Meta-learners turn the causal problem into prediction fits. Let . Use separate samples or cross-fitting so an observation’s nuisance predictions are generated without training on its own outcome.
S-learner. Fit one function and calculate . It can share information across arms, but strong regularization or a model without interactions may ignore variation associated with . This is not inevitable for every learner and does not prove S is always worse.
T-learner. Fit among treated units and among controls, then subtract predictions. Each fit uses one arm: a sparse group or missing support for some can make predictions very uncertain. Accurate factual prediction does not guarantee accurate counterfactual differences.
X-learner. First estimate both means. For each treated unit form and for each control ; then fit functions of these two pseudo-effects within their arms. One possible combination is
Here was fitted among treated units and among controls. This convention gives more weight to the treated-trained function when is small; suitable weights depend on stage precision. Imbalance may favor X in some problems but does not guarantee it always wins. Künzel and colleagues study the proposal and conditions.
If nuisance means were learned in another sample, the expectation of among treated units given is ; that of among controls is . Both signal the effect but each inherits error from a different counterfactual mean. Second-stage regressions and final combination add uncertainty. A smooth curve does not imply good extrapolation where treated or control units are absent.
The R residual loss
The R-learner minimizes, with out-of-fold nuisance predictions,
With true functions, under the earlier causal assumptions and finite second moments, . The risk difference between and is
Under overlap, the unrestricted pointwise minimizer is . Restricting to a family yields a projection weighted by , which need not equal the best unweighted approximation. Do not naively divide by when small: the loss can be optimized in weighted form. Quasi-oracle properties require regularity and rates, as Nie and Wager explain.
The doubly robust pseudo-outcome
The DR-learner fits a second regression of
on . If estimated functions are treated as fixed because they were learned on independent data, with and finite expectations, conditional bias of relative to is
It vanishes if propensity is correct or both conditional means are correct. This pseudo-outcome property does not guarantee second-stage consistency or coverage of an arbitrary interval. Kennedy studies two-stage DR-learner error bounds: an additional term depends on nuisance-error products under second-stage regression and sample-splitting conditions. Propensities near zero or one amplify residuals; clipping them changes the estimator and may introduce bias.
Honest causal trees and forests
A causal tree partitions space to separate effects, not merely predicted levels. In an honest tree one part of a subsample chooses splits and a disjoint part estimates leaf effects. Separation avoids using the same outcome to select an extreme leaf and estimate it again. Even so, small leaves, poor overlap, and approximation bias can damage precision and coverage.
A causal forest aggregates many trees and uses their adaptive neighborhoods to estimate effects. Asymptotic normality and intervals for particular variants require assumptions on honesty, splits, subsampling, overlap, and regularity. Tree dispersion is not automatically a valid forest standard error. See Wager and Athey and generalized random forests.
A covariate’s importance may indicate it helps separate estimated heterogeneity; it does not identify the causal effect of intervening on that covariate. Testing many subgroups and highlighting only the most significant changes interval interpretation through selection.
Evaluate without knowing individual effects
Good factual outcome prediction is insufficient to evaluate . For priority fixed without evaluation outcomes, consider the top fraction and define
The RATE family integrates with a weight function. AUTOC uses weight one; QINI uses weight . If cumulative gain per population unit is , its difference from random treatment is : the area between them is QINI under this normalization, one RATE member, not the whole family. Declare tie-breaking and numerical integration. See Yadlowsky and colleagues.
In observational evaluation, unobserved effects are replaced with AIPW scores using nuisances fitted out of fold or in another sample under the same identification assumptions. A useful ranking can be miscalibrated: compare mean predictions and scores in predefined groups, with uncertainty and suitable correction when examining many groups. Few cases at the top yield large variability; nonsignificance does not prove homogeneity.
A rule can correctly rank two subgroups and exaggerate their effect difference: TOC evaluates prioritization while group calibration tests a different property. The converse also fails: a constant estimator can be well calibrated on average but not discriminate whom to treat. Fix cutoffs and model without evaluation outcomes; choosing them after trying many alternatives makes the contrast optimistic.
From estimation to decisions
A policy decides whom to treat. Its absolute value and gain versus no treatment are
A tree rule can be selected by maximizing the average of over a declared class. If each treatment costs , optimize net gain ; a budget further restricts admissible rules. Then fix the policy and evaluate on independent data: reusing the sample to search many rules and value the winner introduces optimism.
Regret depends on oracle : the best allowed tree and best unrestricted rule are different comparisons. In a known-mechanism simulation estimate regret with a separate Monte Carlo sample. In observational data such as 401(k), true oracle value is unobserved: report estimated values and differences from defined policies, with uncertainty and assumptions, not fabricated true regret. Policy-learning guarantees depend on class, overlap, and nuisance quality; see Athey and Wager.
Lab
Five learners in a simulation
The mechanism provides known conditional truth to calculate test error. Training data build models and evaluation remains separate. To compare five methods on a common basis we use Ridge regressions on polynomial features; results depend on that choice and seed.
import numpy as npfrom sklearn.linear_model import Ridge, LogisticRegressionfrom sklearn.model_selection import StratifiedKFolddef mundo(n, seed, escenario='lineal', propension=.35):
"""SCM con ignorabilidad por construcción; solo la simulación conoce tau."""
if escenario not in ('constante','lineal','escalon') or not 0 < propension < 1:
raise ValueError('Escenario o propensión inválidos')
rng = np.random.default_rng(seed)
x = rng.uniform(-1,1,n)
t = rng.binomial(1,propension,n)
tau = (np.full(n,.8) if escenario=='constante' else
.8 + .8*x if escenario=='lineal' else .4 + 1.2*(x>0))
mu0 = 1+.5*x+np.sin(2*x)
y = mu0 + t*tau + rng.normal(0,.8,n)
return x,t,y,tau
x_train,t_train,y_train,tau_train = mundo(2000,272701)
x_test,t_test,y_test,tau_test = mundo(4000,272702)
print('Entrenamiento y prueba independientes:',len(x_train),len(x_test))
print('Tratados en entrenamiento:',int(t_train.sum()))
def phi(x):
x=np.asarray(x,dtype=float)
return np.column_stack([np.ones(len(x)),x,x*x,x*x*x])
def ajustar(P,y,weights=None):
model=Ridge(alpha=1.,fit_intercept=False)
model.fit(P,y,sample_weight=weights)
return model# Nuisances fuera de pliegue: dos divisiones estratificadas.
P_train = phi(x_train)
P_test = phi(x_test)
mu0_cf=np.empty(len(x_train))
mu1_cf=np.empty(len(x_train))
m_cf=np.empty(len(x_train))
e_cf=np.empty(len(x_train))
folds=StratifiedKFold(n_splits=2,shuffle=True,random_state=272703)
for train_idx,held_idx in folds.split(P_train,t_train):
for arm, dest in [(0,mu0_cf),(1,mu1_cf)]:
mask=train_idx[t_train[train_idx]==arm]
if len(mask)<P_train.shape[1]:
raise ValueError('Brazo insuficiente en un pliegue')
dest[held_idx]=ajustar(P_train[mask],y_train[mask]).predict(P_train[held_idx])
m_cf[held_idx]=ajustar(P_train[train_idx],y_train[train_idx]).predict(P_train[held_idx])
prop=LogisticRegression(C=1.,max_iter=500)
prop.fit(P_train[train_idx,1:],t_train[train_idx])
e_cf[held_idx]=prop.predict_proba(P_train[held_idx,1:])[:,1]
if np.any((e_cf<=.01)|(e_cf>=.99)):
raise ValueError('Propensiones extremas: revisar solapamiento')
print('Rango de propensiones fuera de pliegue:',np.round([e_cf.min(),e_cf.max()],4))
prop_full=LogisticRegression(C=1.,max_iter=500).fit(P_train[:,1:],t_train)
e_test=prop_full.predict_proba(P_test[:,1:])[:,1]# S incluye interacciones del tratamiento con las mismas funciones base.
joint = np.column_stack([P_train,t_train[:,None]*P_train])
s_model=ajustar(joint,y_train)
zeros=np.zeros_like(P_test)
tau_s=s_model.predict(np.column_stack([P_test,P_test]))-s_model.predict(np.column_stack([P_test,zeros]))
# T estima una media por brazo.
t0=ajustar(P_train[t_train==0],y_train[t_train==0])
t1=ajustar(P_train[t_train==1],y_train[t_train==1])
tau_t=t1.predict(P_test)-t0.predict(P_test)
# X usa pseudoefectos construidos con medias fuera de pliegue.
treated=t_train==1
control=~treated
x1=ajustar(P_train[treated],y_train[treated]-mu0_cf[treated])
x0=ajustar(P_train[control],mu1_cf[control]-y_train[control])
tau_x=e_test*x0.predict(P_test)+(1-e_test)*x1.predict(P_test)
# R minimiza el cuadrado residual con pesos (T-e)^2.
res_t=t_train-e_cf
res_y=y_train-m_cf
r_model=ajustar(P_train,res_y/res_t,weights=res_t**2)
tau_r=r_model.predict(P_test)
# DR regresa la puntuación aumentada de cada observación sobre X.
gamma=mu1_cf-mu0_cf+t_train*(y_train-mu1_cf)/e_cf-(1-t_train)*(y_train-mu0_cf)/(1-e_cf)
dr_model=ajustar(P_train,gamma)
tau_dr=dr_model.predict(P_test)
estimaciones={'S':tau_s,'T':tau_t,'X':tau_x,'R':tau_r,'DR':tau_dr}
for name,pred in estimaciones.items():
print(name,'ECM en prueba sintética:',round(float(np.mean((pred-tau_test)**2)),5))
print('Los ECM requieren la verdad de la simulación; no están disponibles en un estudio real.')The following comparison reuses the same fitting rules across six worlds. Each MSE uses independent test data and truth available only in simulation; one realization does not establish general dominance.
# Celda complementaria: ejecutar después de meta_01_datos, meta_02_auxiliares
# y meta_03_modelos. Reutiliza mundo, phi y ajustar sin alterar sus variables.
def comparar_meta_mundos(escenario, propension, n_entrenamiento=600, n_prueba=1200):
"""Cinco ajustes con las mismas bases, Ridge y cross-fitting del laboratorio."""
# Dos generadores con semillas distintas: prueba independiente del ajuste.
x, t, y, _ = mundo(n_entrenamiento, 272711, escenario, propension)
xt, _, _, verdad = mundo(n_prueba, 272712, escenario, propension)
P, Pt = phi(x), phi(xt)
mu0, mu1 = np.empty(len(x)), np.empty(len(x))
marginal, e = np.empty(len(x)), np.empty(len(x))
folds = StratifiedKFold(n_splits=2, shuffle=True, random_state=272703)
for train, held in folds.split(P, t):
for arm, dest in [(0, mu0), (1, mu1)]:
sample = train[t[train] == arm]
if len(sample) < P.shape[1]:
raise ValueError('Brazo insuficiente en un pliegue')
dest[held] = ajustar(P[sample], y[sample]).predict(P[held])
marginal[held] = ajustar(P[train], y[train]).predict(P[held])
prop = LogisticRegression(C=1., max_iter=500)
prop.fit(P[train, 1:], t[train])
e[held] = prop.predict_proba(P[held, 1:])[:, 1]
if np.any((e <= .01) | (e >= .99)):
raise ValueError('Propensiones extremas: revisar solapamiento')
prop = LogisticRegression(C=1., max_iter=500).fit(P[:, 1:], t)
et = prop.predict_proba(Pt[:, 1:])[:, 1]
treated, control = t == 1, t == 0
# S conjunta, con exactamente las mismas interacciones de tratamiento.
s = ajustar(np.column_stack([P, t[:, None]*P]), y)
s_pred = s.predict(np.column_stack([Pt, Pt])) - s.predict(
np.column_stack([Pt, np.zeros_like(Pt)]))
# T por brazo; X usa pseudoefectos obtenidos fuera de pliegue.
t0, t1 = ajustar(P[control], y[control]), ajustar(P[treated], y[treated])
t_pred = t1.predict(Pt)-t0.predict(Pt)
x1 = ajustar(P[treated], y[treated]-mu0[treated])
x0 = ajustar(P[control], mu1[control]-y[control])
x_pred = et*x0.predict(Pt)+(1-et)*x1.predict(Pt)
# La pérdida de R y la pseudo-variable de DR coinciden con meta_03.
residual_t, residual_y = t-e, y-marginal
r = ajustar(P, residual_y/residual_t, weights=residual_t**2)
gamma = mu1-mu0+t*(y-mu1)/e-(1-t)*(y-mu0)/(1-e)
dr = ajustar(P, gamma)
preds = {'S': s_pred, 'T': t_pred, 'X': x_pred,
'R': r.predict(Pt), 'DR': dr.predict(Pt)}
errores = {name: float(np.mean((estimate-verdad)**2))
for name, estimate in preds.items()}
if not all(np.isfinite(value) for value in errores.values()):
raise ValueError('ECM no finito')
return errores, int(t.sum()), (float(e.min()), float(e.max()))
for escenario_comparacion in ('constante', 'lineal', 'escalon'):
for p_comparacion in (.2, .5):
errores_comparacion, tratados_comparacion, rango_comparacion = comparar_meta_mundos(
escenario_comparacion, p_comparacion)
print('Efecto:', escenario_comparacion, '| p:', p_comparacion,
'| tratados en entrenamiento:', tratados_comparacion,
'| rango e fuera de pliegue:', tuple(round(v, 3) for v in rango_comparacion))
print(' ECM en prueba independiente:',
{name: round(value, 5) for name, value in errores_comparacion.items()})
print('Cada ECM usa la verdad sintética; una muestra no demuestra un ganador universal.')Out-of-sample ranking, calibration, and value
Ranking is fixed using training. DR scores use nuisance means fitted on training, evaluation outcomes, and known treatment probability in this randomized simulation. Priority ties retain input order, including each bootstrap resample. Integration is a Riemann sum over group sizes, and bootstrap resamples evaluation with the learned model fixed: its standard error excludes retraining. In observational data an estimated propensity may add bias that this conditional bootstrap does not measure.
# La regla de prioridad X se aprendió solo en entrenamiento.
# Las nuisances de evaluación se ajustan con todo el entrenamiento.
mu0_eval=t0.predict(P_test)
mu1_eval=t1.predict(P_test)
e_eval=np.full(len(x_test),.35) # Propensión verdadera del ensayo simulado.
gamma_eval=(mu1_eval-mu0_eval
+t_test*(y_test-mu1_eval)/e_eval
-(1-t_test)*(y_test-mu0_eval)/(1-e_eval))
print('La evaluación usa la probabilidad conocida de aleatorización:',e_eval[0])
def metricas_prioridad(scores, gamma):
scores,gamma=np.asarray(scores),np.asarray(gamma)
if scores.shape!=gamma.shape or len(gamma)<2 or not np.isfinite(scores).all() or not np.isfinite(gamma).all():
raise ValueError('Puntuaciones inválidas')
order=np.argsort(-scores,kind='stable')
ordered=gamma[order]
q=np.arange(1,len(gamma)+1)/len(gamma)
toc=np.cumsum(ordered)/np.arange(1,len(gamma)+1)-gamma.mean()
return q,toc,float(toc.mean()),float(np.mean(q*toc))
q,toc,autoc,qini=metricas_prioridad(tau_x,gamma_eval)
print('AUTOC y QINI por suma de Riemann:',round(autoc,5),round(qini,5))
print('TOC en q=1:',round(toc[-1],12))
print('El ranking está fijado por entrenamiento; QINI integra q·TOC.')
# Bootstrap de la muestra de evaluación manteniendo fijo el modelo aprendido.
rng_boot=np.random.default_rng(272704)
B=250
rates=[]
for _ in range(B):
indices=rng_boot.integers(0,len(q),len(q))
rates.append(metricas_prioridad(tau_x[indices],gamma_eval[indices])[2:])
rates=np.asarray(rates)
print('EE bootstrap condicional al modelo: AUTOC y QINI',np.round(rates.std(axis=0,ddof=1),5))
print('Este bootstrap no incluye la variación de volver a entrenar los modelos.')from math import erfc, sqrt
# Cortes elegidos con entrenamiento y mantenidos fijos en evaluación.
prioridad_train=e_cf*x0.predict(P_train)+(1-e_cf)*x1.predict(P_train)
cortes=np.quantile(prioridad_train,[.25,.5,.75])
grupos=np.searchsorted(cortes,tau_x,side='right')
for grupo in range(4):
indices=np.flatnonzero(grupos==grupo)
if len(indices)<2:
raise ValueError('Grupo de evaluación demasiado pequeño')
pred=float(tau_x[indices].mean())
obs=float(gamma_eval[indices].mean())
diferencia=gamma_eval[indices]-tau_x[indices]
se=float(diferencia.std(ddof=1)/np.sqrt(len(indices)))
p=erfc(abs(float(diferencia.mean()))/(sqrt(2)*se)) if se>0 else float(diferencia.mean()==0)
print('Grupo',grupo+1,'n',len(indices),'predicción',round(pred,4),
'media DR',round(obs,4),'EE diferencia',round(se,4),
'p normal aproximado',round(p,4),'p Bonferroni',round(min(1,4*p),4))
print('Contrastes aproximados condicionados al modelo entrenado; no certifican efectos individuales.')# Umbral de prioridad fijado con entrenamiento, objetivo aproximado 30 %.
prioridad_train=e_cf*x0.predict(P_train)+(1-e_cf)*x1.predict(P_train)
umbral=float(np.quantile(prioridad_train,.7))
politica=(tau_x>=umbral).astype(int)
mu0_score=mu0_eval+(1-t_test)*(y_test-mu0_eval)/(1-e_eval)
valor_score=mu0_score+politica*gamma_eval
ganancia=politica*gamma_eval
print('Proporción tratada en evaluación:',round(float(politica.mean()),4))
print('Valor DR estimado:',round(float(valor_score.mean()),4))
print('Ganancia incremental DR:',round(float(ganancia.mean()),4))
print('EE condicional de la ganancia:',round(float(ganancia.std(ddof=1)/np.sqrt(len(ganancia))),4))
print('La política y su umbral se fijaron sin utilizar resultados de evaluación.')Honest forest and policies locally
Prepare a compatible isolated environment, for example Python 3.13, and install dependencies with pip install "numpy==2.2.6" "scipy==1.15.3" "scikit-learn==1.6.1" "econml==0.16.0" "doubleml==0.11.4". DoubleML downloads the 401(k) dataset. Normal execution trains the full example forest and bootstrap; set environment variable ORYON_SHORT=1 for a quick check, whose eight resamples do not support reliable inference.
The custom forest is a teaching simplification: it chooses splits with one half of each subsample and estimates leaves with the other. It does not exactly reproduce generalized random forests’ criterion or inference. Its percentile bootstrap intervals are exploratory and coverage is not guaranteed. The policy tree uses greedy splits without guaranteeing the global class optimum; evaluation standard errors condition on already fitted models. Those intervals describe the mean of calculated scores: if clipped propensity and estimated means are incorrect, they omit that bias and do not guarantee causal-value coverage. In 401(k), eligibility is not participation and not all covariates have been shown to precede treatment: interpret results as an observational comparison under assumptions, not causal proof. True regret is calculated only in simulation.
"""Bosque honesto, EconML y aprendizaje de políticas.
Requiere Python local con NumPy, SciPy, scikit-learn, EconML y DoubleML.
Consulta la preparación del entorno y las limitaciones en el texto.
"""
import os
for variable in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS',
'NUMEXPR_NUM_THREADS'):
os.environ[variable] = '1'
import numpy as np
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.model_selection import StratifiedKFold, train_test_split
from sklearn.tree import DecisionTreeClassifier
from threadpoolctl import threadpool_limits
from econml.dml import CausalForestDML
from doubleml.datasets import fetch_401K
import econml
import doubleml
SHORT = os.environ.get('ORYON_SHORT', '0') == '1'
SEED = 272701
def datos_sinteticos(n, seed):
"""Tratamiento aleatorizado, mecanismos y CATE conocidos."""
rng = np.random.default_rng(seed)
X = rng.uniform(-1, 1, size=(n, 3))
tau = 1.2 * X[:, 0] + .4 * X[:, 1]
mu0 = .5 * X[:, 0] + .3 * X[:, 1] ** 2
T = rng.binomial(1, .5, n)
Y = mu0 + T * tau + rng.normal(0, 1, n)
return X, T, Y, mu0, tau
def honest_tree(X, T, Y, random, max_depth=2, min_arm=8, groups=None):
"""Estructura y efectos se estiman en dos mitades disjuntas.
El criterio de partición es deliberadamente simple: producto de tamaños
de las hijas por la diferencia cuadrática de sus efectos. No es GRF.
"""
if groups is None:
groups = np.arange(len(Y))
unique_groups = np.unique(groups)
subset = random.choice(unique_groups, size=int(.7*len(unique_groups)), replace=False)
random.shuffle(subset)
split = len(subset)//2
# Las copias bootstrap de una misma unidad siempre van a la misma mitad.
structure = np.flatnonzero(np.isin(groups, subset[:split]))
estimation = np.flatnonzero(np.isin(groups, subset[split:]))
def supported(indices):
return min(np.count_nonzero(T[indices] == 0),
np.count_nonzero(T[indices] == 1)) >= min_arm
def estimate(indices):
return float(Y[indices][T[indices] == 1].mean()
- Y[indices][T[indices] == 0].mean())
def grow(si, ei, depth):
if not supported(si) or not supported(ei):
return None
leaf = {'effect': estimate(ei), 'n0': int(np.sum(T[ei] == 0)),
'n1': int(np.sum(T[ei] == 1))}
if depth == max_depth:
return leaf
best = None
for j in range(X.shape[1]):
for threshold in np.unique(np.quantile(X[si, j], [.25, .5, .75])):
sl, sr = si[X[si, j] <= threshold], si[X[si, j] > threshold]
el, er = ei[X[ei, j] <= threshold], ei[X[ei, j] > threshold]
if not all(supported(z) for z in (sl, sr, el, er)):
continue
diff = estimate(sl)-estimate(sr)
score = len(sl)*len(sr)/(len(sl)+len(sr)) * diff**2
if best is None or score > best[0]:
best = (score, j, float(threshold), sl, sr, el, er)
if best is not None:
_, j, threshold, sl, sr, el, er = best
leaf.update(feature=j, threshold=threshold,
left=grow(sl, el, depth+1), right=grow(sr, er, depth+1))
return leaf
return grow(structure, estimation, 0)
def forest_predictions(X, T, Y, Xtest, trees, seed, groups=None):
"""Promedia diferencias de medias por hoja de árboles honestos."""
random = np.random.default_rng(seed)
predictions = []
for _ in range(trees):
root = honest_tree(X, T, Y, random, groups=groups)
if root is None:
continue
values = np.empty(len(Xtest))
for i, x in enumerate(Xtest):
node = root
while 'feature' in node:
node = node['left'] if x[node['feature']] <= node['threshold'] else node['right']
values[i] = node['effect']
predictions.append(values)
if not predictions:
raise RuntimeError('Ningún árbol tiene apoyo suficiente en ambos brazos')
return np.mean(predictions, axis=0), len(predictions)
def forest_bootstrap_interval(X, T, Y, Xtest, repetitions, trees, seed):
"""Bootstrap n-out-of-n: reentrena un bosque por remuestra completa.
Percentiles exploratorios para puntos fijados de antemano, sin garantizar
cobertura; se agrupan duplicados de la misma unidad en cada árbol.
"""
random = np.random.default_rng(seed)
estimates = []
n = len(Y)
for b in range(repetitions):
indices = random.integers(0, n, n)
estimate, _ = forest_predictions(X[indices], T[indices], Y[indices],
Xtest, trees, seed+b+1, groups=indices)
estimates.append(estimate)
return np.quantile(np.asarray(estimates), [.025, .975], axis=0)
def nuisance_models(seed, trees):
outcome = RandomForestRegressor(n_estimators=trees, min_samples_leaf=15,
max_features=.8, n_jobs=1, random_state=seed)
propensity = RandomForestClassifier(n_estimators=trees, min_samples_leaf=15,
max_features=.8, n_jobs=1, random_state=seed+1)
return outcome, propensity
def fit_nuisances(X, T, Y, seed, trees):
"""Modelos de resultado por brazo y probabilidad de tratamiento."""
m0, _ = nuisance_models(seed, trees)
m1, e = nuisance_models(seed+2, trees)
m0.fit(X[T == 0], Y[T == 0])
m1.fit(X[T == 1], Y[T == 1])
e.fit(X, T)
if not np.array_equal(e.classes_, [0, 1]):
raise ValueError('Se necesitan ambos brazos de tratamiento')
return m0, m1, e
def scores_from_fit(fits, X, T, Y, clip=.05):
m0, m1, model_e = fits
mu0, mu1 = m0.predict(X), m1.predict(X)
raw_e = model_e.predict_proba(X)[:, 1]
e = np.clip(raw_e, clip, 1-clip)
gamma0 = mu0 + (1-T)*(Y-mu0)/(1-e)
gamma1 = mu1 + T*(Y-mu1)/e
return gamma0, gamma1-gamma0, raw_e
def training_scores(X, T, Y, seed, trees):
"""Nuisances para política entrenadas fuera del pliegue puntuado."""
n = len(Y)
gamma0, gamma, prop = np.empty(n), np.empty(n), np.empty(n)
folds = StratifiedKFold(n_splits=3, shuffle=True, random_state=seed)
for k, (tr, va) in enumerate(folds.split(X, T)):
fits = fit_nuisances(X[tr], T[tr], Y[tr], seed+10*k, trees)
gamma0[va], gamma[va], prop[va] = scores_from_fit(fits, X[va], T[va], Y[va])
return gamma0, gamma, prop
def policy_fit(X, gamma, seed):
"""Árbol greedy de profundidad 2; no afirma óptimo global de la clase."""
if not np.any(np.abs(gamma) > 0):
raise ValueError('No hay variación en las puntuaciones')
policy = DecisionTreeClassifier(max_depth=2, min_samples_leaf=30,
random_state=seed)
policy.fit(X, (gamma > 0).astype(int), sample_weight=np.abs(gamma))
return policy
def summarize(name, values):
values = np.asarray(values, float)
mean = float(values.mean())
se = float(values.std(ddof=1)/np.sqrt(len(values)))
print(name, 'media', round(mean, 4), '| EE condicional', round(se, 4),
'| IC normal 95%', (round(mean-1.96*se, 4), round(mean+1.96*se, 4)))
def simulation_demo():
n_train, n_test = (1200, 1200) if SHORT else (3000, 5000)
X, T, Y, _, _ = datos_sinteticos(n_train, SEED)
Xe, Te, Ye, mu0e, taue = datos_sinteticos(n_test, SEED+1)
forest_trees, nuisance_trees = (8, 15) if SHORT else (40, 50)
own, used = forest_predictions(X, T, Y, Xe, forest_trees, SEED+2)
econ = CausalForestDML(discrete_treatment=True, n_estimators=40 if SHORT else 120,
subforest_size=4, min_samples_leaf=8, max_depth=8,
max_samples=.45, cv=2, honest=True, inference=True,
n_jobs=1, random_state=SEED+3)
econ.fit(Y, T, X=X)
cate_econ = np.asarray(econ.effect(Xe)).reshape(-1)
print('\nSIMULACIÓN | entrenamiento', n_train, '| evaluación', n_test,
'| árboles propios usados', used)
print('ECM CATE propio y EconML:', round(float(np.mean((own-taue)**2)), 5),
round(float(np.mean((cate_econ-taue)**2)), 5))
print('Comparación de predicción frente a verdad sintética, no prueba de cobertura.')
low, high = econ.effect_interval(Xe[:3], alpha=.05)
bootstrap_enabled = os.environ.get('ORYON_BOOTSTRAP', '1') != '0'
if bootstrap_enabled:
repetitions, bootstrap_trees = (8 if SHORT else 100), forest_trees
own_low, own_high = forest_bootstrap_interval(
X, T, Y, Xe[:3], repetitions, bootstrap_trees, SEED+12)
print('Bootstrap exploratorio propio:', repetitions, 'remuestras completas,',
bootstrap_trees, 'árboles reentrenados en cada remuestra')
if SHORT:
print('Ocho remuestras solo comprueban el flujo y no sirven para inferencia fiable.')
for j in range(3):
print('Punto', j, '| CATE real', round(float(taue[j]), 4),
'| EconML', round(float(cate_econ[j]), 4), '| IC puntual',
(round(float(low[j]), 4), round(float(high[j]), 4)))
if bootstrap_enabled:
print(' Bosque propio', round(float(own[j]), 4), '| IC bootstrap exploratorio',
(round(float(own_low[j]), 4), round(float(own_high[j]), 4)))
print('Los intervalos del bosque propio son aproximaciones sin garantía de cobertura;')
print('tres puntos no demuestran cobertura de ninguno de los dos métodos.')
_, gamma, _ = training_scores(X, T, Y, SEED+4, nuisance_trees)
policy = policy_fit(X, gamma, SEED+5)
treatment = policy.predict(Xe)
oracle = (taue > 0).astype(int)
observed_gain = treatment * taue
oracle_gain = oracle * taue
print('Fracción tratada por árbol aprendido:', round(float(treatment.mean()), 4))
summarize('Valor verdadero Monte Carlo del árbol', mu0e+observed_gain)
summarize('Valor verdadero Monte Carlo del oráculo irrestricto', mu0e+oracle_gain)
summarize('Regret frente al oráculo irrestricto', oracle_gain-observed_gain)
fits = fit_nuisances(X, T, Y, SEED+6, nuisance_trees)
gamma0, gamma_eval, raw_e = scores_from_fit(fits, Xe, Te, Ye)
summarize('Valor DR del árbol en evaluación', gamma0+treatment*gamma_eval)
summarize('Ganancia DR frente a no tratar', treatment*gamma_eval)
print('Propensiones de evaluación recortadas:', int(np.sum((raw_e < .05) | (raw_e > .95))))
print('El regret es una media Monte Carlo de diferencias conocidas por el DGP;')
print('sus EE reflejan el muestreo de evaluación, no la variación del entrenamiento.')
def real_401k_demo():
controls = ['age', 'inc', 'educ', 'fsize', 'marr', 'twoearn', 'db', 'pira', 'hown']
data = fetch_401K(return_type='DataFrame')
frame = data[['net_tfa', 'e401'] + controls].dropna().reset_index(drop=True)
X = frame[controls].to_numpy(dtype=float)
T = frame['e401'].to_numpy(dtype=int)
Y = frame['net_tfa'].to_numpy(dtype=float)
tr, va = train_test_split(np.arange(len(Y)), test_size=.35, random_state=SEED+8,
stratify=T)
trees = 15 if SHORT else 50
_, gamma_train, prop_train = training_scores(X[tr], T[tr], Y[tr], SEED+9, trees)
policy = policy_fit(X[tr], gamma_train, SEED+10)
fits = fit_nuisances(X[tr], T[tr], Y[tr], SEED+11, trees)
gamma0, gamma_eval, prop_eval = scores_from_fit(fits, X[va], T[va], Y[va])
treatment = policy.predict(X[va])
print('\n401(k) | DoubleML', doubleml.__version__, '| n', len(Y),
'| entrenamiento', len(tr), '| evaluación', len(va))
print('Tratamiento: elegibilidad e401; resultado: activos financieros netos net_tfa.')
print('Árbol de profundidad 2, greedy; fracción tratada:', round(float(treatment.mean()), 4))
print('Propensiones de evaluación: mínimo', round(float(prop_eval.min()), 4),
'máximo', round(float(prop_eval.max()), 4),
'| recortadas a [0,05; 0,95]:', int(np.sum((prop_eval < .05) | (prop_eval > .95))))
print('Recorte fuera de intervalo en puntuaciones de entrenamiento:',
int(np.sum((prop_train < .05) | (prop_train > .95))))
summarize('Valor estimado: no tratar', gamma0)
summarize('Valor estimado: tratar a todos', gamma0+gamma_eval)
summarize('Valor estimado: árbol', gamma0+treatment*gamma_eval)
summarize('Diferencia pareada: árbol menos no tratar', treatment*gamma_eval)
summarize('Diferencia pareada: árbol menos tratar a todos', (treatment-1)*gamma_eval)
print('EE condicionales: política y nuisances quedan fijas; no incluyen incertidumbre')
print('de entrenamiento ni hacen válidos supuestos de ignorabilidad o modelos.')
print('Es una comparación observacional. La temporalidad de covariables no está')
print('garantizada; selección, ausencia de confusión, solapamiento y recorte importan.')
print('No hay oráculo ni regret verdadero observado en estos datos.')
print('EconML', econml.__version__, '| ejecución corta', SHORT)
with threadpool_limits(limits=1):
simulation_demo()
real_401k_demo()npm run lab and open the connection link.Exercises
Step 1 of 3. What is the treated term’s conditional expectation?
Step 1 of 3. What is the conditional mean of Y−m(X) given X and T?
def x_learner(X, t, y, base_learner):
"""Ajusta cuatro clones y devuelve una función de predicción de CATE."""
raise NotImplementedError('Implementa el X-learner')Check the numeric exercise after solving it:
prioridades = np.array([3,7,9,1,8,2,4,10,6,5])
puntuaciones = np.array([.2,1.1,.7,-.1,1.4,.3,.8,1.9,-.3,.6])
elegidos = np.argsort(-prioridades)[:3]
ganancia_numerica = puntuaciones[elegidos].sum()/len(puntuaciones)
print('Identificadores elegidos:',elegidos+1,'| ganancia incremental:',ganancia_numerica)
assert abs(ganancia_numerica-.4)<1e-12