Algorithmresearch
Targeted maximum likelihood estimation
Also called TMLE, targeted minimum loss-based estimation.
Van der Laan's estimator that fits an initial outcome model and then updates it along the efficient influence function, giving a doubly robust plug-in estimate.
- Time
- Θ(k n) worstΘ(n) best
- Space
- Θ(n) extra
- Where
- k = the number of Newton-Raphson steps for the fluctuation; n = the number of units
- Model
- Real RAM
- Properties
- deterministicdoubly robustneeds positivityplug insolves efficient score equationstays in outcome range
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Mark J. van der Laan, Daniel Rubin, 2006
Targeted maximum likelihood estimation (TMLE) estimates the average treatment effect as a plug-in: it predicts and for every unit with an outcome model and averages the difference. Before averaging, it moves the outcome model by one fitted number in the direction of the clever covariate , which is built from the propensity score. After this update the residuals, weighted by , add up to zero, so the plug-in estimate equals the AIPW estimate at the updated model. It is therefore doubly robust in the same way as AIPW, and with a logistic update it keeps the estimate inside the range of the outcome, which AIPW does not.
In plain words
Start with a model that predicts each person's outcome with and without treatment, and average the predicted differences. If the model is wrong, the answer is biased. AIPW fixes this by adding weighted prediction errors to the answer, but that addition can push the answer to impossible values, such as a probability above one.
TMLE puts the fix into the model instead of into the answer. It nudges every prediction by a small amount, more for people with a low chance of the treatment they got, and picks the size of the nudge so that the weighted prediction errors cancel out. Then it averages the nudged predictions. The answer has the same protection as AIPW, but since it is an average of predictions, it always makes sense.
The problem
Identification. This is the same as for IPW and AIPW. The estimand is . Under consistency with SUTVA, ignorability and positivity , it is identified by the g-formula with . The efficient influence function of in the nonparametric model is
Ignorability and SUTVA cannot be checked from the observed data; positivity can be checked in part from the estimated propensities.
Estimation. The input is units with treatment , outcome in a known range , a propensity value , and initial predictions and of and strictly inside . The outcome and the predictions are scaled to by ; for a binary outcome no scaling is needed. The initial predictions can come from any learner: a logistic regression in each arm, or an ensemble chosen by cross-validation (the super learner of van der Laan and Rose). The output is the estimate , its parts and , the fitted , and a standard error.
The algorithm
TMLE-ATE(T, Y, e, Q1, Q0) ▷ Y, Q1, Q0 scaled to [0, 1]; 0 < e_i < 1; 0 < Q < 1- 1
for i ← 1 to n do H_i ← T_i / e_i - (1 - T_i) / (1 - e_i); o_i ← logit Q_{T_i, i} - 2
ε ← 0 - 3
repeat - 4
U ← Σ_i H_i (Y_i - expit(o_i + ε H_i)); I ← Σ_i H_i² q_i (1 - q_i) ▷ q_i = expit(o_i + ε H_i) - 5
δ ← U / I; halve δ while the log-likelihood at ε + δ is below the one at ε - 6
ε ← ε + δ - 7
until |δ| < tol (1 + |ε|) - 8
for i ← 1 to n do Q1*_i ← expit(logit Q1_i + ε / e_i); Q0*_i ← expit(logit Q0_i - ε / (1 - e_i)) - 9
μ1 ← mean(Q1*); μ0 ← mean(Q0*); return (μ1 - μ0, μ1, μ0, ε)
Line L1 builds the clever covariate and the offset, the initial prediction for the arm each unit was in, on the logit scale. Lines L2 to L7 fit the one-parameter logistic regression of on with that offset and no intercept, by Newton-Raphson on its score , with step halving so that no step lowers the log-likelihood. The log-likelihood is strictly concave in , so the root of is the unique maximizer. The code uses and at most 100 steps. If separates the outcome (every unit with has and every unit with has , or the reverse), no maximizer exists and the code raises an error. Line L8 updates both predictions of every unit, not only the observed one, and line L9 averages them. Multiply by to return to the original scale.
Variance. The influence-function variance is
and is a normal confidence interval of approximate level when both working models are consistent. This is cited (van der Laan and Rose 2011), not proved here.
Linear fluctuation. For an unbounded outcome with squared loss, the update is , and with is one least squares step. It solves the score equation exactly but loses the range guarantee.
Example
Take the eight units of the IPW page with a binary outcome: for the five mild units and for the three severe ones. The design propensity is for and for , and the initial outcome model ignores : (the treated mean) and (the control mean).
| unit | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | |
| 1 | 1 | 0 | 0 | 0 | 1 | 1 | 0 | |
| 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | |
| 4 | 4 | |||||||
| residual | 1/2 | 1/2 | 1/4 | 1/4 | 1/4 |
The initial plug-in is , and AIPW at the initial model gives . The linear fluctuation is easy to follow by hand: and , so . The updated treated predictions are for and for ; the control predictions are and . Averaging over the five mild and three severe units, , and . AIPW evaluated at the updated predictions also gives , since the weighted residuals now add to zero.
The logistic fluctuation of lines L2 to L7 gives and , with and . The stratified estimate is 0, since all units in a stratum have the same outcome. The propensities are the true design values, so all three estimates are consistent, but eight units are far too few for them to agree: the answers , and differ by terms that shrink only in large samples. The example shows the arithmetic, not the accuracy.
Correctness
The proofs establish:
- the log-likelihood of the fluctuation is strictly concave in ; a maximizer exists unless separates the outcome, and it solves the score equation ;
- any predictions that solve this score equation make the plug-in estimate equal to the AIPW estimate at those predictions (exactly; the tests check it with fractions for the linear fluctuation and to for the logistic one);
- with the logistic fluctuation every updated prediction, and so the estimate, lies inside the range of the outcome;
- if the propensity is constant within each arm and the initial fits are logistic regressions with an intercept in each arm, the update is ;
- the population limit of the procedure equals if either the propensity or the initial outcome model is right.
The convergence of the estimate to that limit, its asymptotic normality and efficiency, and the coverage of the interval are cited from van der Laan and Rubin (2006) and van der Laan and Rose (2011), not proved. The simulation numbers are measured.
Proof: The targeted estimate is the AIPW estimate at the updated outcome model, and its limit is doubly robustfull
The outcome is scaled to . Unit has treatment , outcome , propensity value and initial predictions of the mean outcome under each treatment. The clever covariate is , and is the prediction for the arm the unit was in. For a number let
so that . The log-likelihood of the fluctuation is .
Lemma 1 (the fluctuation step). and . So is strictly concave, it has at most one maximizer, and a maximizer exists if and only if changes sign; then .
Proof. For , , and . With the chain rule gives the factor in and in . Every and , so . A strictly decreasing continuous has at most one zero, which is the maximizer, and it has one exactly when it takes both signs.
fails to change sign only when for all units with and for all with , or the reverse (the outcome is separated by ). Then the code raises an error. Lines L3 to L7 are Newton-Raphson for the root of with step halving; each accepted step does not lower , and on a strictly concave smooth function this converges to the maximizer. Lines L8 and L9 give and .
Theorem 2 (TMLE is AIPW at the targeted predictions). Let be any predictions that satisfy the score equation . Then
Proof. For each unit, : if both sides are , and if both are . So the AIPW estimate at is , and the last sum is 0.
By Lemma 1 the logistic fluctuation gives predictions that satisfy the score equation, so Theorem 2 applies to TMLE.
Theorem 3 (the linear fluctuation). With and , the least squares choice with satisfies the score equation exactly, so Theorem 2 holds in exact arithmetic.
Proof. , so .
Theorem 4 (range). With the logistic fluctuation, every is in , so and . On the original scale , .
Proof. maps the real line into , and an average of numbers in is in . The scale map is increasing.
Theorem 5 (no update needed). If is constant within each arm, and and come from logistic regressions with an intercept, fitted within each arm, then and the TMLE equals the plug-in estimate .
Proof. The intercept's score equation of the logistic fit in arm is . With for every treated unit and for every control, . By Lemma 1, .
The limit is doubly robust
Use the setting and assumptions of the AIPW proof: independent units, consistency, ignorability, positivity, true propensity and true regressions . Fix working functions and , let be their fluctuations, , and suppose the population score has a root . Let .
Theorem 6. If , or if and , then .
Proof. The argument of Theorem 2 in expectation gives , where and is the AIPW score. If , the bias identity of the AIPW page gives for every outcome function , in particular for . If , then , and is strictly decreasing (the derivative is ), so , and .
What is not proved here
That and , that is asymptotically linear with influence function when the nuisance estimates converge fast enough, that it is efficient when both are right, and that the influence-function variance gives intervals of the right coverage are cited from van der Laan and Rubin (2006) and van der Laan and Rose (2011, Chapters 4 and 5). The simulation figures on the page are measured.
Complexity
Each Newton-Raphson step does work (two sums, and a log-likelihood evaluation per halving), so with steps the fluctuation costs ; is small in practice, since the problem is one-dimensional and concave. Lines L1, L8 and L9 are . The code keeps the offsets and the updated predictions, extra space. The initial fits dominate the cost when flexible learners are used. The linear fluctuation needs one pass and no iteration.
Properties
- Plug-in. The estimate is , an average of predictions that obey the model's range. In a near-positivity example with four units (; ; ; all initial predictions 0.2), AIPW estimates as 4.1 and the ATE as 3.6; TMLE gives and .
- Doubly robust. In a simulation with uniform on , , , true ATE , and 200 samples (seed 2026), with logistic models in as the right models and constants as the wrong ones:
| working models | mean of | SD | 95% coverage | largest |
|---|---|---|---|---|
| both right | 0.1169 | 0.0371 | 0.940 | 0.0009 |
| outcome wrong | 0.1171 | 0.0371 | 0.945 | 0.0065 |
| propensity wrong | 0.1173 | 0.0352 | 0.895 | 0 |
| both wrong | 0.2151 | 0.0309 | 0.130 | 0 |
The two estimators agree to the third decimal on the same fits. With a constant propensity the update is exactly 0 (the last proved property above), so the last two rows equal AIPW. These numbers are measured.
- Same asymptotics as AIPW. When the nuisance estimates converge fast enough, TMLE and AIPW have the same influence function and so the same limiting variance, which reaches Hahn's (1998) efficiency bound if both models are right. Their difference is of second order.
- Many parameters, one framework. The same recipe (a submodel through the initial fit whose score at contains the efficient influence function, then a plug-in) gives estimators of the ATT, of risk ratios, of survival curves and of effects of time-varying treatments.
Variants and improvements
- Super learner for the initial fit. Van der Laan and Rose recommend fitting and by a cross-validated ensemble of learners, so that both are likely to be consistent.
- Cross-validated TMLE. Fit the nuisances on other folds than the ones used in the update, as in double machine learning, to drop the Donsker conditions that flexible learners may break.
- Collaborative TMLE. Chooses the propensity model in steps, guided by the fit of the targeted outcome model, to avoid weights that add variance without removing bias.
- Iterated and one-step versions. For parameters whose clever covariate depends on itself, the fluctuation is repeated until the score equation holds. The one-step estimator is AIPW: it adds the mean influence function to the plug-in without changing the model.
- Weighted fluctuation. Fitting with covariate and weights or solves the same score equation and is often more stable when the weights are large.
When to use it
Use TMLE when you would use AIPW and the outcome is bounded, especially binary, and the propensities come near 0 or 1, since the plug-in form keeps the estimate in range, which Gruber and van der Laan (2010) found also makes it more stable in finite samples. It is also the natural choice for parameters beyond the ATE, such as survival probabilities, where an average of predictions is easier to keep valid than a weighted correction. For a continuous outcome with no natural bounds, AIPW or the linear fluctuation is simpler and gives almost the same answer.
Pitfalls
- The bounds of the outcome. The logistic fluctuation needs a known range , and the initial predictions must be strictly inside it. Taking and as the sample minimum and maximum is common; truncate predictions a little inside, such as to on the scale of .
- Truncating the propensities. Bounding to an interval such as stabilizes but changes the target slightly; report the bound.
- Not a fix for confounding. Like every method that uses only , TMLE assumes ignorability; targeting improves the estimate of a statistical quantity, not its causal meaning.
- Overfitting. A learner that interpolates the data makes nearly 0, so the update does nothing and the bias of the initial fit stays. Use cross-validated fits.
- A separated update. With very few units, can separate a binary outcome and the fluctuation has no maximum. The code reports this rather than returning a huge .
- Coverage with a wrong model. In the table above, coverage was 0.895 with the wrong propensity model, below the nominal 0.95. The influence-function variance assumes both models are consistent.
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/targeted-maximum-likelihood-estimation/. The authors are listed in prov/SKN7EC.jsonl.
"""Targeted maximum likelihood estimation (TMLE) of the average treatment effect.
The outcome y is scaled to [0, 1] (pass bounds=(a, b) for an outcome in
[a, b]). The inputs are the propensities e[i] and initial predictions q1[i] and
q0[i] of E[Y | T = 1, X_i] and E[Y | T = 0, X_i], on the scale of y. The
targeting step fits one number eps along the clever covariate
H(t, x) = t / e(x) - (1 - t) / (1 - e(x)),
with the logistic fluctuation logit Q*(t, x) = logit Q(t, x) + eps H(t, x), or
the linear fluctuation Q*(t, x) = Q(t, x) + eps H(t, x). The estimate is the
mean of Q*(1, X_i) - Q*(0, X_i). The linear fluctuation is exact for Fraction
inputs; the logistic one is solved by Newton-Raphson in floating point.
"""
import math
from collections.abc import Sequence
from statistics import NormalDist
from typing import NamedTuple
class TMLEResult(NamedTuple):
tau: object # the TMLE estimate of E[Y(1) - Y(0)], on the scale of the input y
mu1: object # the estimate of E[Y(1)]
mu0: object # the estimate of E[Y(0)]
eps: object # the fitted fluctuation parameter
q1_star: list # the targeted predictions Q*(1, X_i), on the [0, 1] scale for the logistic fluctuation
q0_star: list # the targeted predictions Q*(0, X_i)
se: float # the influence-function standard error of tau
def _expit(z: float) -> float:
if z >= 0:
return 1.0 / (1.0 + math.exp(-z))
ez = math.exp(z)
return ez / (1.0 + ez)
def _logit(p: float) -> float:
return math.log(p / (1.0 - p))
def _check(t, y, e, q1, q0):
n = len(t)
if not (n == len(y) == len(e) == len(q1) == len(q0)):
raise ValueError("t, y, e, q1 and q0 must have the same length")
if n < 2:
raise ValueError("need at least two units")
for ti, ei in zip(t, e):
if ti not in (0, 1):
raise ValueError("every treatment must be 0 or 1")
if not 0 < ei < 1:
raise ValueError("positivity fails: every propensity must be strictly between 0 and 1")
def clever_covariate(t: Sequence[int], e: Sequence) -> list:
"""H_i = T_i / e_i - (1 - T_i) / (1 - e_i)."""
return [1 / ei if ti == 1 else -1 / (1 - ei) for ti, ei in zip(t, e)]
def aipw_estimate(t, y, e, q1, q0):
"""The AIPW estimate with outcome predictions q1, q0 (for comparison with TMLE)."""
n = len(t)
s = 0
for ti, yi, ei, a, b in zip(t, y, e, q1, q0):
s += a - b + (ti * (yi - a) / ei if ti == 1 else -(yi - b) / (1 - ei))
return s / n
def fluctuate_logistic(y01: Sequence[float], qa: Sequence[float], h: Sequence[float], tol: float = 1e-12, max_iter: int = 100) -> float:
"""Maximize sum y log q + (1 - y) log(1 - q), q = expit(logit qa + eps h), over eps.
Newton-Raphson on the score U(eps) = sum h (y - q), with step halving on the
log-likelihood, which is concave in eps. Stops when the step is below
tol * (1 + |eps|)."""
off = [_logit(q) for q in qa]
def loglik(eps):
s = 0.0
for yi, oi, hi in zip(y01, off, h):
z = oi + eps * hi
# log expit(z) = -log1p(exp(-z)); log(1 - expit(z)) = -log1p(exp(z))
lp = -math.log1p(math.exp(-z)) if z > -30 else z
lq = -math.log1p(math.exp(z)) if z < 30 else -z
s += yi * lp + (1 - yi) * lq
return s
eps = 0.0 # @line L2
cur = loglik(eps)
for _ in range(max_iter): # @line L3
u = 0.0 # @line L4
info = 0.0
for yi, oi, hi in zip(y01, off, h):
q = _expit(oi + eps * hi)
u += hi * (yi - q)
info += hi * hi * q * (1 - q)
if info <= 0:
raise ArithmeticError("zero information in the fluctuation")
step = u / info # @line L5
new = eps + step
val = loglik(new)
halvings = 0
while val < cur - 1e-15 * abs(cur) and halvings < 60:
step /= 2
new = eps + step
val = loglik(new)
halvings += 1
eps, cur = new, val # @line L6
if abs(step) < tol * (1 + abs(eps)): # @line L7
return eps
raise ArithmeticError("the fluctuation did not converge; the outcome may be separated by H")
def tmle_ate(t: Sequence[int], y: Sequence, e: Sequence, q1: Sequence, q0: Sequence, bounds: tuple | None = None, fluctuation: str = "logistic") -> TMLEResult:
"""TMLE of the ATE. Cost: Theta(n) per Newton step, Theta(n) for the rest."""
_check(t, y, e, q1, q0)
n = len(t)
h = clever_covariate(t, e) # @line L1
if fluctuation == "linear":
# least squares of the residual y - Q(T, X) on H, no intercept: eps = sum H r / sum H^2
r = [yi - (a if ti == 1 else b) for ti, yi, a, b in zip(t, y, q1, q0)]
eps = sum(hi * ri for hi, ri in zip(h, r)) / sum(hi * hi for hi in h)
s1 = [a + eps / ei for a, ei in zip(q1, e)]
s0 = [b - eps / (1 - ei) for b, ei in zip(q0, e)]
scale, shift = 1, 0
ys = list(y)
elif fluctuation == "logistic":
lo, hi_ = bounds if bounds is not None else (0, 1)
if not lo < hi_:
raise ValueError("bounds must satisfy a < b")
scale, shift = hi_ - lo, lo
ys = [(float(yi) - lo) / scale for yi in y]
a1 = [(float(v) - lo) / scale for v in q1]
a0 = [(float(v) - lo) / scale for v in q0]
if any(not 0 <= v <= 1 for v in ys):
raise ValueError("an outcome lies outside the bounds")
if any(not 0 < v < 1 for v in a1 + a0):
raise ValueError("initial predictions must lie strictly inside the bounds")
qa = [u if ti == 1 else v for ti, u, v in zip(t, a1, a0)]
eps = fluctuate_logistic(ys, qa, h)
s1 = [_expit(_logit(u) + eps / float(ei)) for u, ei in zip(a1, e)] # @line L8
s0 = [_expit(_logit(v) - eps / (1 - float(ei))) for v, ei in zip(a0, e)]
else:
raise ValueError("fluctuation must be 'logistic' or 'linear'")
mu1 = sum(s1) / n
mu0 = sum(s0) / n
tau01 = mu1 - mu0 # @line L9
# influence curve on the [0, 1] scale: H (Y - Q*) + Q*(1, X) - Q*(0, X) - tau
d = [hi * (yi - (u if ti == 1 else v)) + u - v - tau01 for hi, yi, ti, u, v in zip(h, ys, t, s1, s0)]
var = sum(float(di) ** 2 for di in d) / (n - 1) / n
se = math.sqrt(var) * float(scale)
if fluctuation == "logistic":
return TMLEResult(tau01 * scale, mu1 * scale + shift, mu0 * scale + shift, eps, s1, s0, se)
return TMLEResult(tau01, mu1, mu0, eps, s1, s0, se)
def tmle_interval(res: TMLEResult, alpha: float = 0.05) -> tuple[float, float]:
z = NormalDist().inv_cdf(1 - alpha / 2)
return float(res.tau) - z * res.se, float(res.tau) + z * res.se
# ----------------------------------------------------------------- nuisance fits
def solve(a: list[list], b: list) -> list:
"""Solve a x = b by Gaussian elimination with partial pivoting."""
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 j in range(c, k + 1):
m[r][j] -= f * m[c][j]
x = [0] * k
for c in range(k - 1, -1, -1):
x[c] = (m[c][k] - sum(m[c][j] * x[j] for j in range(c + 1, k))) / m[c][c]
return x
def fit_logistic(rows: Sequence[Sequence[float]], y: Sequence[float], tol: float = 1e-10, max_iter: int = 50) -> list[float]:
"""Logistic (or quasi-binomial, for y in [0, 1]) regression by Newton-Raphson."""
p = len(rows[0])
b = [0.0] * p
for _ in range(max_iter):
grad = [0.0] * p
hess = [[0.0] * p for _ in range(p)]
for r, yi in zip(rows, y):
q = _expit(sum(bj * rj for bj, rj in zip(b, r)))
w = q * (1.0 - q)
for i in range(p):
grad[i] += (yi - q) * r[i]
for j in range(i + 1):
hess[i][j] += w * r[i] * r[j]
for i in range(p):
for j in range(i + 1, p):
hess[i][j] = hess[j][i]
step = solve(hess, grad)
b = [bj + sj for bj, sj in zip(b, step)]
if max(abs(s) for s in step) < tol:
return b
raise ArithmeticError("Newton-Raphson did not converge; check for separation")
def fit_nuisances(x, t, y01, outcome_features, propensity_features):
"""Propensity by logistic regression; Q(t, x) by logistic regression of y in [0, 1] within each arm."""
prow = [propensity_features(xi) for xi in x]
orow = [outcome_features(xi) for xi in x]
g = fit_logistic(prow, t)
e = [_expit(sum(gj * rj for gj, rj in zip(g, r))) for r in prow]
b1 = fit_logistic([r for r, ti in zip(orow, t) if ti == 1], [yi for yi, ti in zip(y01, t) if ti == 1])
b0 = fit_logistic([r for r, ti in zip(orow, t) if ti == 0], [yi for yi, ti in zip(y01, t) if ti == 0])
q1 = [_expit(sum(bj * rj for bj, rj in zip(b1, r))) for r in orow]
q0 = [_expit(sum(bj * rj for bj, rj in zip(b0, r))) for r in orow]
return e, q1, q0
test_targeted_maximum_likelihood_estimation.py 159 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/targeted-maximum-likelihood-estimation/. The authors are listed in prov/SKN7EC.jsonl.
import math
import random
import statistics
from fractions import Fraction as Fr
import pytest
from targeted_maximum_likelihood_estimation import (
aipw_estimate,
clever_covariate,
fit_nuisances,
tmle_ate,
tmle_interval,
)
# The worked example of the page: the eight units of the IPW page with a binary outcome.
EX_T = [1, 1, 0, 0, 0, 1, 1, 0]
EX_Y = [1, 1, 1, 1, 1, 0, 0, 0]
EX_E = [Fr(1, 4)] * 5 + [Fr(3, 4)] * 3
def test_worked_example_linear_fluctuation_exact():
q1, q0 = [Fr(1, 2)] * 8, [Fr(3, 4)] * 8
assert aipw_estimate(EX_T, EX_Y, EX_E, q1, q0) == Fr(1, 3)
r = tmle_ate(EX_T, EX_Y, EX_E, q1, q0, fluctuation="linear")
assert r.eps == Fr(21, 256)
assert r.q1_star[0] == Fr(53, 64) and r.q1_star[7] == Fr(39, 64)
assert r.q0_star[0] == Fr(41, 64) and r.q0_star[7] == Fr(27, 64)
assert (r.mu1, r.mu0, r.tau) == (Fr(191, 256), Fr(143, 256), Fr(3, 16))
assert aipw_estimate(EX_T, EX_Y, EX_E, r.q1_star, r.q0_star) == Fr(3, 16)
def test_worked_example_logistic_fluctuation():
e = [float(v) for v in EX_E]
r = tmle_ate(EX_T, EX_Y, e, [0.5] * 8, [0.75] * 8)
assert abs(r.eps - 0.3735756) < 1e-6
assert abs(r.tau - 0.1892179) < 1e-6
assert abs(aipw_estimate(EX_T, EX_Y, e, r.q1_star, r.q0_star) - r.tau) < 1e-12
def test_linear_fluctuation_solves_score_exactly():
rng = random.Random(4)
for _ in range(200):
n = rng.randint(2, 10)
t = [rng.randint(0, 1) for _ in range(n)]
if len(set(t)) < 2:
t[0], t[1] = 0, 1
y = [Fr(rng.randint(-9, 9)) for _ in range(n)]
e = [Fr(rng.randint(1, 9), 10) for _ in range(n)]
q1 = [Fr(rng.randint(-9, 9), 2) for _ in range(n)]
q0 = [Fr(rng.randint(-9, 9), 3) for _ in range(n)]
r = tmle_ate(t, y, e, q1, q0, fluctuation="linear")
h = clever_covariate(t, e)
resid = [yi - (a if ti == 1 else b) for ti, yi, a, b in zip(t, y, r.q1_star, r.q0_star)]
assert sum(hi * ri for hi, ri in zip(h, resid)) == 0
assert r.tau == aipw_estimate(t, y, e, r.q1_star, r.q0_star)
def expit(z):
return 1 / (1 + math.exp(-z))
TRUE_ATE = math.log((1 + math.e) / 2) - 0.5 # integral over [0, 1] of expit(x) - expit(-1 + 2x)
def simulate(n, rng):
"""X uniform on [0, 1]; e(x) = expit(-2 + 4x); Pr[Y = 1 | T, X] = expit(-1 + 2x + T(1 - x))."""
x, t, y = [], [], []
for _ in range(n):
xi = rng.random()
ti = 1 if rng.random() < expit(-2 + 4 * xi) else 0
yi = 1 if rng.random() < expit(-1 + 2 * xi + ti * (1 - xi)) else 0
x.append(xi), t.append(ti), y.append(yi)
return x, t, y
def test_logistic_score_equation_and_plug_in_identity():
rng = random.Random(8)
x, t, y = simulate(800, rng)
e, q1, q0 = fit_nuisances(x, t, y, lambda v: [1.0], lambda v: [1.0, v])
r = tmle_ate(t, y, e, q1, q0)
h = clever_covariate(t, e)
score = sum(hi * (yi - (a if ti == 1 else b)) for hi, yi, ti, a, b in zip(h, y, t, r.q1_star, r.q0_star))
assert abs(score) < 1e-8
assert abs(r.tau - aipw_estimate(t, y, e, r.q1_star, r.q0_star)) < 1e-10
assert all(0 < v < 1 for v in r.q1_star + r.q0_star)
def test_constant_propensity_needs_no_update():
"""With a constant propensity, H is constant in each arm, and a logistic outcome fit with an
intercept in each arm already solves the score equation: eps = 0 and TMLE = AIPW = plug-in."""
rng = random.Random(12)
x, t, y = simulate(500, rng)
e, q1, q0 = fit_nuisances(x, t, y, lambda v: [1.0, v], lambda v: [1.0])
r = tmle_ate(t, y, e, q1, q0)
assert abs(r.eps) < 1e-9
plug = sum(a - b for a, b in zip(q1, q0)) / len(t)
assert abs(r.tau - plug) < 1e-9 and abs(r.tau - aipw_estimate(t, y, e, q1, q0)) < 1e-9
def test_agreement_with_aipw_and_double_robustness():
"""r = 30 samples of n = 1000 (seed 2026). Stated tolerance: in every sample, |TMLE - AIPW| < 0.01
on the same nuisance fits; the mean over samples is within 4 SE + 0.005 of the true ATE when
either model is right."""
rng = random.Random(2026)
full = lambda v: [1.0, v]
const = lambda v: [1.0]
configs = {"both": (full, full), "outcome wrong": (const, full), "propensity wrong": (full, const)}
est = {k: [] for k in configs}
r = 30
for _ in range(r):
x, t, y = simulate(1000, rng)
for name, (of, pf) in configs.items():
e, q1, q0 = fit_nuisances(x, t, y, of, pf)
res = tmle_ate(t, y, e, q1, q0)
assert abs(res.tau - aipw_estimate(t, y, e, q1, q0)) < 0.01, name
est[name].append(res.tau)
for name, v in est.items():
assert abs(statistics.mean(v) - TRUE_ATE) < 4 * statistics.stdev(v) / math.sqrt(r) + 0.005, name
def test_stays_in_range_near_positivity_limit():
t, y, e, q = [1, 1, 0, 0], [1, 0, 0, 1], [0.05, 0.5, 0.5, 0.5], [0.2] * 4
a = aipw_estimate(t, y, e, q, q)
assert abs(a - 3.6) < 1e-12 # AIPW: E[Y(1)] estimated as 4.1 for a binary outcome
r = tmle_ate(t, y, e, q, q)
assert 0 < r.mu1 < 1 and 0 < r.mu0 < 1 and -1 < r.tau < 1
assert abs(r.tau - 0.26994310) < 1e-7
def test_bounds_scaling_matches_rescaled_data():
rng = random.Random(3)
t = [rng.randint(0, 1) for _ in range(50)]
t[0], t[1] = 0, 1
y01 = [rng.random() for _ in range(50)]
e = [0.2 + 0.6 * rng.random() for _ in range(50)]
q1 = [0.1 + 0.8 * rng.random() for _ in range(50)]
q0 = [0.1 + 0.8 * rng.random() for _ in range(50)]
base = tmle_ate(t, y01, e, q1, q0)
a, b = -3.0, 7.0
sc = lambda v: a + (b - a) * v
scaled = tmle_ate(t, [sc(v) for v in y01], e, [sc(v) for v in q1], [sc(v) for v in q0], bounds=(a, b))
assert abs(scaled.tau - 10 * base.tau) < 1e-9 and abs(scaled.se - 10 * base.se) < 1e-9
lo, hi = tmle_interval(scaled)
assert lo < scaled.tau < hi
def test_input_checks():
with pytest.raises(ValueError):
tmle_ate([1, 0], [1, 0], [1.0, 0.5], [0.5, 0.5], [0.5, 0.5])
with pytest.raises(ValueError):
tmle_ate([1, 0], [1, 0], [0.5, 0.5], [1.0, 0.5], [0.5, 0.5])
with pytest.raises(ValueError):
tmle_ate([1, 0], [2, 0], [0.5, 0.5], [0.5, 0.5], [0.5, 0.5])
with pytest.raises(ArithmeticError):
tmle_ate([1, 0, 0, 0], [1, 0, 0, 0], [0.05, 0.5, 0.5, 0.5], [0.2] * 4, [0.2] * 4) # H separates Y
History
Van der Laan and Rubin (2006) introduced targeted maximum likelihood learning as a general way to turn an initial density estimate into an estimator that solves the efficient influence function equation for a chosen parameter, and so is doubly robust and efficient when the nuisances are well estimated. The clever covariate had appeared before as a regression term in the doubly robust estimators of Scharfstein, Rotnitzky and Robins (1999) and Bang and Robins (2005). Gruber and van der Laan (2010) showed that the logistic fluctuation on a scaled outcome keeps estimates in range for bounded continuous outcomes. Van der Laan and Rose (2011) wrote the book that made the method widely used, with the super learner for the initial fits. The method was later renamed targeted minimum loss-based estimation, keeping the abbreviation, because the update can use any loss function.
References
- Mark J. van der Laan and Daniel Rubin, Targeted maximum likelihood learning, The International Journal of Biostatistics 2(1), 2006, the whole article (the targeting step along a submodel whose score is the efficient influence function, and its double robustness)
- Susan Gruber and Mark J. van der Laan, A targeted maximum likelihood estimator of a causal effect on a bounded continuous outcome, The International Journal of Biostatistics 6(1), 2010, the whole article (scaling the outcome to [0, 1] and using the logistic fluctuation)
- Mark J. van der Laan and Sherri Rose, Targeted Learning, Causal Inference for Observational and Experimental Data, Springer, 2011, Chapter 4 (introduction to TMLE, pp. 67 to 82) and Chapter 5 (understanding TMLE)
- Heejung Bang and James M. Robins, Doubly robust estimation in missing data and causal inference models, Biometrics 61(4), 2005, pp. 962 to 973 (the regression on the clever covariate, an earlier form of the targeting step)
- 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 for the ATE)
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 SKN7EC Edit this page History Report an error Markdown