Algorithm Search⌘K

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
Properties
cross fitteddeterministic given foldsdoubly robust ate scoreneeds positivityneyman orthogonal score
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 n\sqrt n-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 Y(1),Y(0)Y(1), Y(0), treatment T∈{0,1}T \in \{0, 1\}, covariates XX, and the estimand τ=E[Y(1)−Y(0)]\tau = \mathbb{E}[Y(1) - Y(0)]. Under consistency with SUTVA, ignorability and positivity, τ=E[ψ(W;η0)]\tau = \mathbb{E}[\psi(W; \eta_0)] with the AIPW score

ψ(W;η)=m1(X)−m0(X)+T(Y−m1(X))e(X)−(1−T)(Y−m0(X))1−e(X),\psi(W; \eta) = m_1(X) - m_0(X) + \frac{T(Y - m_1(X))}{e(X)} - \frac{(1 - T)(Y - m_0(X))}{1 - e(X)},

evaluated at the true nuisances η0=(e,μ1,μ0)\eta_0 = (e, \mu_1, \mu_0), as on the AIPW page. For the partially linear model Y=θT+g(X)+UY = \theta T + g(X) + U with E[U∣X,T]=0\mathbb{E}[U \mid X, T] = 0 and a continuous or binary TT, the parameter is θ\theta. It is causal if, in addition, TT is as good as random given XX and the effect of TT is the same constant θ\theta for everyone; it is identified by θ=E[(T−m(X))(Y−l(X))]/E[(T−m(X))2]\theta = \mathbb{E}[(T - m(X))(Y - l(X))]/\mathbb{E}[(T - m(X))^2] with m(X)=E[T∣X]m(X) = \mathbb{E}[T \mid X], l(X)=E[Y∣X]l(X) = \mathbb{E}[Y \mid X], if TT is not a function of XX. Ignorability, SUTVA and the constant effect cannot be checked from the observed data.

Estimation. The input is nn units (Xi,Ti,Yi)(X_i, T_i, Y_i), a number of folds kk (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

  1. DML-ATE(X, T, Y, k, learn_e, learn_m)
  2. 1give each unit a fold label in {0, ..., k - 1}: a random permutation cut into k near-equal parts
  3. 2for f ← 0 to k - 1 do
  4. 3ê ← learn_e(units not in fold f) ▷ predicts T from X
  5. 4m̂1 ← learn_m(treated units not in fold f); m̂0 ← learn_m(control units not in fold f)
  6. 5for each unit i in fold f do
  7. 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))
  8. 7τ̂ ← (1/n) Σ_i ψ_i
  9. 8return τ̂ and v = Σ_i (ψ_i - τ̂)² / (n (n - 1))

Lines L3 and L4 never see the units of fold ff, 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 kk fold estimates instead (DML1) gives the same answer here when the folds have equal sizes, because the score is linear in τ\tau. The interval is τ^±z1−α/2v\hat\tau \pm z_{1 - \alpha/2}\sqrt v. Predicted propensities can be clipped to [β,1−β][\beta, 1 - \beta] for a small β\beta; the clip changes the estimand slightly and should be reported.

Partially linear model. The same loop fits l^\hat l (a regression of YY on XX) and m^\hat m (of TT on XX) on the other folds, forms the residuals Y~i=Yi−l^(Xi)\tilde Y_i = Y_i - \hat l(X_i) and T~i=Ti−m^(Xi)\tilde T_i = T_i - \hat m(X_i), and returns the residual-on-residual coefficient θ^=∑iT~iY~i/∑iT~i2\hat\theta = \sum_i\tilde T_i\tilde Y_i/\sum_i\tilde T_i^2 (Robinson 1988). Its sandwich variance is 1n⋅1n∑iψ^i2(1n∑iT~i2)2\frac1n\cdot\frac{\frac1n\sum_i\hat\psi_i^2}{(\frac1n\sum_i\tilde T_i^2)^2} with ψ^i=(Y~i−θ^T~i)T~i\hat\psi_i = (\tilde Y_i - \hat\theta\tilde T_i)\tilde T_i.

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 k=1k = 1 (no cross-fitting) and least squares on the same features for both nuisances, the partially linear estimate is exactly the coefficient of TT in the least squares regression of YY on TT and those features. Take four units with X=(0,1,2,3)X = (0, 1, 2, 3), T=(0,1,1,3)T = (0, 1, 1, 3) and Y=(1,2,4,7)Y = (1, 2, 4, 7), and the features (1,x)(1, x). The regression of TT on (1,x)(1, x) has intercept −0.1-0.1 and slope 0.90.9, with fitted values (−0.1,0.8,1.7,2.6)(-0.1, 0.8, 1.7, 2.6), so T~=(0.1,0.2,−0.7,0.4)\tilde T = (0.1, 0.2, -0.7, 0.4). The regression of YY on (1,x)(1, x) has intercept 0.50.5 and slope 2, with fitted values (0.5,2.5,4.5,6.5)(0.5, 2.5, 4.5, 6.5), so Y~=(0.5,−0.5,−0.5,0.5)\tilde Y = (0.5, -0.5, -0.5, 0.5). Then θ^=(0.05−0.1+0.35+0.2)/(0.01+0.04+0.49+0.16)=0.5/0.7=5/7\hat\theta = (0.05 - 0.1 + 0.35 + 0.2)/(0.01 + 0.04 + 0.49 + 0.16) = 0.5/0.7 = 5/7. The regression of YY on (1,x,T)(1, x, T) gives Y=47+1914x+57TY = \tfrac47 + \tfrac{19}{14}x + \tfrac57T, with the same coefficient 5/75/7 on TT. 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 XX uniform on [0,1][0, 1], e(x)=expit⁡(−2+4x)e(x) = \operatorname{expit}(-2 + 4x) and Y=x+2x2+T(1+x)+εY = x + 2x^2 + T(1 + x) + \varepsilon with standard normal ε\varepsilon, so the true ATE is 1.5. The learners are regressograms: the mean in each of bb equal bins of [0,1][0, 1]. With n=1000n = 1000, k=5k = 5 and 300 samples (seed 2026):

outcome learner propensity learner estimator mean SD 95% coverage
2 bins 10 bins plug-in regression 1n∑(m^1−m^0)\frac1n\sum(\hat m_1 - \hat m_0) 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 T=cos⁡(2πX)+VT = \cos(2\pi X) + V and Y=0.5T+2cos⁡(2πX)+UY = 0.5T + 2\cos(2\pi X) + U, the regression of YY on (1,X,T)(1, X, T) 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 τ\tau by the exact AIPW bias formula, which, when the fitted propensity stays in [c,1−c][c, 1 - c], is bounded by 1c∥e−e^∥(∥μ1−m^1∥+∥μ0−m^0∥)\frac1c\|e - \hat e\|(\|\mu_1 - \hat m_1\| + \|\mu_0 - \hat m_0\|): 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 n(τ^−τ)\sqrt n(\hat\tau - \tau) under overlap (the true and fitted propensities stay in [c,1−c][c, 1 - c]), consistency of each nuisance learner, and the rate condition ∥e−e^∥⋅∥μt−m^t∥=oP(n−1/2)\|e - \hat e\|\cdot\|\mu_t - \hat m_t\| = o_P(n^{-1/2}), 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 Wi=(Xi,Ti,Yi)W_i = (X_i, T_i, Y_i), i=1,…,ni = 1, \ldots, n, are independent copies of W=(X,T,Y)W = (X, T, Y). For the ATE, assume consistency with SUTVA, ignorability and positivity as on the AIPW page, and write e(x)=Pr⁡[T=1∣X=x]e(x) = \Pr[T = 1 \mid X = x] and μt(x)=E[Y∣T=t,X=x]\mu_t(x) = \mathbb{E}[Y \mid T = t, X = x]. For working functions η=(e~,m1,m0)\eta = (\tilde e, m_1, m_0) the AIPW score is

ψ(W;η)=m1(X)−m0(X)+T(Y−m1(X))e~(X)−(1−T)(Y−m0(X))1−e~(X).\psi(W; \eta) = m_1(X) - m_0(X) + \frac{T(Y - m_1(X))}{\tilde e(X)} - \frac{(1 - T)(Y - m_0(X))}{1 - \tilde e(X)}.

Lemma 1 (folds). MAKE-FOLDS gives every unit one label in {0,…,k−1}\{0, \ldots, k - 1\}, and the fold sizes differ by at most 1.

Proof. The unit at position pp of the permutation, 0≤p<n0 \le p < n, gets label ⌊pk/n⌋\lfloor pk/n\rfloor, which is in {0,…,k−1}\{0, \ldots, k - 1\}. Label ff goes to the positions pp with fn/k≤p<(f+1)n/kfn/k \le p < (f + 1)n/k, which number ⌈(f+1)n/k⌉−⌈fn/k⌉\lceil (f + 1)n/k\rceil - \lceil fn/k\rceil. This is ⌊n/k⌋\lfloor n/k\rfloor or ⌈n/k⌉\lceil n/k\rceil, since ⌈a+n/k⌉−⌈a⌉\lceil a + n/k\rceil - \lceil a\rceil is one of these two for every real aa. □\square

Lemma 2 (the loop). DML-ATE returns τ^=1n∑iψ(Wi;η^(−f(i)))\hat\tau = \frac1n\sum_i \psi(W_i; \hat\eta^{(-f(i))}), where f(i)f(i) is the fold of unit ii and η^(−f)\hat\eta^{(-f)} is fitted on the units outside fold ff. If the learners ignore their training data and return fixed functions η\eta, then τ^\hat\tau is the AIPW estimate with η\eta, for every kk 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 ψi\psi_i once, with the nuisances of line L3 and L4 fitted on the other folds. Line L7 averages. If the learners return fixed η\eta, every η^(−f)=η\hat\eta^{(-f)} = \eta. □\square

Exact bias with cross-fitting

Theorem 3. Let D−fD_{-f} be the units outside fold ff, and suppose the fitted propensity satisfies e^(−f)(x)∈[c,1−c]\hat e^{(-f)}(x) \in [c, 1 - c]. For a unit ii in fold ff,

E[ψ(Wi;η^(−f)) ∣ D−f]−τ=EX[(ee^−1)(μ1−m^1)−(1−e1−e^−1)(μ0−m^0)],\mathbb{E}\big[\psi(W_i; \hat\eta^{(-f)}) \,\big|\, D_{-f}\big] - \tau = \mathbb{E}_X\left[\Big(\frac{e}{\hat e} - 1\Big)(\mu_1 - \hat m_1) - \Big(\frac{1 - e}{1 - \hat e} - 1\Big)(\mu_0 - \hat m_0)\right],

with e^,m^t\hat e, \hat m_t the functions fitted on D−fD_{-f} and EX\mathbb{E}_X the expectation over a new XX. Hence

∣E[ψ(Wi;η^(−f))∣D−f]−τ∣≤1c ∥e−e^∥ (∥μ1−m^1∥+∥μ0−m^0∥),\big|\mathbb{E}[\psi(W_i; \hat\eta^{(-f)}) \mid D_{-f}] - \tau\big| \le \frac1c\,\|e - \hat e\|\,\big(\|\mu_1 - \hat m_1\| + \|\mu_0 - \hat m_0\|\big),

where ∥g∥=(EX[g(X)2])1/2\|g\| = (\mathbb{E}_X[g(X)^2])^{1/2}.

Proof. The units are independent, so WiW_i is independent of D−fD_{-f}, and given D−fD_{-f} the functions η^(−f)\hat\eta^{(-f)} are fixed. The bias identity of the AIPW page (Theorem 2 there) holds for any fixed working functions, so it applies to η^(−f)\hat\eta^{(-f)} conditionally on D−fD_{-f}. The bound follows by the Cauchy-Schwarz inequality, as in Corollary 4 there. □\square

Without cross-fitting (k=1k = 1), η^\hat\eta depends on WiW_i itself, the conditioning step fails, and E[ψ(Wi;η^)]\mathbb{E}[\psi(W_i; \hat\eta)] has no such form; an overfitted learner can then make the residuals Yi−m^Ti(Xi)Y_i - \hat m_{T_i}(X_i) small for the units it was fitted on. The tests check the key fact behind Theorem 3: with cross-fitting, raising YiY_i by 1 changes ψi\psi_i by exactly 1/e^i1/\hat e_i (or −1/(1−e^i)-1/(1 - \hat e_i)) and leaves the other scores of its fold unchanged, while with k=1k = 1 other scores change too.

Neyman orthogonality

Theorem 4 (ATE score). Let η0=(e,μ1,μ0)\eta_0 = (e, \mu_1, \mu_0), and for bounded directions h=(he,h1,h0)h = (h_e, h_1, h_0) let ηr=η0+rh\eta_r = \eta_0 + rh. Then ddrE[ψ(W;ηr)]∣r=0=0\frac{d}{dr}\mathbb{E}[\psi(W; \eta_r)]\big|_{r = 0} = 0.

Proof. By the bias identity with e~=e+rhe\tilde e = e + rh_e and mt=μt+rhtm_t = \mu_t + rh_t,

E[ψ(W;ηr)]−τ=E[−rhee+rhe(−rh1)−rhe1−e−rhe(−rh0)]=r2 E[heh1e+rhe+heh01−e−rhe].\mathbb{E}[\psi(W; \eta_r)] - \tau = \mathbb{E}\left[\frac{-rh_e}{e + rh_e}(-rh_1) - \frac{rh_e}{1 - e - rh_e}(-rh_0)\right] = r^2\,\mathbb{E}\left[\frac{h_eh_1}{e + rh_e} + \frac{h_eh_0}{1 - e - rh_e}\right].

For ∣r∣|r| small, e+rhee + rh_e and 1−e−rhe1 - e - rh_e stay above c/2c/2 if e∈[c,1−c]e \in [c, 1 - c], so the expectation is bounded, and the whole is O(r2)O(r^2). Its derivative at r=0r = 0 is 0. □\square

Theorem 5 (partially linear score). In the model Y=θ0T+g(X)+UY = \theta_0 T + g(X) + U with E[U∣X,T]=0\mathbb{E}[U \mid X, T] = 0, let m(X)=E[T∣X]m(X) = \mathbb{E}[T \mid X], l(X)=E[Y∣X]l(X) = \mathbb{E}[Y \mid X], and ψ(W;θ,l,m)=(Y−l(X)−θ(T−m(X)))(T−m(X))\psi(W; \theta, l, m) = (Y - l(X) - \theta(T - m(X)))(T - m(X)). Then E[ψ(W;θ0,l,m)]=0\mathbb{E}[\psi(W; \theta_0, l, m)] = 0, and the derivative of E[ψ(W;θ0,l+rhl,m+rhm)]\mathbb{E}[\psi(W; \theta_0, l + rh_l, m + rh_m)] at r=0r = 0 is 0. If E[(T−m(X))2]>0\mathbb{E}[(T - m(X))^2] > 0, then θ0=E[(T−m)(Y−l)]/E[(T−m)2]\theta_0 = \mathbb{E}[(T - m)(Y - l)]/\mathbb{E}[(T - m)^2].

Proof. l(X)=θ0m(X)+g(X)l(X) = \theta_0 m(X) + g(X), so Y−l(X)−θ0(T−m(X))=UY - l(X) - \theta_0(T - m(X)) = U. Write V=T−m(X)V = T - m(X), which has E[V∣X]=0\mathbb{E}[V \mid X] = 0. Then E[UV]=E[V E[U∣X,T]]=0\mathbb{E}[UV] = \mathbb{E}[V\,\mathbb{E}[U \mid X, T]] = 0. With the perturbed functions, the score is (U−rhl+θ0rhm)(V−rhm)(U - rh_l + \theta_0 rh_m)(V - rh_m), whose mean is

E[UV]−r E[Uhm]−r E[(hl−θ0hm)V]+r2 E[(hl−θ0hm)hm].\mathbb{E}[UV] - r\,\mathbb{E}[Uh_m] - r\,\mathbb{E}[(h_l - \theta_0h_m)V] + r^2\,\mathbb{E}[(h_l - \theta_0h_m)h_m].

E[Uhm(X)]=0\mathbb{E}[Uh_m(X)] = 0 because E[U∣X]=0\mathbb{E}[U \mid X] = 0, and E[(hl−θ0hm)(X)V]=0\mathbb{E}[(h_l - \theta_0h_m)(X)V] = 0 because E[V∣X]=0\mathbb{E}[V \mid X] = 0. So the mean is r2r^2 times a constant, with derivative 0 at r=0r = 0. The last claim: E[V(Y−l)]=E[V(θ0V+U)]=θ0E[V2]\mathbb{E}[V(Y - l)] = \mathbb{E}[V(\theta_0V + U)] = \theta_0\mathbb{E}[V^2]. □\square

Theorem 6 (no cross-fitting, linear learners). If k=1k = 1 and both learners are least squares on the same feature vector F(x)F(x), and the regression of YY on (T,F(X))(T, F(X)) has a unique solution, then θ^\hat\theta equals the OLS coefficient of TT in that regression.

Proof. This is the Frisch-Waugh-Lovell theorem. Let F\mathbf F be the n×qn \times q feature matrix, PP the projection on its columns and M=I−PM = I - P. The fitted learners give the residuals T~=MT\tilde T = M\mathbf T and Y~=MY\tilde Y = M\mathbf Y, so θ^=T~⊤Y~/T~⊤T~\hat\theta = \tilde T^\top\tilde Y/\tilde T^\top\tilde T. The OLS fit is Y=bT+Fγ+u\mathbf Y = b\mathbf T + \mathbf F\gamma + \mathbf u with F⊤u=0\mathbf F^\top\mathbf u = 0 and T⊤u=0\mathbf T^\top\mathbf u = 0. Then Pu=0P\mathbf u = 0, and MY=bMT+MFγ+Mu=bT~+uM\mathbf Y = bM\mathbf T + M\mathbf F\gamma + M\mathbf u = b\tilde T + \mathbf u. So T~⊤Y~=b T~⊤T~+T⊤Mu=b T~⊤T~+T⊤u=b T~⊤T~\tilde T^\top\tilde Y = b\,\tilde T^\top\tilde T + \mathbf T^\top M\mathbf u = b\,\tilde T^\top\tilde T + \mathbf T^\top\mathbf u = b\,\tilde T^\top\tilde T. Uniqueness of the OLS solution means T\mathbf T is not in the column span of F\mathbf F, so T~⊤T~>0\tilde T^\top\tilde T > 0, and θ^=b\hat\theta = b. □\square

What is not proved here

The asymptotic normality n(τ^−τ)→N(0,V)\sqrt n(\hat\tau - \tau) \to N(0, V) with V=E[(ψ(W;η0)−τ)2]V = \mathbb{E}[(\psi(W; \eta_0) - \tau)^2], under the conditions that the propensity stays in [c,1−c][c, 1 - c], that each nuisance error tends to 0, and that the product of the propensity error and the outcome error is o(n−1/2)o(n^{-1/2}), and the same result for θ^\hat\theta 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 kk folds fits three learners (one for the propensity and one per arm) on about n(k−1)/kn(k - 1)/k units and predicts on about n/kn/k units, so the total is about 3k3k fits; with a learner that costs C(m)C(m) on mm units, the time is Θ(n)+3k C(n)\Theta(n) + 3k\,C(n) up to the change from nn to n(k−1)/kn(k - 1)/k. The scores need Θ(n)\Theta(n) space. The fold assignment is a random permutation, Θ(n)\Theta(n). 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 o(n−1/4)o(n^{-1/4}), which lasso, forests and boosting can reach under sparsity or smoothness conditions, the product is o(n−1/2)o(n^{-1/2}), and the bias is negligible next to the standard error.
  • Efficient. With the AIPW score, the limiting variance is E[(ψ(W;η0)−τ)2]\mathbb{E}[(\psi(W; \eta_0) - \tau)^2], 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 YY and those that predict TT, 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 (k−1)/k(k - 1)/k 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 1/n1/\sqrt n. 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 1/e^1/\hat e 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 XX, θ\theta is a weighted average of the effects with weights Var⁡[T∣X]\operatorname{Var}[T \mid X], 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.

double_machine_learning.pyI0RawGitHub
# 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 n\sqrt n rate by regressing the residual of YY on the residual of TT, both from nonparametric regressions on XX. 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 C(α)C(\alpha) 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

  1. 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)
  2. 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)
  3. 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)
  4. 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)
  5. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example