Algorithmresearch
Double machine learning
Also called DML, debiased machine learning.
Estimates a causal parameter with machine learning for the nuisance functions, using orthogonal scores and cross-fitting so that the parameter is root-n consistent.
- Time
- Θ(n + k C) worst · best
- Space
- Θ(n) extra
- Where
- C = the cost of fitting one learner on at most n units and predicting; k = the number of folds; n = the number of units
- Model
- Real RAM
- Properties
- cross fitteddeterministic given foldsdoubly robust ate scoreneeds positivityneyman orthogonal score
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Victor Chernozhukov, Denis Chetverikov, Mert Demirer, Esther Duflo, Christian Hansen, Whitney Newey, James Robins, 2018
Double machine learning (DML) estimates a low-dimensional causal parameter, such as the average treatment effect or the coefficient of a treatment in a partially linear model, when the nuisance functions (the propensity score, the outcome regressions) are fitted by flexible learners such as the lasso, random forests or gradient boosting. Two ideas make this work. The estimate solves a Neyman orthogonal score, whose mean does not move to first order when the nuisances are slightly wrong, so the learners' bias enters only as a product of two errors. And the nuisances for each unit are fitted on the other folds of the data (cross-fitting), so the unit's own noise cannot leak into its own prediction. Under rate conditions that many learners meet, the estimate is -consistent and asymptotically normal, with an ordinary confidence interval.
In plain words
Machine learning models predict well, but they are biased on purpose: they trade bias for less noise. If you plug their predictions straight into an effect estimate, that bias goes straight into the answer, and the usual confidence interval is wrong.
DML does two things. First, it uses an estimating formula built so that errors in the predictions cancel to first order. With two separate predictions, one for the treatment and one for the outcome, only the product of their errors is left, and a product of two small numbers is very small. Second, it splits the data into parts. The predictions for each part come from models trained on the other parts, so no person's own outcome is used to make that person's prediction. Then it pools the answers.
The problem
Identification. For the ATE: potential outcomes , treatment , covariates , and the estimand . Under consistency with SUTVA, ignorability and positivity, with the AIPW score
evaluated at the true nuisances , as on the AIPW page. For the partially linear model with and a continuous or binary , the parameter is . It is causal if, in addition, is as good as random given and the effect of is the same constant for everyone; it is identified by with , , if is not a function of . Ignorability, SUTVA and the constant effect cannot be checked from the observed data.
Estimation. The input is units , a number of folds (5 is common), and learners: functions that take training data and return a predictor. The output is the estimate, its standard error and a normal confidence interval.
The algorithm
DML-ATE(X, T, Y, k, learn_e, learn_m)- 1
give each unit a fold label in {0, ..., k - 1}: a random permutation cut into k near-equal parts - 2
for f ← 0 to k - 1 do - 3
ê ← learn_e(units not in fold f) ▷ predicts T from X - 4
m̂1 ← learn_m(treated units not in fold f); m̂0 ← learn_m(control units not in fold f) - 5
for each unit i in fold f do - 6
ψ_i ← m̂1(X_i) - m̂0(X_i) + T_i (Y_i - m̂1(X_i)) / ê(X_i) - (1 - T_i)(Y_i - m̂0(X_i)) / (1 - ê(X_i)) - 7
τ̂ ← (1/n) Σ_i ψ_i - 8
return τ̂ and v = Σ_i (ψ_i - τ̂)² / (n (n - 1))
Lines L3 and L4 never see the units of fold , and line L6 uses the fitted functions only on those units. Line L7 pools all the scores (the DML2 form of Chernozhukov et al.); averaging the fold estimates instead (DML1) gives the same answer here when the folds have equal sizes, because the score is linear in . The interval is . Predicted propensities can be clipped to for a small ; the clip changes the estimand slightly and should be reported.
Partially linear model. The same loop fits (a regression of on ) and (of on ) on the other folds, forms the residuals and , and returns the residual-on-residual coefficient (Robinson 1988). Its sandwich variance is with .
Repeated splits. The estimate depends on the random folds. Chernozhukov et al. suggest repeating the whole procedure with several fold assignments and reporting the median estimate, with a variance that adds the spread across splits.
Example
With (no cross-fitting) and least squares on the same features for both nuisances, the partially linear estimate is exactly the coefficient of in the least squares regression of on and those features. Take four units with , and , and the features . The regression of on has intercept and slope , with fitted values , so . The regression of on has intercept and slope 2, with fitted values , so . Then . The regression of on gives , with the same coefficient on . This is the Frisch-Waugh-Lovell theorem, and DML generalizes it: replace the two linear fits by any learners, and fit them on other folds.
Simulation. For the ATE, take uniform on , and with standard normal , so the true ATE is 1.5. The learners are regressograms: the mean in each of equal bins of . With , and 300 samples (seed 2026):
| outcome learner | propensity learner | estimator | mean | SD | 95% coverage |
|---|---|---|---|---|---|
| 2 bins | 10 bins | plug-in regression | 1.782 | 0.080 | |
| 2 bins | 10 bins | DML | 1.495 | 0.084 | 0.970 |
| 10 bins | 10 bins | DML | 1.520 | 0.083 | 0.950 |
The coarse outcome learner alone is biased by 0.28; the orthogonal score removes almost all of it, because the propensity learner is good. For the partially linear model with and , the regression of on gives a mean of 1.169 (coverage 0), while DML with 20-bin learners gives 0.510 (SD 0.035, coverage 0.913). These numbers are measured, not proved.
Correctness
The proofs establish:
- the folds partition the units, with sizes that differ by at most 1, and with learners that ignore their training data DML is exactly the AIPW estimate;
- with cross-fitting, conditionally on the other folds, the mean of each unit's score differs from by the exact AIPW bias formula, which, when the fitted propensity stays in , is bounded by : a product of the two nuisance errors;
- the ATE score and the partially linear score are Neyman orthogonal: the derivative of their mean in any direction of the nuisances is 0 at the truth;
- without cross-fitting and with linear learners on the same features, the partially linear estimate is the OLS coefficient (Frisch-Waugh-Lovell).
The asymptotic normality of under overlap (the true and fitted propensities stay in ), consistency of each nuisance learner, and the rate condition , and the validity of the interval, are cited from Chernozhukov et al. (2018), not proved.
Proof: Cross-fitting makes the bias of the DML estimate a product of nuisance errors, and the score is Neyman orthogonalfull
The units , , are independent copies of . For the ATE, assume consistency with SUTVA, ignorability and positivity as on the AIPW page, and write and . For working functions the AIPW score is
Lemma 1 (folds). MAKE-FOLDS gives every unit one label in , and the fold sizes differ by at most 1.
Proof. The unit at position of the permutation, , gets label , which is in . Label goes to the positions with , which number . This is or , since is one of these two for every real .
Lemma 2 (the loop). DML-ATE returns , where is the fold of unit and is fitted on the units outside fold . If the learners ignore their training data and return fixed functions , then is the AIPW estimate with , for every and every fold assignment.
Proof. Line L2 visits each fold once, and by Lemma 1 every unit is in exactly one fold, so line L6 sets each once, with the nuisances of line L3 and L4 fitted on the other folds. Line L7 averages. If the learners return fixed , every .
Exact bias with cross-fitting
Theorem 3. Let be the units outside fold , and suppose the fitted propensity satisfies . For a unit in fold ,
with the functions fitted on and the expectation over a new . Hence
where .
Proof. The units are independent, so is independent of , and given the functions are fixed. The bias identity of the AIPW page (Theorem 2 there) holds for any fixed working functions, so it applies to conditionally on . The bound follows by the Cauchy-Schwarz inequality, as in Corollary 4 there.
Without cross-fitting (), depends on itself, the conditioning step fails, and has no such form; an overfitted learner can then make the residuals small for the units it was fitted on. The tests check the key fact behind Theorem 3: with cross-fitting, raising by 1 changes by exactly (or ) and leaves the other scores of its fold unchanged, while with other scores change too.
Neyman orthogonality
Theorem 4 (ATE score). Let , and for bounded directions let . Then .
Proof. By the bias identity with and ,
For small, and stay above if , so the expectation is bounded, and the whole is . Its derivative at is 0.
Theorem 5 (partially linear score). In the model with , let , , and . Then , and the derivative of at is 0. If , then .
Proof. , so . Write , which has . Then . With the perturbed functions, the score is , whose mean is
because , and because . So the mean is times a constant, with derivative 0 at . The last claim: .
Theorem 6 (no cross-fitting, linear learners). If and both learners are least squares on the same feature vector , and the regression of on has a unique solution, then equals the OLS coefficient of in that regression.
Proof. This is the Frisch-Waugh-Lovell theorem. Let be the feature matrix, the projection on its columns and . The fitted learners give the residuals and , so . The OLS fit is with and . Then , and . So . Uniqueness of the OLS solution means is not in the column span of , so , and .
What is not proved here
The asymptotic normality with , under the conditions that the propensity stays in , that each nuisance error tends to 0, and that the product of the propensity error and the outcome error is , and the same result for in the partially linear model, are cited from Chernozhukov et al. (2018). Theorem 3 shows why the product condition controls the bias; the control of the remaining empirical-process term by cross-fitting is in that paper. The simulation numbers on the page are measured.
Complexity
Each of the folds fits three learners (one for the propensity and one per arm) on about units and predicts on about units, so the total is about fits; with a learner that costs on units, the time is up to the change from to . The scores need space. The fold assignment is a random permutation, . In practice the learners dominate, and repeated splits multiply the cost by their number.
Properties
- Product rate. The bias is a product of the two nuisance errors. If each error is , which lasso, forests and boosting can reach under sparsity or smoothness conditions, the product is , and the bias is negligible next to the standard error.
- Efficient. With the AIPW score, the limiting variance is , Hahn's (1998) efficiency bound.
- Doubly robust. The ATE score inherits the double robustness of AIPW: the conditional bias is 0 if either the propensity or the outcome learner is exactly right.
- No Donsker condition. Cross-fitting replaces the empirical-process conditions that a learner fitted on the same data would need. That is why the learners can be as complex as forests or neural networks.
- Randomness from the split. Two runs with different folds give slightly different estimates; in the simulation, the cross-fitted and the full-sample estimates with 10-bin learners differed by 0.015 on average.
Variants and improvements
- Other orthogonal scores. The partially linear IV model, the ATT, the local average treatment effect, quantile effects and conditional effects on a few groups each have their own orthogonal score; the algorithm is the same.
- Post-double-selection. With lasso learners, Belloni, Chernozhukov and Hansen (2014) select the controls that predict and those that predict , then run OLS on the union. It is an early form of the orthogonal idea.
- Cross-validated TMLE. TMLE with cross-fitted initial fits reaches the same limit with a plug-in estimate.
- Choosing the learners. Use cross-validation within the training folds to tune each learner, or an ensemble. The learner for the propensity should be judged by its fit, not by the effect estimate.
When to use it
Use DML when there are many covariates, or the confounding is nonlinear, so that a parametric propensity or outcome model is likely wrong, and you want a valid confidence interval for one effect. It needs enough data to fit good learners on of the sample, and enough overlap that the propensity stays away from 0 and 1. With few covariates and a small sample, AIPW with simple parametric models is easier to check and often as good.
Pitfalls
- Learners too slow. The guarantee needs the product of the nuisance errors to shrink faster than . A learner that does not converge, such as an outcome model that ignores an important covariate and a propensity model that is also poor, leaves a bias that cross-fitting cannot remove.
- Weak overlap. Large weights inflate the variance of the ATE score, exactly as in IPW. Look at the distribution of the predicted propensities, and consider the ATT, trimming or the partially linear model.
- The partially linear estimate under heterogeneity. If the effect varies with , is a weighted average of the effects with weights , not the ATE.
- Reporting one split. Report the number of folds and splits, and the variation across splits.
- Bad controls. Flexible learners do not decide which variables to adjust for. A covariate affected by the treatment, or a collider, biases the estimate however good the learner is; see the backdoor criterion.
- Untested ignorability. DML is about estimation. It inherits the identifying assumptions of the score, which the data cannot check; follow with a sensitivity analysis.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/double-machine-learning/. The authors are listed in prov/AN6TYE.jsonl.
"""Double (debiased) machine learning with cross-fitting.
Two estimators are given:
* dml_ate: the average treatment effect with the AIPW (doubly robust) score
psi_i = m1(X_i) - m0(X_i) + T_i (Y_i - m1(X_i)) / e(X_i) - (1 - T_i)(Y_i - m0(X_i)) / (1 - e(X_i)),
where the nuisances e, m1, m0 for unit i are fitted on the folds that do not contain i.
* dml_plr: the coefficient theta of the partially linear model Y = theta T + g(X) + error,
with the residual-on-residual (Robinson) score (Y - l(X) - theta (T - m(X))) (T - m(X)),
l(X) = E[Y | X], m(X) = E[T | X].
A learner is a function learner(xs, ys) that returns a predictor x -> prediction.
With k = 1 there is no cross-fitting: the nuisances are fitted on the whole sample.
"""
import math
import random
from collections.abc import Callable, Sequence
from statistics import NormalDist
from typing import NamedTuple
Learner = Callable[[list, list], Callable]
class DMLResult(NamedTuple):
estimate: object # the point estimate
se: float # the standard error from the score variance
lower: float # lower end of the normal interval
upper: float # upper end of the normal interval
scores: list # the per-unit scores (for the ATE) or the per-unit products (for the PLR)
def make_folds(n: int, k: int, rng: random.Random | None) -> list[int]:
"""Fold label of each unit: a random permutation cut into k parts whose sizes differ by at most 1.
With k = 1 every unit is in fold 0."""
if not 1 <= k <= n:
raise ValueError("need 1 <= k <= n")
order = list(range(n))
if rng is not None:
rng.shuffle(order)
label = [0] * n
for pos, i in enumerate(order):
label[i] = pos * k // n
return label
def _train_test(label, fold, k):
"""With k = 1, train and test on everything (no cross-fitting)."""
if k == 1:
return range(len(label)), range(len(label))
return [i for i, f in enumerate(label) if f != fold], [i for i, f in enumerate(label) if f == fold]
def _interval(est, var, alpha):
se = math.sqrt(float(var))
z = NormalDist().inv_cdf(1 - alpha / 2)
return se, float(est) - z * se, float(est) + z * se
def dml_ate(x: Sequence, t: Sequence[int], y: Sequence, outcome_learner: Learner, propensity_learner: Learner, k: int = 5, rng: random.Random | None = None, trim: float = 0.0, alpha: float = 0.05) -> DMLResult:
"""Cross-fitted AIPW estimate of the ATE. The propensity predictions are clipped to [trim, 1 - trim].
Cost: k fits of each learner plus Theta(n)."""
n = len(t)
if not (n == len(x) == len(y)):
raise ValueError("x, t and y must have the same length")
label = make_folds(n, k, rng) # @line L1
psi = [None] * n
for fold in range(k): # @line L2
train, test = _train_test(label, fold, k)
tr1 = [i for i in train if t[i] == 1]
tr0 = [i for i in train if t[i] == 0]
if not tr1 or not tr0:
raise ValueError("a training set has no treated or no control units")
e_hat = propensity_learner([x[i] for i in train], [t[i] for i in train]) # @line L3
m1_hat = outcome_learner([x[i] for i in tr1], [y[i] for i in tr1]) # @line L4
m0_hat = outcome_learner([x[i] for i in tr0], [y[i] for i in tr0])
for i in test: # @line L5
e = e_hat(x[i])
if trim:
e = min(max(e, trim), 1 - trim)
if not 0 < e < 1:
raise ValueError("positivity fails: a predicted propensity is 0 or 1")
a, b = m1_hat(x[i]), m0_hat(x[i])
psi[i] = a - b + ((y[i] - a) / e if t[i] == 1 else -(y[i] - b) / (1 - e)) # @line L6
est = sum(psi) / n # @line L7
var = sum((p - est) ** 2 for p in psi) / (n - 1) / n
se, lo, hi = _interval(est, var, alpha)
return DMLResult(est, se, lo, hi, psi) # @line L8
def dml_plr(x: Sequence, t: Sequence, y: Sequence, learner: Learner, k: int = 5, rng: random.Random | None = None, treatment_learner: Learner | None = None, alpha: float = 0.05) -> DMLResult:
"""Cross-fitted partially linear model: theta = sum (T - m)(Y - l) / sum (T - m)^2.
The standard error is the sandwich sqrt(mean(psi^2) / n) / mean((T - m)^2)."""
n = len(t)
if not (n == len(x) == len(y)):
raise ValueError("x, t and y must have the same length")
tl = treatment_learner or learner
label = make_folds(n, k, rng)
rt = [None] * n
ry = [None] * n
for fold in range(k):
train, test = _train_test(label, fold, k)
l_hat = learner([x[i] for i in train], [y[i] for i in train])
m_hat = tl([x[i] for i in train], [t[i] for i in train])
for i in test:
ry[i] = y[i] - l_hat(x[i])
rt[i] = t[i] - m_hat(x[i])
j = sum(v * v for v in rt)
if j == 0:
raise ValueError("the treatment residuals are all 0: T is a function of X in the fit")
theta = sum(a * b for a, b in zip(rt, ry)) / j
psi = [(b - theta * a) * a for a, b in zip(rt, ry)]
var = (sum(p * p for p in psi) / n) / ((j / n) ** 2) / n
se, lo, hi = _interval(theta, var, alpha)
return DMLResult(theta, se, lo, hi, psi)
# ----------------------------------------------------------------- learners
def solve(a: list[list], b: list) -> list:
"""Solve a x = b by Gaussian elimination with partial pivoting (exact for Fractions)."""
k = len(b)
m = [list(row) + [bi] for row, bi in zip(a, b)]
for c in range(k):
p = max(range(c, k), key=lambda r: abs(m[r][c]))
if m[p][c] == 0:
raise ValueError("singular system")
m[c], m[p] = m[p], m[c]
for r in range(c + 1, k):
f = m[r][c] / m[c][c]
if f != 0:
for jj in range(c, k + 1):
m[r][jj] -= f * m[c][jj]
out = [0] * k
for c in range(k - 1, -1, -1):
out[c] = (m[c][k] - sum(m[c][jj] * out[jj] for jj in range(c + 1, k))) / m[c][c]
return out
def linear_learner(features: Callable) -> Learner:
"""Least squares on features(x), by the normal equations."""
def fit(xs, ys):
rows = [features(v) for v in xs]
p = len(rows[0])
xtx = [[sum(r[a] * r[b] for r in rows) for b in range(p)] for a in range(p)]
xty = [sum(r[a] * yi for r, yi in zip(rows, ys)) for a in range(p)]
coef = solve(xtx, xty)
return lambda v: sum(c * f for c, f in zip(coef, features(v)))
return fit
def binned_learner(n_bins: int, lo: float = 0.0, hi: float = 1.0) -> Learner:
"""Regressogram: the mean of y in each of n_bins equal bins of [lo, hi]; the overall mean in an empty bin."""
def fit(xs, ys):
s = [0.0] * n_bins
c = [0] * n_bins
for v, yi in zip(xs, ys):
b = min(n_bins - 1, max(0, int((v - lo) / (hi - lo) * n_bins)))
s[b] += yi
c[b] += 1
overall = sum(ys) / len(ys)
means = [s[b] / c[b] if c[b] else overall for b in range(n_bins)]
return lambda v: means[min(n_bins - 1, max(0, int((v - lo) / (hi - lo) * n_bins)))]
return fit
def oracle_learner(f: Callable) -> Learner:
"""Ignores the training data and returns f; used to check the estimator against AIPW."""
return lambda xs, ys: f
test_double_machine_learning.py 182 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/double-machine-learning/. The authors are listed in prov/AN6TYE.jsonl.
import math
import random
import statistics
from fractions import Fraction as Fr
import pytest
from double_machine_learning import (
binned_learner,
dml_ate,
dml_plr,
linear_learner,
make_folds,
oracle_learner,
solve,
)
def aipw(x, t, y, e, m1, m0):
n = len(t)
return sum(m1(v) - m0(v) + (yi - m1(v)) / e(v) if ti == 1 else m1(v) - m0(v) - (yi - m0(v)) / (1 - e(v)) for v, ti, yi in zip(x, t, y)) / n
def test_oracle_learners_give_aipw_exactly():
rng = random.Random(1)
for _ in range(50):
n = rng.randint(6, 15)
x = [Fr(rng.randint(0, 9), 9) for _ in range(n)]
t = [i % 2 for i in range(n)] # at least 3 units per arm, so no training set lacks an arm
y = [Fr(rng.randint(-9, 9)) for _ in range(n)]
e = lambda v: Fr(1, 5) + Fr(3, 5) * v
m1 = lambda v: 2 + 3 * v
m0 = lambda v: v * v
target = aipw(x, t, y, e, m1, m0)
for k in (1, 2, 3):
# oracle learners ignore their training data, so the folds do not matter
assert dml_ate_oracle(x, t, y, e, m1, m0, k).estimate == target
def dml_ate_oracle(x, t, y, e, m1, m0, k):
"""Outcome learner that returns m1 on treated training data and m0 on control data (told apart by a tag)."""
tagged_x = [(v, ti) for v, ti in zip(x, t)]
def outcome(xs, ys):
arm = xs[0][1]
f = m1 if arm == 1 else m0
return lambda p: f(p[0])
def prop(xs, ts):
return lambda p: e(p[0])
return dml_ate(tagged_x, t, y, outcome, prop, k=k, rng=random.Random(k))
def test_plr_without_cross_fitting_is_ols_exactly():
"""With k = 1 and linear learners on the same features, the residual-on-residual coefficient is the
OLS coefficient of T in the regression of Y on (T, features) (Frisch-Waugh-Lovell)."""
rng = random.Random(2)
feats = lambda v: [Fr(1), v, v * v]
for _ in range(40):
n = rng.randint(6, 14)
x = [Fr(rng.randint(-5, 5), 3) for _ in range(n)]
t = [Fr(rng.randint(-4, 4)) for _ in range(n)]
y = [Fr(rng.randint(-9, 9)) for _ in range(n)]
rows = [[ti] + feats(v) for ti, v in zip(t, x)]
p = len(rows[0])
xtx = [[sum(r[a] * r[b] for r in rows) for b in range(p)] for a in range(p)]
xty = [sum(r[a] * yi for r, yi in zip(rows, y)) for a in range(p)]
try:
ols = solve(xtx, xty)[0]
except ValueError:
continue
r = dml_plr(x, t, y, linear_learner(feats), k=1)
assert r.estimate == ols
def test_folds_are_balanced():
for n in (5, 10, 37):
for k in (1, 2, 3, 5):
lab = make_folds(n, k, random.Random(n * k))
sizes = [lab.count(f) for f in range(k)]
assert sum(sizes) == n and max(sizes) - min(sizes) <= 1
with pytest.raises(ValueError):
make_folds(3, 4, None)
def test_cross_fitting_keeps_own_outcome_out_of_nuisances():
"""Raising y_i by 1 changes psi_i by exactly 1/e_i (treated) and no other unit of its fold."""
rng = random.Random(3)
n = 30
x = [Fr(rng.randint(0, 20), 20) for _ in range(n)]
t = [i % 2 for i in range(n)]
y = [Fr(rng.randint(-9, 9)) for _ in range(n)]
lin = linear_learner(lambda v: [Fr(1), v])
prop = oracle_learner(lambda v: Fr(1, 4) + v / 2)
base = dml_ate(x, t, y, lin, prop, k=3, rng=random.Random(7))
lab = make_folds(n, 3, random.Random(7))
i = 1 # a treated unit
y2 = list(y)
y2[i] += 1
new = dml_ate(x, t, y2, lin, prop, k=3, rng=random.Random(7))
assert new.scores[i] - base.scores[i] == 1 / (Fr(1, 4) + x[i] / 2)
for j in range(n):
if j != i and lab[j] == lab[i]:
assert new.scores[j] == base.scores[j]
# without cross-fitting the fitted outcome model moves, so other scores change too
a = dml_ate(x, t, y, lin, prop, k=1)
b = dml_ate(x, t, y2, lin, prop, k=1)
assert any(a.scores[j] != b.scores[j] for j in range(n) if j != i)
def expit(z):
return 1 / (1 + math.exp(-z))
def sim_ate(n, rng):
x, t, y = [], [], []
for _ in range(n):
xi = rng.random()
ti = 1 if rng.random() < expit(-2 + 4 * xi) else 0
x.append(xi), t.append(ti), y.append(xi + 2 * xi * xi + ti * (1 + xi) + rng.gauss(0, 1))
return x, t, y
def test_debiasing_with_a_coarse_outcome_learner():
"""r = 40 samples, n = 1000 (seed 2026), true ATE 1.5. Outcome learner: 2 bins (badly biased);
propensity learner: 10 bins. The plug-in regression is off by more than 0.15 on average;
DML is within 4 SE + 0.03 of 1.5."""
rng = random.Random(2026)
dml, plug = [], []
r = 40
for _ in range(r):
x, t, y = sim_ate(1000, rng)
res = dml_ate(x, t, y, binned_learner(2), binned_learner(10), k=5, rng=random.Random(1))
dml.append(res.estimate)
m1 = binned_learner(2)([v for v, ti in zip(x, t) if ti], [yi for yi, ti in zip(y, t) if ti])
m0 = binned_learner(2)([v for v, ti in zip(x, t) if not ti], [yi for yi, ti in zip(y, t) if not ti])
plug.append(sum(m1(v) - m0(v) for v in x) / len(x))
assert abs(statistics.mean(dml) - 1.5) < 4 * statistics.stdev(dml) / math.sqrt(r) + 0.03
assert statistics.mean(plug) - 1.5 > 0.15
def test_cross_fitted_close_to_full_sample_aipw():
"""Stated tolerance: over 20 samples of n = 1000 (seed 5), the mean absolute difference between
the cross-fitted (k = 5) and the full-sample (k = 1) estimates with 10-bin learners is below 0.03."""
rng = random.Random(5)
diffs = []
for _ in range(20):
x, t, y = sim_ate(1000, rng)
cf = dml_ate(x, t, y, binned_learner(10), binned_learner(10), k=5, rng=random.Random(1))
full = dml_ate(x, t, y, binned_learner(10), binned_learner(10), k=1)
diffs.append(abs(cf.estimate - full.estimate))
assert statistics.mean(diffs) < 0.03
def test_partially_linear_model():
"""Y = 0.5 T + 2 cos(2 pi X) + noise, T = cos(2 pi X) + noise. Linear-in-x OLS is biased (about 1.17);
DML with 20-bin learners is within 4 SE + 0.03 of 0.5 over r = 30 samples of n = 1000 (seed 9)."""
rng = random.Random(9)
est, ols = [], []
for _ in range(30):
x, t, y = [], [], []
for _ in range(1000):
xi = rng.random()
ti = math.cos(2 * math.pi * xi) + rng.gauss(0, 1)
x.append(xi), t.append(ti), y.append(0.5 * ti + 2 * math.cos(2 * math.pi * xi) + rng.gauss(0, 1))
est.append(dml_plr(x, t, y, binned_learner(20), k=5, rng=random.Random(1)).estimate)
ols.append(dml_plr(x, t, y, linear_learner(lambda v: [1.0, v]), k=1).estimate)
assert abs(statistics.mean(est) - 0.5) < 4 * statistics.stdev(est) / math.sqrt(30) + 0.03
assert statistics.mean(ols) > 1.0
def test_input_checks():
with pytest.raises(ValueError):
dml_ate([0.1, 0.2], [1, 1], [1.0, 2.0], binned_learner(2), binned_learner(2), k=1)
with pytest.raises(ValueError):
xs = [Fr(1, 10), Fr(2, 10), Fr(3, 10)]
ts = [Fr(1), Fr(2), Fr(3)] # T is an exact linear function of X: no treatment residual is left
dml_plr(xs, ts, [Fr(1), Fr(5), Fr(2)], oracle_learner(lambda v: v), k=1, treatment_learner=linear_learner(lambda v: [Fr(1), v]))
History
Robinson (1988) showed that the coefficient of the partially linear model can be estimated at the rate by regressing the residual of on the residual of , both from nonparametric regressions on . Robins, Rotnitzky and Zhao (1994) and the later semiparametric work built the augmented scores that are orthogonal in the same sense, and Neyman's earlier tests had used scores that are insensitive to nuisance parameters. Belloni, Chernozhukov and Hansen (2014) gave valid inference after lasso selection of many controls. Chernozhukov, Chetverikov, Demirer, Duflo, Hansen, Newey and Robins (2018) combined orthogonal scores with cross-fitting into a general recipe that works with any learner that converges fast enough, and named it double or debiased machine learning.
References
- Victor Chernozhukov, Denis Chetverikov, Mert Demirer, Esther Duflo, Christian Hansen, Whitney Newey and James Robins, Double/debiased machine learning for treatment and structural parameters, The Econometrics Journal 21(1), 2018, pp. C1 to C68 (Neyman orthogonal scores, cross-fitting, the DML1 and DML2 estimators, the partially linear model and the ATE)
- P. M. Robinson, Root-N-consistent semiparametric regression, Econometrica 56(4), 1988, pp. 931 to 954 (the coefficient of the partially linear model from residuals of Y and T on X)
- Alexandre Belloni, Victor Chernozhukov and Christian Hansen, Inference on treatment effects after selection among high-dimensional controls, The Review of Economic Studies 81(2), 2014, pp. 608 to 650 (post-double-selection with the lasso, a forerunner of the orthogonal approach)
- James M. Robins, Andrea Rotnitzky and Lue Ping Zhao, Estimation of regression coefficients when some regressors are not always observed, Journal of the American Statistical Association 89(427), 1994, pp. 846 to 866 (the augmented estimating function used as the ATE score)
- Jinyong Hahn, On the role of the propensity score in efficient semiparametric estimation of average treatment effects, Econometrica 66(2), 1998, pp. 315 to 331 (the efficiency bound reached by the ATE score)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag AN6TYE Edit this page History Report an error Markdown