A randomized pilot: TMLE with known treatment chances#

At a glance#

A health plan ran a pilot of its navigation program for patients going home from hospital. The pilot drew who got the offer at random, but gave high-risk patients a larger chance (80%) than the others (20%), and it recorded each patient’s chance. Did the offer raise the share of patients with a successful 30-day transition (a transition score of at least 0.7 of the maximum)?

Offering navigation to every eligible patient would raise the share of successful transitions, compared with offering it to no one, by 0.152 (15 percentage points), with a 95% confidence interval of 0.111 to 0.193. The simple comparison of offered and other patients shows almost no difference (-0.006), because the pilot offered navigation mostly to high-risk patients, who succeed less often. The main caveat is that the answer leans on the pilot having used the recorded chances; if staff overrode the draw, it fails. If your data have no recorded chances, start with the one treatment, one outcome example instead.

The data are simulated, so we know the true effect (0.142), and the interval contains it.

The question#

The program gives a patient a bedside plan and two navigator calls in the 30 days after discharge. The plan ran a pilot first. Navigator time was scarce, so the pilot favored the patients it expected to gain most: each patient in the high-risk group (a discharge-risk score above average) had an 80% chance of the offer, and every other patient a 20% chance. The pilot stored both chances for every patient. The question is how much the share of successful transitions would change if every eligible patient got the offer, compared with no one. This is the average treatment effect (ATE).

The graph shows what we assume causes what. R is the risk group, W the four recorded characteristics (the risk score among them), A the offer, Y a successful transition, and U any unrecorded factor.

        ┌───────────────────┐
        │                   ▼
  W ──▶ R ──▶ A ──────────▶ Y ◀── U
  │                         ▲
  └─────────────────────────┘

  W  = discharge_risk, prior_utilization, medication_burden, age
  R  = high_risk, a cut of discharge_risk at its average
  A  = transition_navigation (the offer)
  Y  = transition_success at day 30
  U  = anything unrecorded that affects success

The only arrow into the offer comes from the risk group, because the draw used nothing else. The risk group also predicts success, so it is a confounder (a factor that affects both who got the offer and who succeeds), and the analysis adjusts for the risk score that defines it. The other three were measured before the offer, so it cannot have changed them. Adjusting for those that predict success, such as prior utilization, makes the estimate more precise. An unrecorded factor U can affect success, but it has no arrow into the offer, which is what a random draw buys.

The data#

Every fit sets its seeds, so a rerun prints the same numbers. Another version of cleverly can print slightly different numbers.

import pandas as pd
from sklearn.linear_model import LinearRegression, LogisticRegression

import cleverly

pd.set_option("display.width", 130)
pd.set_option("display.max_columns", 20)
print("cleverly", cleverly.__version__)
cleverly 0.2.4

make_randomized_pilot draws 3,000 simulated discharges from the pilot and also returns the true effect, which real data never give you.

from cleverly.datasets import make_randomized_pilot

# With your own data, load your data frame here, such as frame = pd.read_csv(...).
# Real data have no `truth`, so drop every line that uses it.
frame, truth = make_randomized_pilot(n=3_000, seed=21)
print("rows and columns:", frame.shape)
print("column names:", list(frame.columns))
print(frame.head().round(3).to_string())
print()
print("true values of the simulated data:")
for key in ("ey1", "ey0", "ate"):
    print(f"  {key}: {truth[key]:.3f}")
rows and columns: (3000, 9)
column names: ['transition_success', 'transition_navigation', 'high_risk', 'discharge_risk', 'prior_utilization', 'medication_burden', 'age', 'chance_no_offer', 'chance_offer']
   transition_success  transition_navigation  high_risk  discharge_risk  prior_utilization  medication_burden    age  chance_no_offer  chance_offer
0                 0.0                    1.0        1.0           0.359              0.114             -0.874 -1.316              0.2           0.8
1                 0.0                    1.0        1.0           1.511              0.510              0.375  1.227              0.2           0.8
2                 0.0                    0.0        0.0          -1.786             -0.794             -0.586  0.640              0.8           0.2
3                 1.0                    0.0        1.0           1.687              0.051              0.837  0.236              0.2           0.8
4                 0.0                    0.0        0.0          -0.047             -0.071             -0.925 -0.143              0.8           0.2

true values of the simulated data:
  ey1: 0.573
  ey0: 0.431
  ate: 0.142

Each row is one discharge: success and the offer (each 1 or 0), the risk group, four characteristics measured before the offer, and the two recorded chances. chance_offer is 0.8 in the high-risk group and 0.2 otherwise, and chance_no_offer is one minus it. ey1 and ey0 are the true shares of successful transitions if everyone or no one got the offer, and ate is their difference.

Why a simple comparison misleads#

In this pilot the chance of the offer depended on the risk group, so offered and other patients differed before the offer.

covariates = ["discharge_risk", "prior_utilization", "medication_burden", "age"]
offered = frame["transition_navigation"] == 1.0
unadjusted = (
    frame.loc[offered, "transition_success"].mean()
    - frame.loc[~offered, "transition_success"].mean()
)
print(f"success rate, offered:      {frame.loc[offered, 'transition_success'].mean():.3f}")
print(f"success rate, not offered:  {frame.loc[~offered, 'transition_success'].mean():.3f}")
print(f"unadjusted difference:      {unadjusted:.3f}")
print(f"true average effect (ATE):  {truth['ate']:.3f}")
print()
groups = frame.groupby("high_risk").agg(
    patients=("transition_success", "size"),
    recorded_chance=("chance_offer", "first"),
    share_offered=("transition_navigation", "mean"),
    success_rate=("transition_success", "mean"),
)
print(groups.round(3).to_string())
success rate, offered:      0.499
success rate, not offered:  0.505
unadjusted difference:      -0.006
true average effect (ATE):  0.142

           patients  recorded_chance  share_offered  success_rate
high_risk                                                        
0.0            1448              0.2          0.193         0.588
1.0            1552              0.8          0.795         0.422

The simple difference is -0.006, while the true effect is +0.142. The high-risk group got the offer about 80% of the time and succeeds less often (0.422 against 0.588), so the offered group is mostly high-risk patients. The comparison mixes the offer’s effect with that difference between the groups. A random draw does not remove this confounding when the chances differ between groups, but because the pilot recorded the chances, the analysis can correct for it without estimating each patient’s chance of the offer.

Set up the analysis#

First, describe the study (StudyProtocol). The description is optional and does not change the estimate, but without it nothing records what the number is about. It records what the estimate means (who it is about, the outcome, how deaths before day 30 count), and every result stores an ID that ties it to this description. navigation_protocol() returns the program’s description, and replace changes the fields this pilot changes.

from dataclasses import replace

from cleverly.datasets import navigation_protocol

# For your own study, build cleverly.StudyProtocol(...). It needs all ten fields, each a short
# text or a list of texts, in the order the output prints them:
#   target_population, eligibility: who the answer is about, and the entry rules;
#   time_zero, horizon: when follow-up starts, and when the outcome is measured;
#   treatment_strategies, treatment_versions: the options compared, and their variants;
#   outcome: the measured result;
#   intercurrent_event_handling: how events such as death before the horizon count;
#   interference_unit: the unit whose treatment can affect only its own outcome;
#   assumption_rationale: why the design makes the causal assumptions believable.
program = navigation_protocol()
protocol = replace(
    program,
    outcome="Successful transition: a 30-day transition score of at least 0.7 of the maximum",
    intercurrent_event_handling=(
        "Use the success indicator regardless of readmission",
        program.intercurrent_event_handling[1],
        "The protocol counts death before day 30 as an unsuccessful transition "
        "(composite strategy)",
    ),
    assumption_rationale=(
        "The pilot drew each offer at random, with a recorded chance that depended only on "
        "the discharge-risk group",
        *program.assumption_rationale[1:],
    ),
)
print("\n".join(protocol.summary_lines()))
Population: Adults with a discharge-home order at a participating hospital during the enrollment period
Eligibility: Age 18 years or older; Discharge home ordered at a participating hospital
Follow-up starts: Discharge-home order, after baseline measurement and before the navigation offer
Strategies: Offer standard transition navigation; Provide usual discharge support
Versions: Bedside transition plan and two scheduled navigator contacts within 30 days; No access to the transition-navigation offer
Outcome: Successful transition: a 30-day transition score of at least 0.7 of the maximum
Horizon: 30 days after discharge
Intercurrent events: Use the success indicator regardless of readmission; Analyze the offer regardless of completed contacts; The protocol counts death before day 30 as an unsuccessful transition (composite strategy)
Interference unit: Individual patient
Rationale: The pilot drew each offer at random, with a recorded chance that depended only on the discharge-risk group; Standardized offer and version records support that each offer is one well-defined action, so a patient's recorded outcome is the outcome they would have had under the offer they got; Reserved navigator capacity and access controls support no interference

The changed fields are the outcome (a successful transition), how events before day 30 count (a death counts as unsuccessful, which the output calls the composite strategy), and the first reason for the assumptions, which now names the random draw. The output’s rationale says the version records support that each offer is one well-defined action, the “well-defined treatment” condition (called consistency) of the next step. Follow-up still starts at the discharge-home order, before the offer, and the treatment is the offer, whether or not the patient completed the calls.

Next, name the outcome, the treatment, and the characteristics to adjust for (PointTreatment). treatment_probabilities names the two columns that hold each patient’s recorded chance of each option, keyed by the treatment’s value. study.identify(ATE(reference=0)) then writes down what must be true for the answer to be causal, with no offer (reference=0) as the comparison.

from cleverly import ATE, CausalStudy, PointTreatment

# For your own data, change the outcome and treatment names, the `covariates` list, and the two
# columns that hold each patient's recorded chance of each option.
study = CausalStudy(
    frame,
    design=PointTreatment(
        outcome="transition_success",
        treatment="transition_navigation",
        adjustment=tuple(covariates),
        treatment_probabilities={0: "chance_no_offer", 1: "chance_offer"},
    ),
    protocol=protocol,
)
effect = study.identify(ATE(reference=0))
print("\n".join(effect.summary().splitlines()[:38]))
                            Causal question (ate)
==============================================================================
Question:      average effect of        Rows:                            3,000
               transition_navigation    Answered by:  adjusting for covariates
               on transition_success
               (1 compared with 0)
Outcome:       transition_success
               (binary)
Treatment:     transition_navigation
               (levels 0, 1)
Adjusted for:  discharge_risk,
               prior_utilization,
               medication_burden, age
==============================================================================
Conditions the answer rests on
condition                checkable   what it says
------------------------------------------------------------------------------
well-defined treatment   no          Each unit's observed outcome is the
                                     outcome it would have had under the
                                     treatment it actually received. This
                                     needs the treatment to be well defined:
                                     every way of getting the same level has
                                     the same effect.
no interference          no          One unit's treatment does not change
                                     another unit's outcome.
no hidden confounding    no          Among units with the same adjusted-for
                                     values, which treatment a unit got is
                                     unrelated to the outcomes it would have
                                     had. This holds when the adjusted-for
                                     columns account for the common causes of
                                     transition_navigation and
                                     transition_success and none of them is
                                     affected by transition_navigation.
overlap                  partly      Every group of units that share the
                                     adjusted-for values had some chance of
                                     each compared level of
                                     transition_navigation.
==============================================================================

Of the four conditions, the data can check only overlap, and only partly, from the chances they hold. “Well-defined treatment” (an offer always means the same plan and calls) and “no interference” (one patient’s offer does not change another’s success) need judgment, which the shared study design supports.

“No hidden confounding” holds by design if the pilot followed its draw. Among patients with the same risk score, the draw alone decided who got the offer, so no unrecorded factor could drive it. “Overlap” (every kind of patient had a real chance of either option) also holds by design, since every chance is 0.2 or 0.8.

Estimate the effect#

The method, targeted maximum likelihood estimation (TMLE), fits an outcome model, which predicts success from the offer and the characteristics. A correction step then weights each patient by one over their chance of the option they got, here the recorded chance, to remove the bias the outcome model leaves.

  • outcome_learner is the outcome model, a plain logistic regression. It cannot capture the curved relationships in these data, and with recorded chances it does not need to be right.

  • No treatment_learner: the recorded chances take the place of a treatment model.

  • CrossFitting(enabled=False): each model is trained and used on all rows. “Go deeper” repeats the fit with out-of-fold predictions.

  • Inference(alpha=0.05) and Runtime(random_state=21, n_jobs=1): a 95% interval and a fixed seed.

from cleverly import CrossFitting, Inference, ModelSpec, Runtime, TMLEMethod

# For your own data, swap in your outcome learner. With recorded chances, the fit needs no
# treatment model. A flexible learner, such as a random forest, needs out-of-fold predictions:
# set cross_fitting=CrossFitting(n_folds=5).
recorded = TMLEMethod(
    models=ModelSpec(outcome_learner=LogisticRegression(max_iter=1000)),
    cross_fitting=CrossFitting(enabled=False),
    inference=Inference(alpha=0.05),
    runtime=Runtime(random_state=21, n_jobs=1),
)
result = effect.estimate(method=recorded)

estimate = result["ate"]
print(result.summary())
print()
print(f"population ATE:  {truth['ate']:.3f}")
                            Effect estimate (TMLE)
==============================================================================
Question:      average effect of        Rows:                            3,000
               transition_navigation    Treated share:                   0.504
               on transition_success    Out-of-fold predictions:            no
               (1 compared with 0)      Outcome model:     logistic regression
Outcome:       transition_success       Treatment model:      known (declared)
               (binary)
Adjusted for:  discharge_risk,
               prior_utilization,
               medication_burden, age
Method:        targeted maximum
               likelihood (TMLE)
==============================================================================
      estimate   std. error           95% CI    p-value
------------------------------------------------------------------------------
ate      0.152        0.021   [0.111, 0.193]    <0.0001
==============================================================================
Notes:
[1] The interval of ate, a difference of two proportions, is built from the
    two proportions' log-odds intervals, so it need not be centred on the
    estimate. The p-value is the level at which the interval would just reach
    the null value.

population ATE:  0.142

The estimate is 0.152, with a standard error of 0.021 and a 95% interval of 0.111 to 0.193, which contains the true 0.142. “Treatment model: known (declared)” confirms that the fit used the recorded chances. With them, the interval is valid in large samples even though the outcome model is wrong. This needs a simple outcome model like this one, or out-of-fold predictions: a flexible model trained and used on the same rows can overfit, which biases the estimate and makes the interval too narrow. Use the recorded chances when you have them. A correctly specified fitted treatment model (unlike the one in the next section) can give a slightly less variable estimate, but its printed interval is no narrower, so you would not see the gain.

Details: why the outcome model can be wrong, and a repeated-draw check

The error of TMLE, beyond its leading term, is a product of the treatment-model error and the outcome-model error. With the recorded chances the first factor is zero, so the estimate is consistent for any limit of the outcome model, and its interval is valid and not conservative (too wide, covering the truth more often than 95%), provided the outcome model is fitted out of fold or has a fixed form, such as this logistic regression (Moore and van der Laan, 2009, Sections 2 and 5; the known treatment mechanism section). A better outcome model still narrows the interval.

When the outcome model is wrong, a correctly specified treatment model fitted to the same offers, such as a logistic regression on the risk group, can give an estimate with a smaller true spread. Its reported standard error is then too large, so its interval is conservative (Moore and van der Laan, 2009, Section 4.2).

A simulation we ran for this page (reviews/notebook-review/probes/randomized-pilot/sweep.py) repeats this fit on 200 draws of the same simulated data. The interval contained the true effect on 186 of them (a 95% interval should contain it on about 190), the mean error was -0.0009, and the mean standard error was 0.98 times the standard deviation of the estimates.

What if you fit the chances instead of using the recorded ones?#

An analyst without the recorded chances, or one who ignores them, fits a treatment model to predict who got the offer. Here that model is a logistic regression on the four characteristics, which cannot reproduce the jump from 20% to 80% at the average risk score. The refit keeps the same outcome model, so only the treatment model differs.

from cleverly.learners import thread_limit

# What a fitted treatment model predicts: a logistic regression of the offer on the four
# characteristics. One CPU thread for this plain scikit-learn fit, as cleverly uses for its own.
with thread_limit():
    offer_model = LogisticRegression(max_iter=1000).fit(
        frame[covariates], frame["transition_navigation"]
    )
fitted_chance = pd.Series(offer_model.predict_proba(frame[covariates])[:, 1], index=frame.index)
chances = fitted_chance.groupby(frame["high_risk"]).agg(["min", "mean", "max"])
chances.insert(0, "recorded", frame.groupby("high_risk")["chance_offer"].first())
print("chance of the offer, by risk group: recorded, and fitted (min, mean, max)")
print(chances.round(3).to_string())
print()

# The same TMLE with the same outcome model, but with the fitted treatment model in place of
# the recorded chances.
unrecorded_study = CausalStudy(
    frame,
    design=PointTreatment(
        outcome="transition_success",
        treatment="transition_navigation",
        adjustment=tuple(covariates),
    ),
    protocol=protocol,
)
fitted = unrecorded_study.identify(ATE(reference=0)).estimate(
    method=replace(
        recorded,
        models=ModelSpec(
            outcome_learner=LogisticRegression(max_iter=1000),
            treatment_learner=LogisticRegression(max_iter=1000),
        ),
    )
)
for label, point in (("recorded chances", estimate), ("fitted chances", fitted["ate"])):
    low, high = point.ci
    miss = point.psi - truth["ate"]
    print(
        f"{label:17s} estimate {point.psi:.3f}  95% CI ({low:.3f}, {high:.3f})  error {miss:+.3f}"
    )
print(f"population ATE    {truth['ate']:.3f}")
chance of the offer, by risk group: recorded, and fitted (min, mean, max)
           recorded    min   mean    max
high_risk                               
0.0             0.2  0.004  0.288  0.539
1.0             0.8  0.441  0.707  0.989

recorded chances  estimate 0.152  95% CI (0.111, 0.193)  error +0.010
fitted chances    estimate 0.095  95% CI (0.043, 0.146)  error -0.047
population ATE    0.142

The fitted model smooths the jump, so its chances spread far from 0.2 and 0.8 in both groups. With those chances and the same wrong outcome model, the estimate falls to 0.095, against 0.152 with the recorded chances. Its interval only just reaches the truth, and that is luck: over 200 simulated draws its interval contained the truth only 61 times, against 186 for the recorded chances.

The estimate stays on target in large samples when either the outcome model or the treatment model is right. Recorded chances make the treatment model right by construction, so the outcome model can be wrong. A fitted treatment model can be wrong too, and with both wrong the estimate is biased. Without recorded chances, use flexible models for both, as the one treatment, one outcome example does.

Details: the repeated draws

The same probe (sweep.py) fits TMLE with the fitted logistic treatment model on each of the 200 draws. Its mean error is -0.0622, and its mean standard error is 1.27 times the standard deviation of its estimates. The interval misses mostly because the estimate is biased.

Check the fit#

The overlap check reads the chances the fit divides by, here the recorded ones. Small chances give large weights, so cleverly caps fitted chances away from 0 and 1 (the weight cap). It never moves a recorded chance: if one falls outside the cap, the fit stops and asks for a wider cap (g_bounds=). The check reports the chance closest to 0 or 1, the share of patients at the cap, and the effective sample size: how many equally weighted patients the weighted group is worth.

assessment = result.assess()
support = assessment.report("support")
nuisance = assessment.report("nuisance_models")
attention = tuple(item.name for item in assessment.attention)
print("checks that need attention:", attention or "none")
print()
print("overlap, from the recorded chances:")
print(f"  chance closest to 0 or 1:            {support.truncated['most_extreme']:.3f}")
print(f"  share of patients at the weight cap: {support.truncated['fraction']:.4f}")
for arm, size in support.effective_sample_size.items():
    share = f"{size['effective']:.0f} of {size['n']:.0f} ({size['ratio']:.2f})"
    print(f"  effective sample size, {arm:7s}: {share}")
print()
(outcome_model,) = (model for model in nuisance.models if model.name == "outcome")
print(f"outcome model AUC: {outcome_model.metrics['auc']:.2f}")
print(nuisance.summary().reading)
checks that need attention: none

overlap, from the recorded chances:
  chance closest to 0 or 1:            0.200
  share of patients at the weight cap: 0.0000
  effective sample size, treated: 969 of 1513 (0.64)
  effective sample size, control: 952 of 1487 (0.64)

outcome model AUC: 0.65
The models show no problem these metrics can detect.

Nothing needs attention. The most extreme chance is 0.200, so no patient’s weight exceeds 5 and none reaches the cap. The weights make each group count as 0.64 of its size, because a low-risk patient who got the offer, or a high-risk patient who did not, counts as five patients.

The outcome model separates successes from failures only modestly (an AUC of 0.65, where 0.5 is chance and 1 is perfect). That is no problem here: a better outcome model would only narrow the interval. The last line printed above is the library’s reading of the model checks: it means they found no problem they can detect.

Try to break the result#

These checks change the data in a known way and refit:

  • placebo shuffles the offer, so the estimate should be about zero;

  • random_common_cause adds a column of noise, so the estimate should barely move;

  • subset refits on random 70% samples, so the estimates should spread as much as the standard error predicts for samples of that size.

refutation = result.diagnostics.refute(random_state=21)
columns = ["test", "original", "refuted_mean", "refuted_sd", "expectation", "verdict"]
print(refutation.to_frame()[columns].round(4).to_string(index=False))
print()
for test in refutation.tests:
    print(f"{test.name}: {test.statistic_name} = {test.statistic:.4f}")
               test  original  refuted_mean  refuted_sd       expectation     verdict
            placebo    0.1524        0.0002      0.0174               ~ 0 descriptive
random_common_cause    0.1524        0.1525      0.0004          ~ 0.1524 descriptive
             subset    0.1524        0.1497      0.0108 scatter ~ 0.01358 descriptive

placebo: t = 0.0504
random_common_cause: paired shift in standard errors = 0.0037
subset: scatter ratio rho = 0.7978

All three readings look as they should. The shuffled offer gives an estimate of 0.0002, far below one standard error, and the noise column moves it by 0.0037 standard errors. The 70% refits spread a little less than the standard error predicts (a ratio of 0.80, where 1 is a perfect match). A ratio well above 1 would mean the interval is too narrow; one below 1 errs on the safe side. The verdict column reads descriptive: cleverly gives a pass or fail only when a simulation study backs the check for this kind of fit, and none covers this one, so you judge the numbers.

What we can and can’t conclude#

For the program’s owner: offering navigation to every eligible patient would raise the share of successful 30-day transitions by about 15 percentage points (95% interval 11 to 19), for adults going home from a participating hospital. The interval covers sampling variation only. It rests on the pilot having followed its random draw with the recorded chances, on an offer meaning the same for everyone, and on one patient’s offer not changing another’s success. It also treats discharges as independent; patients who share navigator teams would need the grouped analysis of the shared-teams example. Recording the chances bought two things: the analysis did not need to estimate anyone’s chance of the offer, and its interval holds even though the outcome model is too simple.

The page does not ask how strong a missing confounder would have to be. That question is about factors that drove the offer, and the random draw left none; the one treatment, one outcome example runs it on observational data. This is not the effect of completing the calls, or of the program at other hospitals. The page shows one simulated sample with a known answer, which does not show how the method performs in general.

Go deeper#

How we know the method works#

fit

simulation study

the study’s data

TMLE with recorded chances, in sample and out of fold

TMLE on a declared known treatment mechanism, against the R package tmle

another simulated binary outcome, with chances set by a two-level group

DR-TMLE (doubly robust TMLE) with recorded chances

DR-TMLE on a declared known treatment mechanism, against the R package drtmle

the same simulated data as the TMLE study

adaptive IPTW (inverse probability of treatment weighting) with recorded chances

adaptive IPTW. Its comparison with the R package drtmle is pending

another simulated binary outcome, whose chances depend on a continuous characteristic

The TMLE and DR-TMLE studies use a deliberately wrong outcome model, as this page does. No study uses this page’s simulated data. The adaptive IPTW study uses ten folds where this page uses five. The technical entry states what the recorded chances guarantee, and validation issues special to DR-TMLE and adaptive IPTW give those methods’ limits.

Two other estimators that use the recorded chances#

Two other methods in cleverly can use the recorded chances. DR-TMLE adds extra correction steps meant for the case where the treatment model is fitted and one of the two models may be wrong. Adaptive IPTW fits no model of success on the characteristics. It fits only a small regression of success on the chance, among the patients who got each option, here a logistic one (reduced_outcome_learner), and weights each patient by one over a chance adjusted by that regression.

DR-TMLE has been checked in sample and adaptive IPTW with out-of-fold predictions, so each is paired with a TMLE fit in the same form. Each fit reads supported when a simulation study covers its setup, and experimental when none does.

from cleverly import AdaptiveIPTWMethod, DRTMLEMethod

logistic = ModelSpec(outcome_learner=LogisticRegression(max_iter=1000))
five_folds = CrossFitting(n_folds=5)
# DR-TMLE fits three small regressions, each on one predicted value: the outcome
# residual on the chance, the offer on the predicted success, and the weighting error
# on the predicted success. Two targets are signed, so they need regressors; this is
# the setup the simulation study checked.
dr_tmle = DRTMLEMethod(
    models=logistic,
    cross_fitting=CrossFitting(enabled=False),
    runtime=Runtime(random_state=21, n_jobs=1),
    reduced_outcome_learner=LinearRegression(),
    reduced_treatment_learner=LogisticRegression(max_iter=1000),
    reduced_mechanism_residual_learner=LinearRegression(),
)
fits = {
    ("TMLE", "in sample"): result,
    ("DR-TMLE", "in sample"): effect.estimate(method=dr_tmle),
    ("TMLE", "out of fold"): effect.estimate(method=replace(recorded, cross_fitting=five_folds)),
    ("adaptive IPTW", "out of fold"): effect.estimate(
        method=AdaptiveIPTWMethod(
            models=ModelSpec(),
            cross_fitting=five_folds,
            runtime=Runtime(random_state=21, n_jobs=1),
            reduced_outcome_learner=LogisticRegression(max_iter=1000),
        )
    ),
}
print(f"{'method':14s} {'predictions':12s} {'estimate':>8s}  {'95% CI':16s}  validation status")
for (name, splitting), fit in fits.items():
    point = fit["ate"]
    low, high = point.ci
    print(
        f"{name:14s} {splitting:12s} {point.psi:8.3f}  ({low:.3f}, {high:.3f})    "
        f"{point.support.label}"
    )
print(f"population ATE: {truth['ate']:.3f}")
method         predictions  estimate  95% CI            validation status
TMLE           in sample       0.152  (0.111, 0.193)    supported
DR-TMLE        in sample       0.151  (0.109, 0.192)    supported
TMLE           out of fold     0.153  (0.111, 0.193)    supported
adaptive IPTW  out of fold     0.144  (0.103, 0.186)    supported
population ATE: 0.142

The four estimates agree closely (0.144 to 0.153), and every interval contains the truth and reads supported. Neither method adds protection over TMLE once the chances are recorded. With recorded chances, use TMLE: the DR-TMLE page shows that, in every situation an analyst can name in advance, TMLE’s interval is valid or too wide whenever DR-TMLE’s is valid. Adaptive IPTW suits an analyst who wants no model of success on the characteristics. DR-TMLE’s own page lists the cases where its interval holds with a fitted treatment model.

A smaller correction step#

The correction step adjusts the outcome model’s predictions until the weighted average of their errors is zero, usually in one full step. Targeting(step_bound=...) caps how far each step can move, so the step reaches the same place in several smaller moves, as the R package tmle3 does when an analyst asks it to. Use it to match a tmle3 analysis that used this option. iterate="best" reports the step whose remaining error is smallest.

from cleverly import Targeting

# Each correction step moves at most 0.5, chosen by a line search, and the fit reports the step
# whose remaining error is smallest. A capped walk takes more steps, so it gets a larger budget.
bounded = effect.estimate(
    method=replace(
        recorded,
        targeting=Targeting(step_bound=0.5, iterate="best", max_iter=1000),
    )
)
walk = bounded.fluctuations["mean"]
point = bounded["ate"]
print(f"reached its stopping rule: {walk.converged}")
for label, fit in (("bounded steps", point), ("full step", estimate)):
    low, high = fit.ci
    print(f"{label:13s} estimate {fit.psi:.4f}, 95% CI ({low:.4f}, {high:.4f})")
reached its stopping rule: True
bounded steps estimate 0.1524, 95% CI (0.1115, 0.1927)
full step     estimate 0.1524, 95% CI (0.1115, 0.1927)

The capped walk reaches the same stopping rule as the full step, and its estimate and interval are identical at the printed four decimals. Here the cap changes only the path, so the default full step is enough unless you need to match a tmle3 analysis.

Where to go next#

When nobody randomized the offer, the one treatment, one outcome example fits the treatment model from the data. The weekly offers example uses logged chances for offers repeated over time. The point-treatment TMLE reference gives the exact guarantees of recorded chances, and the DR-TMLE and adaptive IPTW references cover the other two methods. The examples index lists every example.