Module contents
Lesson 27 of 28Advanced 120 min

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

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 T∈{0,1}T\in\{0,1\} be assignment and Y(0),Y(1)Y(0),Y(1) potential outcomes. The conditional average treatment effect is

τ(x)=E[Y(1)−Y(0)∣X=x].\tau(x)=E[Y(1)-Y(0)\mid X=x].

This is an average for units with covariates xx, not an observed individual effect. With consistency, no interference, joint exchangeability (Y(0),Y(1))⊥T∣X(Y(0),Y(1))\perp T\mid X, and overlap 0<e(x)=P(T=1∣X=x)<10<e(x)=P(T=1\mid X=x)<1,

τ(x)=μ1(x)−μ0(x),μt(x)=E[Y∣T=t,X=x].\tau(x)=\mu_1(x)-\mu_0(x),\qquad \mu_t(x)=E[Y\mid T=t,X=x].

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 m(x)=E[Y∣X=x]m(x)=E[Y\mid X=x]. 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 μ^(x,t)\widehat\mu(x,t) and calculate μ^(x,1)−μ^(x,0)\widehat\mu(x,1)-\widehat\mu(x,0). It can share information across arms, but strong regularization or a model without interactions may ignore variation associated with tt. This is not inevitable for every learner and does not prove S is always worse.

T-learner. Fit μ^1\widehat\mu_1 among treated units and μ^0\widehat\mu_0 among controls, then subtract predictions. Each fit uses one arm: a sparse group or missing support for some xx 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 D1=Y−μ^0(X)D^1=Y-\widehat\mu_0(X) and for each control D0=μ^1(X)−YD^0=\widehat\mu_1(X)-Y; then fit functions of these two pseudo-effects within their arms. One possible combination is

τ^X(x)=e^(x)τ^0(x)+(1−e^(x))τ^1(x).\widehat\tau_X(x)=\widehat e(x)\widehat\tau_0(x) +(1-\widehat e(x))\widehat\tau_1(x).

Here τ^1\widehat\tau_1 was fitted among treated units and τ^0\widehat\tau_0 among controls. This convention gives more weight to the treated-trained function when ee 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 D1D^1 among treated units given X=xX=x is μ1(x)−μ^0(x)\mu_1(x)-\widehat\mu_0(x); that of D0D^0 among controls is μ^1(x)−μ0(x)\widehat\mu_1(x)-\mu_0(x). 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.

InteractiveFive learners in the same world

Simulate X uniform on [−1,1], random treatment with probability p, and Y = m₀(X) + T·τ(X) + ε, with normal ε of standard deviation 0.65. Baseline response is 0.5X, with or without sin(3πX). The same seed is used in all scenarios.

  • True CATE
  • Estimated CATE
S-learnerMSE: 0.039
−0.90.31.6-101X
T-learnerMSE: 0.033
−0.90.31.6-101X
X-learnerMSE: 0.030
−0.90.31.6-101X
R-learnerMSE: 0.021
−0.90.31.6-101X
DR-learnerMSE: 0.034
−0.90.31.6-101X

All five use a common radial basis and penalized regression. S penalizes interactions with T, including its intercept; T fits each arm separately. X combines pseudo-effects with weights p and 1−p. R and DR use out-of-fold nuisance models; propensity p is known by design.

MSE averages error against true CATE at 101 grid points without using training outcomes for evaluation. Truth is known only because the mechanism is simulated. The chosen basis may smooth the step; none of these comparisons makes one method a universal winner.

True effect
Baseline response
Randomized treatment
Sample size
Treated207
Controls193
Penalty λ0.01
Seed2727
Change treatment and effect shape; compare actual fits with simulator truth.

The R residual loss

The R-learner minimizes, with out-of-fold nuisance predictions,

1n∑i[(Yi−m^(Xi))−(Ti−e^(Xi))f(Xi)]2.\frac1n\sum_i\left[(Y_i-\widehat m(X_i)) -(T_i-\widehat e(X_i))f(X_i)\right]^2.

With true functions, under the earlier causal assumptions and finite second moments, E[Y−m(X)∣X,T]=(T−e(X))τ(X)E[Y-m(X)\mid X,T]=(T-e(X))\tau(X). The risk difference between ff and τ\tau is

E ⁣[e(X)(1−e(X))(f(X)−τ(X))2].E\!\left[e(X)(1-e(X))(f(X)-\tau(X))^2\right].

Under overlap, the unrestricted pointwise minimizer is τ\tau. Restricting ff to a family yields a projection weighted by e(1−e)e(1-e), which need not equal the best unweighted approximation. Do not naively divide by T−e(X)T-e(X) 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

Γ=μ^1(X)−μ^0(X)+T(Y−μ^1(X))e^(X)−(1−T)(Y−μ^0(X))1−e^(X)\Gamma=\widehat\mu_1(X)-\widehat\mu_0(X) +\frac{T(Y-\widehat\mu_1(X))}{\widehat e(X)} -\frac{(1-T)(Y-\widehat\mu_0(X))}{1-\widehat e(X)}

on XX. If estimated functions are treated as fixed because they were learned on independent data, with 0<e^(x)<10<\widehat e(x)<1 and finite expectations, conditional bias of Γ\Gamma relative to τ\tau is

(e^−e)[μ^1−μ1e^+μ^0−μ01−e^].(\widehat e-e)\left[ \frac{\widehat\mu_1-\mu_1}{\widehat e} +\frac{\widehat\mu_0-\mu_0}{1-\widehat e} \right].

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 YY 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.

InteractiveChoose a leaf and estimate its effect

First choose the split that separates the estimated effects of two leaves most. Then compare estimation on independent observations with reuse of those that chose the split.

First valid replicate: split X=0.35; the leaf with highest estimated effect at splitting is right. Bars are approximate 95% normal intervals; dots show each leaf’s true effect under the model.

LeftRight *−1.51.1
  • Estimate and approximate interval
  • True leaf effect

Coverage over 237 valid replicates: honest 92.0 % and reused 89.0 %. Monte Carlo error for the selected reading measures only finite-replicate variation; it does not guarantee nominal coverage. 3 attempts are excluded for insufficient observations in a leaf or arm.

Honest92.0 %
Reused89.0 %

Model: X uniform on [0,1], randomized treatment with probability ½, and Y=0.5X+T·1(X≥0.5)+ε, with independent normal ε and adjustable standard deviation. Each leaf’s true mean effect integrates the step over its interval. Each replicate generates two independent equal halves; both strategies use the first to choose among five fixed splits. Reuse estimates on that same half and honest estimation on the second. Each leaf of both halves requires at least five treated and five controls.

The criterion selects the largest absolute difference between estimates, and coverage is measured in the leaf that looked best in the first half. This depth-one tree illustrates selection and honesty; it does not implement the full causal forest criterion. Intervals use sample variances from both arms and normal quantiles, so neither honesty nor 95% guarantees exact finite-sample coverage. Seed 2727. See Wager and Athey.

Observations per half
Noise standard deviation
Example intervals
Selected-leaf coverage92.0 %
Monte Carlo error1.8 %
Mean bias0.009
Valid replicates / attempts237 / 240
Compare splits and coverage with separate or reused samples.

Evaluate without knowing individual effects

Good factual outcome prediction is insufficient to evaluate τ^\widehat\tau. For priority S(X)S(X) fixed without evaluation outcomes, consider the top fraction qq and define

TOC⁡(q)=E[τ(X)∣S(X) en el q superior]−E[τ(X)].\operatorname{TOC}(q)=E[\tau(X)\mid S(X)\text{ en el }q\text{ superior}] -E[\tau(X)].

The RATE family integrates TOC⁡(q)\operatorname{TOC}(q) with a weight function. AUTOC uses weight one; QINI uses weight qq. If cumulative gain per population unit is G(q)=qE[τ∣top q]G(q)=qE[\tau\mid\text{top }q], its difference from random treatment is qTOC⁡(q)q\operatorname{TOC}(q): 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.

InteractivePrioritize under a budget

Rank 400 units by a signal fixed before observing outcomes. The curve shows gain per person in the whole population when treating the highest-priority fraction q; the dashed line represents randomly treating the same fraction.

  • Estimated cumulative gain
  • Random reference
  • Selected budget

Treated fraction q

TOC(q) compares mean effect in the priority group with the full sample mean effect. Its area is AUTOC. Gain minus reference is q × TOC(q); the area of that difference is QINI. They are distinct members of the RATE family.

  • Estimated TOC
  • No improvement over average

Treated fraction q

Model: X uniform on [−1, 1], T assigned with probability ½, Y=X²+T(0.4+1.2X)+ε with normal ε of standard deviation 0.5. AIPW scores use true means and propensity; they are noisy even when the model is known. Direct signal is X+noise, inverse is −X+noise, and random signal does not use X. These are not fitted models.

For treating 30.0 %, true gain in this simulated sample is 0.333 per person in the population; the estimate uses observed outcomes and true model functions and may differ. Gain is incremental versus no treatment, not absolute policy value. Seed 272701.

G(q) linearly interpolates gains between consecutive ranks, equivalent to treating a fraction of the next unit. QINI and AUTOC integrals use this interpolation; the TOC curve connects rank values and shows the right-hand limit at q=0. Priority ties are broken by index. One sample provides no uncertainty estimate and does not establish universal superiority.

Simulated priority
0.4
30
Estimated gain at budget0.309
TOC at budget0.620
QINI0.171
AUTOC0.531
Compare cumulative gain and ranking measures for the same sample.

From estimation to decisions

A policy π(X)∈{0,1}\pi(X)\in\{0,1\} decides whom to treat. Its absolute value and gain versus no treatment are

V(π)=E[μ0(X)+π(X)τ(X)],V(π)−V(0)=E[π(X)τ(X)].V(\pi)=E[\mu_0(X)+\pi(X)\tau(X)],\qquad V(\pi)-V(0)=E[\pi(X)\tau(X)].

A tree rule can be selected by maximizing the average of π(Xi)Γi\pi(X_i)\Gamma_i over a declared class. If each treatment costs c(X)c(X), optimize net gain π(X)(Γ−c(X))\pi(X)(\Gamma-c(X)); 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 V(π⋆)−V(π)V(\pi^\star)-V(\pi) depends on oracle π⋆\pi^\star: 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.

[ ]Set up NumPyBrowser
import numpy as np
[ ]Set up regressionsBrowser
from sklearn.linear_model import Ridge, LogisticRegression
[ ]Set up foldsBrowser
from sklearn.model_selection import StratifiedKFold
[ ]Generate the world and split samplesBrowser
def 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
[ ]Fit nuisances out of foldBrowser
# 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]
[ ]Fit five meta-learnersBrowser
# 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.

[ ]Compare six simulated worldsBrowser
# 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.

[ ]Evaluate ranking with AIPWBrowser
# 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.')
[ ]Examine group calibrationBrowser
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.')
[ ]Value a fixed policyBrowser
# 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.

[ ]Honest forest and policy with 401(k)Local GPU
"""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()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofThe pseudo-outcome and its errors
Prove: Assume consistency, exchangeability, overlap, and nuisance functions estimated on an independent sample, with 0<e^(x)<10<\widehat e(x)<1 and finite expectations. Prove that E[Γ∣X=x]=τ(x)E[\Gamma\mid X=x]=\tau(x) if propensity is correct or both outcome means are correct.
The proof will appear here as you work.

Step 1 of 3. What is the treated term’s conditional expectation?

ProofThe minimum residual loss
Prove: With m(X)=E[Y∣X]m(X)=E[Y\mid X], e(X)=P(T=1∣X)e(X)=P(T=1\mid X), the lesson’s causal assumptions and finite second moments, derive R-learner excess risk relative to τ\tau.
The proof will appear here as you work.

Step 1 of 3. What is the conditional mean of Y−m(X) given X and T?

NumericPrioritize three of ten
For ten units, priorities in identifier order 1 to 10 are [3, 7, 9, 1, 8, 2, 4, 10, 6, 5] and AIPW scores are [0.2, 1.1, 0.7, −0.1, 1.4, 0.3, 0.8, 1.9, −0.3, 0.6]. Treat the top 30%. Calculate estimated incremental gain per population unit: their score sum divided by ten.
CodeBuild an X-learner
Implement x_learner(X, t, y, base_learner). X is a finite numeric matrix with observations in rows and at least one column; t and y are equal-length vectors, t contains only 0 or 1, and each arm has at least two observations. Reject invalid input with ValueError. base_learner is a regressor compatible with sklearn.base.clone, fit(X,y), and predict(X), returning finite vector predictions. Do not modify the learner or input data. Fit independent clones μ̂₀ and μ̂₁ by arm. For controls construct D⁰=μ̂₁(X)−Y; for treated units D¹=Y−μ̂₀(X). Fit two further clones τ̂₀ and τ̂₁ to their respective pseudo-effects. Fit scikit-learn LogisticRegression with C=1.0 and max_iter=500 to estimate ê(X)=P(T=1|X), using all observations. Clip ê to [0.01, 0.99] when predicting. Return a predict(X_new) function accepting a nonempty finite numeric matrix with the same column count, rejecting other inputs with ValueError, and returning a vector ê(X_new)τ̂₀(X_new)+(1−ê(X_new))τ̂₁(X_new). Train all models once inside x_learner, not at each prediction. This version uses the same observations to fit means and form pseudo-effects; it does not implement cross-fitting. Causal interpretation requires consistency, ignorability, and overlap; clipping probabilities does not create overlap or guarantee correct models.
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')
Shift+Enter to run
QuizA sparse arm
You have many controls and few treated units, and the effect appears simpler than baseline response. What is a reasonable comparison?
QuizRegularization and a small effect
An S-learner predicts Y well but its regularized model barely uses T. What risk should you investigate?
QuizFew data in both arms
In a small balanced trial you suspect a nearly constant effect. What initial strategy is most defensible?
QuizComplex heterogeneity with strong overlap
You have a large sample with support in both arms and suspect highly nonlinear CATE. Which comparison is most informative?
QuizWeak overlap
A DR-learner produces huge scores where estimated propensities approach zero. What should you do first?
QuizA policy chosen among many
You search hundreds of trees and select the one with highest value on the same data. What is needed to value it?

Check the numeric exercise after solving it:

[ ]Calculate budgeted gainBrowser
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