Who should get the offer: learned rules and random offers with TMLE#
At a glance#
A hospital offers navigation to some of the patients it sends home, and nobody randomized the offer. Navigation helps patients with high need and harms patients with low need. Who should get it, and how many patients would stay home for 30 days under a rule learned from the records? And if staff can cover only some of those who qualify, what does offering it at random among them achieve?
The rule learned from these records offers navigation mainly to patients with a need score above 0. Under it, 71.7% of patients would stay home for 30 days (95% confidence interval 69.0% to 74.3%). The fit learns ten versions of the rule, each on nine tenths of the patients, and 71.7% is their average, and it is the guide to the one rule you would deploy.
Under current practice 67.0% stayed home. You can quote both shares, but cleverly does not yet
estimate the rule’s gain over current practice, so that gap has no interval. Offering navigation
at random to half of the patients with a need score above 0 raises the share by 2.6 per 100
patients sent home, against offering it to no one (95% CI 1.1 to 4.2).
Both answers are causal only if the recorded need score and living situation capture every common cause of the offer and of staying home, which the data cannot check.
The data are simulated, so we know the true values (71.7 and 3.3 per 100), and each interval contains its value.
The question#
At the discharge-home order, the program decides whether to offer a patient navigation: a bedside transition plan and two navigator contacts in the 30 days after discharge, which help with medicines, appointments and warning signs. The outcome is whether the patient stays home, with no unplanned readmission, for 30 days. A treatment rule is a recipe that decides from a patient’s recorded characteristics who gets the offer, and its value is the share who would stay home had the offer followed that rule for every patient.
need, lives_alone ──▶ offer ──▶ stays home for 30 days
need, lives_alone ─────────────▶ stays home for 30 days
need also changes how much the offer helps
assumed absent: an unrecorded cause of both the offer and staying home
Staff offered navigation more often to patients with higher need and to patients who live alone, and both characteristics also change the chance of staying home. They are confounders, variables that drive both the offer and the outcome. Need does one more thing: it changes how much the offer helps, so the best rule offers navigation to some patients and not to others.
The data#
Every fit sets its seeds, so a rerun prints the same numbers.
from dataclasses import replace
import numpy as np
import pandas as pd
import cleverly
pd.set_option("display.width", 160)
pd.set_option("display.max_columns", 20)
print("cleverly", cleverly.__version__)
cleverly 0.2.6
Another version of cleverly can print slightly different numbers.
make_treatment_rules draws 2,000 simulated patients and also returns the true answers, which
real data never give you.
from cleverly.datasets import make_treatment_rules
# With your own data, load one row per patient, such as pd.read_csv(...), with the recorded
# characteristics, the offer (0 or 1), and the outcome (1 if the patient stayed home 30 days).
# Real data have no `truth`: delete the lines marked "simulation only" here and below. The cells
# below name need, lives_alone, offer and home_30, and cut need at 0 and at the bands of the rule
# cell; change those for your data.
frame, truth = make_treatment_rules(n=2_000, seed=7)
print("rows and columns:", frame.shape)
print(list(frame.columns))
print(frame.head().round(2).to_string())
print("offered:", int(frame["offer"].sum()), " stayed home 30 days:", int(frame["home_30"].sum()))
print()
# simulation only, to the end of the cell
print("true share who stay home for 30 days:")
print(f" offer to no one {truth['ey_none']:.4f}")
print(f" offer to everyone {truth['ey_all']:.4f}")
best, cutoff = truth["ey_best_rule"], truth["best_rule_cutoff"]
print(f" the best rule {best:.4f}, offers when need > {cutoff:g}")
rows and columns: (2000, 4)
['need', 'lives_alone', 'offer', 'home_30']
need lives_alone offer home_30
0 0.25 0.0 0.0 1.0
1 0.79 0.0 1.0 1.0
2 0.55 1.0 1.0 1.0
3 -0.55 1.0 1.0 1.0
4 -0.40 1.0 1.0 1.0
offered: 1061 stayed home 30 days: 1339
true share who stay home for 30 days:
offer to no one 0.6522
offer to everyone 0.6763
the best rule 0.7197, offers when need > -0.1
Each row is one patient. need is a need score from -1 (lowest) to 1 (highest), where 0 is the
middle of the scale rather than a clinical cut-off, and
lives_alone is 1 for a patient who lives alone. Offering navigation to everyone would raise the
share who stay home only from 0.6522 to 0.6763, because the offer helps some patients and harms
others. The best rule, which offers navigation only where it helps, would reach 0.7197.
Why a simple comparison misleads#
print("average need and share living alone, by the offer:")
print(frame.groupby("offer")[["need", "lives_alone"]].mean().round(3))
print()
# The simple comparison: the share who stayed home, offered minus not offered.
shares = frame.groupby("offer")["home_30"].mean()
print(f"simple difference, everyone: {shares[1] - shares[0]:+.4f}")
print(f"true difference, everyone offered against none: {truth['ate']:+.4f}") # simulation only
half = np.where(frame["need"] > 0, "need above 0", "need 0 or below")
by_half = frame.groupby([half, "offer"])["home_30"].mean().unstack()
print("simple difference by half:", (by_half[1.0] - by_half[0.0]).round(4).to_dict())
average need and share living alone, by the offer:
need lives_alone
offer
0.0 -0.096 0.473
1.0 0.084 0.524
simple difference, everyone: -0.0328
true difference, everyone offered against none: +0.0241
simple difference by half: {'need 0 or below': -0.1467, 'need above 0': 0.1066}
Offered patients had higher need and lived alone more often, and without navigation both lower the chance of staying home. So the simple difference, -0.0328, says navigation hurts, while offering it to everyone would in truth raise the share by 0.0241. Split at a need score of 0, the simple differences point opposite ways, -0.1467 and 0.1066: a first sign that the offer helps some patients and not others. Each half still mixes the offer’s effect with who got it.
Set up the analysis#
First, describe the study (StudyProtocol): who is in it, when follow-up starts, what each option
means, and what the outcome is. The description does not change the estimate; it records what the
estimate means, and each result keeps a copy of it. You can skip it if you need only the estimate.
The code adapts the program’s shared study description.
from cleverly.datasets import navigation_protocol
# For your own study, build cleverly.StudyProtocol(target_population=..., eligibility=...,
# time_zero=..., treatment_strategies=(...), treatment_versions=(...), outcome=..., horizon=...,
# intercurrent_event_handling=(...), interference_unit=..., assumption_rationale=(...)),
# one field for each printed label, with your own text.
program = navigation_protocol()
protocol = replace(
program,
treatment_strategies=(
*program.treatment_strategies,
"Offer navigation by a rule learned from the recorded need and living situation",
"Offer navigation at random, with chance one half, to patients with a need score above 0",
),
treatment_versions=(
*program.treatment_versions,
"The standard offer for the patients the rule selects, usual support for the others",
"The standard offer for the patients the random draw selects, usual support for the others",
),
outcome="Stayed home for 30 days after discharge, with no unplanned readmission",
intercurrent_event_handling=(
"Count an unplanned readmission within 30 days as not staying home",
program.intercurrent_event_handling[1], # the shared rule on completed contacts
"Count death before day 30 as not staying home (composite strategy)",
),
)
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; Offer navigation by a rule learned from the recorded need and living situation; Offer navigation at random, with chance one half, to patients with a need score above 0
Versions: Bedside transition plan and two scheduled navigator contacts within 30 days; No access to the transition-navigation offer; The standard offer for the patients the rule selects, usual support for the others; The standard offer for the patients the random draw selects, usual support for the others
Outcome: Stayed home for 30 days after discharge, with no unplanned readmission
Horizon: 30 days after discharge
Intercurrent events: Count an unplanned readmission within 30 days as not staying home; Analyze the offer regardless of completed contacts; Count death before day 30 as not staying home (composite strategy)
Interference unit: Individual patient
Rationale: The recorded baseline variables cover the measured common causes; 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 protocol adds the learned rule and the random offer to the shared description’s two options, and changes the outcome and the intercurrent events, the rules for events after discharge. A readmission or a death counts as not staying home, so an option cannot look better because its patients die first. Folding such an event into the outcome is called a composite strategy.
Name the columns, the question and its conditions#
Tell cleverly which column holds the offer, which holds the outcome, and which characteristics
to adjust for (PointTreatment). LearnedRuleValue asks for the value of a rule that the fit
learns from the data. identify checks that the columns can answer that question and lists the
conditions the answer needs.
from cleverly import CausalStudy, LearnedRuleValue, PointTreatment
# For your own data, change the column names.
design = PointTreatment(outcome="home_30", treatment="offer", adjustment=("need", "lives_alone"))
study = CausalStudy(frame, design=design, protocol=protocol)
question = study.identify(LearnedRuleValue())
print(question.summary())
Causal question (ey_learned_rule)
==============================================================================
Question: weighted average over Rows: 2,000
the outer folds of the Answered by: adjusting for covariates
value of the rule
learned on each fold's
training rows
Outcome: home_30 (binary)
Treatment: offer (levels 0, 1)
Adjusted for: need, lives_alone
==============================================================================
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
offer and home_30 and none of them is
affected by offer.
==============================================================================
Methods
method name
------------------------------------------------------------------------------
tmle targeted maximum likelihood (TMLE)
==============================================================================
Notes:
[1] The full summary states 7 further conditions the answer rests on.
[2] The methods table lists the methods that fit. 11 other methods cannot
estimate this question; the full summary says why.
The question line is the target: the fit holds out each tenth of the patients in turn (the “outer folds”), learns a rule without it, and the target is the average value of those rules. The three conditions, in plain words:
well-defined treatment (called consistency in the study description): an offer means the same contacts for every patient;
no interference: one patient’s offer does not change another patient’s chance of staying home;
no hidden confounding: need and living alone hold every common cause of the offer and of staying home.
The data cannot check any of them. Note [1] points to seven more conditions in
summary(detail="full"). Two matter most here: overlap, meaning every patient had a real chance of
either option, which the weight check below partly checks; and a clear best rule, meaning the offer
has some effect, good or bad, for almost every patient, so the learned rules do not flip at random.
The simulation meets both. On real data the weight check speaks to overlap, and nothing checks the
clear best rule directly. Only TMLE, used next, answers this question.
Estimate the value of a learned rule#
The fit splits the patients into ten folds, groups of 200. For each fold, it fits an outcome model on the other nine folds, and the rule offers navigation to a patient when that model predicts a better chance of staying home with the offer than without it. It then estimates how that rule does on the fold it did not learn from, with targeted maximum likelihood estimation (TMLE): a correction step that uses the treatment model to remove the bias that the outcome model leaves. The reported value is the average of the ten fold results.
outcome_learnerpredicts staying home from the offer and the characteristics. The rule can only offer navigation by need if the model lets the offer’s effect change with need, so it includes every product of two inputs, such as offer times need.treatment_learnerpredicts who was offered.CrossFitting(n_folds=10, fold_evaluation=True)learns each fold’s rule without that fold and scores it on that fold, so no patient helps choose the rule that is then scored on them.
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures
from cleverly import CrossFitting, ModelSpec, Runtime, TMLEMethod
# For your own data, give the outcome model the offer-by-characteristic terms that the rule can
# use. C=1e6 turns off scikit-learn's default shrinkage of the coefficients, which would pull the
# offer's effect toward zero and blur where it helps. Runtime fixes the seeds.
outcome_model = make_pipeline(
PolynomialFeatures(2, interaction_only=True, include_bias=False),
LogisticRegression(C=1e6, max_iter=5000),
)
method = TMLEMethod(
models=ModelSpec(
outcome_learner=outcome_model,
treatment_learner=LogisticRegression(C=1e6, max_iter=1000),
),
cross_fitting=CrossFitting(n_folds=10, fold_evaluation=True),
runtime=Runtime(random_state=13, n_jobs=1),
)
learned = question.estimate(method=method)
print(learned.summary())
Effect estimate (TMLE)
==============================================================================
Question: value of a treatment Rows: 2,000
rule learned from the Treated share: 0.530
data Out-of-fold predictions: 10 folds
Outcome: home_30 (binary) Outcome model: logistic regression
Adjusted for: need, lives_alone after polynomial terms
Method: targeted maximum Treatment model: logistic regression
likelihood (TMLE) Probability limits: [0.01471, 0.9853]
==============================================================================
estimate std. error 95% CI p-value
------------------------------------------------------------------------------
ey_learned_rule[learned rule] 0.717 0.014 [0.690, 0.743] <0.0001
==============================================================================
Notes:
[1] The interval of ey_learned_rule[learned rule] is built on the log-odds
scale and turned back, so it stays inside the possible range of a
proportion and need not be centred on the estimate.
The estimate row is the value of the learned rule: 0.717, so about 72 of every 100 patients would stay home for 30 days (95% CI 0.690 to 0.743). The p-value tests only whether the share is zero. The treated share, 0.530, is the share offered in the data. The probability limits are a floor and a ceiling for each predicted chance of the offer, chosen from the number of rows, and no patient reached them.
from cleverly.datasets import learned_rule_truth
value = learned["ey_learned_rule[learned rule]"]
record = learned.extra["learned_rule"]
low, high = value.ci
print(f"value of the learned rule: {value.psi:.4f}, 95% CI {low:.4f} to {high:.4f}")
print(
f"per 100 patients: {100 * value.psi:.1f} stay home, 95% CI {100 * low:.1f} to {100 * high:.1f}"
)
print(f"stayed home under the staff's own choices: {100 * frame['home_30'].mean():.1f} per 100")
(split,) = record.splits # the fit drew one split of the patients into ten folds
# arm_shares holds, per fold, the share of patients its rule does not offer and offers.
fold_shares = [offered for _, offered in split.arm_shares]
print(
f"share of patients each fold's rule offers: {min(fold_shares):.3f} to {max(fold_shares):.3f}"
)
# learned.nuisance holds the fitted parts behind the estimate. Its regimes.values[i, a, r] is
# patient i's chance of offer a under option r. The learned rule is
# option 0, so [:, 1, 0] is 1 when the rule from the fold that held the patient out offers.
offered_by_rule = pd.Series(learned.nuisance.regimes.values[:, 1, 0], index=frame.index)
edges = [-1.0, -0.1, 0.0, 0.1, 0.2, 1.0]
labels = ["-1 to -0.1", "-0.1 to 0", "0 to 0.1", "0.1 to 0.2", "0.2 to 1"]
bands = pd.cut(frame["need"], edges, labels=labels, include_lowest=True).rename("need score")
print("share the rules offer, by need score:")
print(offered_by_rule.groupby(bands, observed=True).mean().round(3).to_string())
print()
# simulation only, to the end of the cell: the true value of the ten fold rules, which the
# simulation computes by refitting each fold's outcome model.
true_target = learned_rule_truth(learned, outcome_model)
print(f"true value of the ten fold rules: {true_target:.4f}, or {100 * true_target:.1f} per 100")
print(f"true value of the best rule: {truth['ey_best_rule']:.4f}")
value of the learned rule: 0.7174, 95% CI 0.6900 to 0.7433
per 100 patients: 71.7 stay home, 95% CI 69.0 to 74.3
stayed home under the staff's own choices: 67.0 per 100
share of patients each fold's rule offers: 0.345 to 0.545
share the rules offer, by need score:
need score
-1 to -0.1 0.000
-0.1 to 0 0.009
0 to 0.1 0.300
0.1 to 0.2 0.744
0.2 to 1 1.000
true value of the ten fold rules: 0.7174, or 71.7 per 100
true value of the best rule: 0.7197
The rules offer navigation to almost no patient with a need score below -0.1 and to almost every patient above 0.2. The best rule offers it above -0.1, so the rules miss many patients between -0.1 and 0.2, where navigation helps only a little. The share each fold’s rule offers varies, both with which 200 patients the fold holds and with where its rule draws the line inside that band. Their true value, 0.7174, is just below the best rule’s 0.7197, and the estimate lands on it.
To use a rule in the program, you would fit the outcome model once on all patients and offer
navigation where it predicts a gain. The section on scoring a rule on the patients it was learned
from fits that rule by hand (its logistic row). cleverly can also estimate that one rule’s value
with an interval, using CrossFitting(enabled=False), when the outcome model has a fixed set of
terms, as this logistic model does.
The “Learned treatment rules” section of the estimands guide shows
how. When the
fold rules settle on one rule, as the conditions below require, the rule fitted on all patients settles
on the same one, so the fold rules’ value is the guide to it. Its true value here is 0.7175.
Details: when the interval can be trusted
The interval is valid in large samples when every patient had a real chance of either option, the treatment model or the outcome model is good enough, and the fold rules settle on one rule as the sample grows. The last condition fails when the offer has no effect for a share of patients: the rules then flip at random, and the interval can be too narrow. The simulation studies also find the interval too narrow at 2,000 patients when the effect is weak for everyone (see “Go deeper”).
Check the weights behind the estimate#
The correction step weights each patient whose offer matches the rule by one over their predicted chance of that offer. The overlap check reads these weights: every patient needs a real chance of the option the rule assigns.
assessment = learned.assess()
ledger = assessment.to_frame()
# Keep the checks that ran: `passed` has a pass mark, `completed` is a report to read.
ran = ledger[ledger["status"].isin(["passed", "completed"])]
print(ran[["check", "status"]].to_string(index=False))
print("needs attention:", tuple(item.name for item in assessment.attention) or "none")
print()
overlap = assessment.report("support").to_frame().iloc[0]
print(f"smallest predicted chance of the offer the rule assigns: {overlap['min_propensity']:.3f}")
print(f"largest weight: {overlap['max_ratio']:.2f}")
matched = int((frame["offer"] == offered_by_rule).sum())
print(f"patients whose offer matched the rule: {matched} of {len(frame)}")
print(f"effective sample size: {overlap['effective_n']:.0f}")
check status
score_equations passed
support completed
nuisance_models completed
omitted_confounding completed
robustness_value completed
elements completed
contour completed
needs attention: none
smallest predicted chance of the offer the rule assigns: 0.429
largest weight: 2.33
patients whose offer matched the rule: 1152 of 2000
effective sample size: 1139
Nothing needs attention. The correction step adjusts the outcome model’s predictions until a
further adjustment would no longer change the estimate, and score_equations passed says it got
there. The nuisance_models row lists the two fitted helper models, for
the outcome and for the offer. Every patient had a predicted chance of at least 0.429 of the option
the rule assigns, so the largest weight is 2.33. Only the 1152 patients whose offer matched the rule
carry weight, and their weights are worth 1139 equally weighted patients, the effective sample
size. Warning signs are a chance near 0, a few huge weights, or an effective sample size far below
the number matched.
A clean check reads the fitted treatment model, so it cannot show that the model is right.
The four rows from omitted_confounding to contour are the bound on a missing confounder, which
“How much could a missing confounder move the answers?” reads below.
What goes wrong when a rule is scored on the patients it was learned from#
The common mistake is to fit one outcome model on all patients, read off the rule, and score the
rule with the same model on the same patients. The code does that by hand, outside cleverly,
with the logistic model above and with a random forest, a flexible model that can memorize noise,
and the simulation gives each rule’s true value.
from sklearn.base import clone
from sklearn.ensemble import RandomForestClassifier
from cleverly.datasets import treatment_rule_value
# thread_limit runs the forest on one CPU thread, so reruns match.
from cleverly.learners import thread_limit
inputs = ["offer", "need", "lives_alone"]
def with_offer(data, offer):
return data[["need", "lives_alone"]].assign(offer=float(offer))[inputs]
forest = RandomForestClassifier(n_estimators=200, min_samples_leaf=5, random_state=17, n_jobs=1)
rows = []
with thread_limit():
for label, model in (("logistic, as above", outcome_model), ("random forest", forest)):
fitted = clone(model).fit(frame[inputs], frame["home_30"])
def chance(data, offer, fitted=fitted):
return fitted.predict_proba(with_offer(data, offer))[:, 1]
def rule(data, chance=chance):
return (chance(data, 1) > chance(data, 0)).astype(float)
offered = rule(frame)
score = np.where(offered == 1, chance(frame, 1), chance(frame, 0)).mean()
rows.append(
{
"model": label,
"share offered": offered.mean(),
"in-sample score": score,
"true value": treatment_rule_value(rule), # simulation only
}
)
scored = pd.DataFrame(rows)
print(scored.round(4).to_string(index=False))
model share offered in-sample score true value
logistic, as above 0.4475 0.7303 0.7175
random forest 0.4590 0.7746 0.6979
Both rules look better on the patients they were learned from than they are, and the forest’s score of 0.7746 against a true 0.6979 shows how far. The forest fits noise: it offers navigation to patients who happened to do well with it and withholds it from patients who happened to do well without it, then counts that luck as the rule’s success. The in-sample score even ranks the worse rule first.
Across 400 simulated samples (see “Go deeper”) the forest’s in-sample score was too high by 0.0871 on average, and the logistic one by 0.0036. With a flexible model such as the forest, no standard formula for an interval allows for the same patients both choosing the rule and scoring it. The fit above avoids the problem, because each rule is scored only on patients it never saw.
When capacity is limited: offer at random#
Suppose staff can cover only about a quarter of the patients: half of the roughly half with a need score above 0. The program would then assign the offer at random: each patient with a need score above 0 gets the offer with chance one half, and no one else does. Unlike the rule, this random offer is fixed before anyone looks at an outcome, so no patient’s luck helps choose it.
Because the program sets those chances itself, they are known exactly, and
Stochastic(..., density_kind="known") declares that they were fixed in advance, so the
interval treats them as exact.
Static(0) is the option of offering to no one. RegimeMean asks for the share who stay home
under each option, and reference= marks the baseline for comparisons: no offers, a
plan that means the same anywhere, while current practice depends on these staff. With simple
models that cannot memorize their training rows, the fit uses every patient for every model
(CrossFitting(enabled=False)), which is faster.
from cleverly import RegimeMean
from cleverly.interventions import Static, Stochastic
# For your own program, return the chances your random offer uses: one row per patient, with the
# chance of no offer and then the chance of an offer.
def random_chances(data):
offer = np.where(data["need"] > 0, 0.5, 0.0)
return np.column_stack([1 - offer, offer])
plans = (
Static(0, name="offer to none"),
Stochastic(random_chances, name="random offer", density_kind="known"),
)
in_sample = replace(method, cross_fitting=CrossFitting(enabled=False))
options = study.identify(RegimeMean(plans, reference="offer to none")).estimate(method=in_sample)
print(options.summary())
Effect estimate (TMLE)
==============================================================================
Question: effect of offer on Rows: 2,000
home_30; each row is Treated share: 0.530
defined below Out-of-fold predictions: no
Outcome: home_30 (binary) Outcome model: logistic regression
Adjusted for: need, lives_alone after polynomial terms
Method: targeted maximum Treatment model: logistic regression
likelihood (TMLE) Probability limits: [0.01471, 0.9853]
==============================================================================
estimate std. error 95% CI p-value
------------------------------------------------------------------------------
ey_regime[offer to none] 0.668 0.016 [0.636, 0.698] <0.0001
ey_regime[random offer] 0.694 0.012 [0.669, 0.717] <0.0001
==============================================================================
What each row estimates
meaning
------------------------------------------------------------------------------
ey_regime[offer to none] counterfactual mean under each declared regime
ey_regime[random offer] counterfactual mean under each declared regime
==============================================================================
Simultaneous 95% bands
band
------------------------------------------------------------------------------
ey_regime[offer to none] [0.633, 0.700]
ey_regime[random offer] [0.667, 0.720]
==============================================================================
Warnings:
[1] The models were fitted and evaluated on the same rows. With flexible
learners this can make the interval too narrow; cross-fitting
(cross_fit=True, or CrossFitting() in a study method) gives out-of-fold
predictions.
Notes:
[2] The interval of ey_regime[offer to none], ey_regime[random offer] is built
on the log-odds scale and turned back, so it stays inside the possible
range of a proportion and need not be centred on the estimate.
[3] The bands cover all 2 rows at once with 95% probability; use them when you
read several rows together. No validation study covers the bands for this
kind of fit, so cleverly marks them experimental.
Each row is the share who would stay home under one option, which the output calls the
counterfactual mean under a regime: 0.668 with no offers and 0.694 under the random offer. The
simultaneous bands cover both rows at once, so they are wider than the intervals; cleverly marks
them experimental, so read the intervals. Warning [1] concerns flexible models, which this fit does
not use.
names = ["ey_regime[random offer]", "ey_regime[offer to none]"]
# psi holds the named estimates in order; .psi is an estimate's value and .ci its interval.
gain = options.contrast(lambda psi: psi[0] - psi[1], names, name="random offer minus none")
low, high = gain.ci
print(f"random offer minus no offers: {gain.psi:+.4f}, 95% CI {low:+.4f} to {high:+.4f}")
print(f"per 100 patients: {100 * gain.psi:+.1f}, 95% CI {100 * low:+.1f} to {100 * high:+.1f}")
options_assessment = options.assess()
print("needs attention:", tuple(item.name for item in options_assessment.attention) or "none")
random_overlap = options_assessment.report("support").to_frame().set_index("regime")
print("largest weight, by option:", random_overlap["max_ratio"].round(2).to_dict())
print()
# simulation only, to the end of the cell: the true gain
true_random = treatment_rule_value(lambda data: random_chances(data)[:, 1])
true_gain = true_random - truth["ey_none"]
print(f"true gain: {true_gain:+.4f}, or {100 * true_gain:+.1f} per 100")
random offer minus no offers: +0.0262, 95% CI +0.0113 to +0.0422
per 100 patients: +2.6, 95% CI +1.1 to +4.2
needs attention: none
largest weight, by option: {'offer to none': 3.19, 'random offer': 2.26}
true gain: +0.0335, or +3.3 per 100
The random offer raises the share who stay home by 2.6 per 100 patients against no offers (95% CI
1.1 to 4.2), and the true gain is 3.3. options.contrast(...) turns the two shares into a
difference, with a standard error that allows for both coming from the same patients. In this
simulation the random offer gains more than offering navigation to everyone would (0.0241 in truth,
from the data step), because it reaches only patients with need above 0, where the offer helps every
patient in this simulation. The weight check finds nothing that needs attention, and the largest
weight is 3.19.
How much could a missing confounder move the answers?#
The robustness value asks how strong a missing confounder would have to be to erase the random
offer’s gain. It reads a row of the fit, and the gain above was built after the fit, so the cell
refits with RegimeContrast, which makes each option’s difference from the reference a row. A
benchmark is a recorded variable used as a yardstick: the bound then says how far a missing
confounder as strong as that variable could move the gain.
from cleverly import RegimeContrast
random_fit = study.identify(RegimeContrast(plans, reference="offer to none")).estimate(
method=in_sample
)
RANDOM_OFFER = "ate_regime[random offer vs offer to none]"
sensitivity = random_fit.sensitivity
robustness = sensitivity.robustness_value(estimand=RANDOM_OFFER)
print(f"robustness value: {robustness['rv']:.3f} ({robustness['rva']:.3f} at the 95% limit)")
# For your own data, benchmark each recorded confounder that the random offer does not read. A
# benchmark refits without the variable, and the random offer cannot assign offers without need.
benchmark = sensitivity.benchmark(covariates=("lives_alone",), estimand=RANDOM_OFFER)
print(
f"strengths of lives_alone: outcome side {benchmark.cf_y:.3f}, offer side {benchmark.cf_d:.3f}"
)
bound = sensitivity.omitted_confounding(estimand=RANDOM_OFFER, benchmark=benchmark)
print(
f"a confounder as strong as lives_alone: largest shift {bound.bias:.4f}, "
f"95% limits {bound.ci_lower:.4f} to {bound.ci_upper:.4f}"
)
robustness value: 0.076 (0.040 at the 95% limit)
strengths of lives_alone: outcome side 0.003, offer side 0.002
a confounder as strong as lives_alone: largest shift 0.0008, 95% limits 0.0128 to 0.0404
A missing confounder has two strengths, each a share from 0 to 1. On the outcome side, it is the share of the outcome’s unexplained variation that the confounder explains. On the offer side, it is roughly how much better the confounder would predict who got an offer, beyond need and living alone, measured through the weights that correct for who got one. The robustness value, 0.076, is a floor: a confounder weaker than that on both sides cannot erase the gain, and 0.040 on both sides is enough to pull the lower end of the interval to zero. A confounder strong on one side can erase it while weaker than 0.076 on the other.
Living alone has strengths of only 0.003 and 0.002, and a confounder that strong would shift the gain by at most 0.0008, leaving one-sided 95% limits of 0.0128 and 0.0404 (one-sided limits, which sit inside the two-sided interval here because the shift is tiny). Whether unrecorded support at home could reach 0.040 on both sides is a judgment about the program.
Details: the limits of the bound
The bound reads the random offer’s gain, under the worst case in which the confounder’s two effects
align. No simulation study covers it for a random offer, so read it as a description. The check
cannot leave out need, because the random offer reads it.
# The same question for the learned rule's value, with the ten rules the fit learned held fixed.
RULE = "ey_learned_rule[learned rule]"
shift = 0.05 # For your own program, the drop in the value that would change the decision.
rule_sensitivity = learned.sensitivity
rule_robustness = rule_sensitivity.robustness_value(
estimand=RULE, null_hypothesis=value.psi - shift
)
print(f"strength on both sides that could lower the value by {shift}: {rule_robustness['rv']:.3f}")
rule_bound = rule_sensitivity.omitted_confounding(estimand=RULE, cf_y=0.03, cf_d=0.03)
print(
f"with both strengths at 0.03: largest shift {rule_bound.bias:.4f}, "
f"value between {rule_bound.lower:.4f} and {rule_bound.upper:.4f}"
)
strength on both sides that could lower the value by 0.05: 0.079
with both strengths at 0.03: largest shift 0.0185, value between 0.6989 and 0.7359
The same check runs on the learned rule’s value. It keeps the ten rules the fit learned fixed, so it asks how far a missing confounder could move the value of those rules, not of the way they were learned. The robustness value, 0.079, is again a floor: a confounder weaker than that on both sides cannot lower the value by 0.05 (5 per 100 patients), while one strong on a single side can do so with the other side weaker. With both strengths at 0.03, the value could move by at most 0.0185, to between 0.6989 and 0.7359.
These are the worst-case shifts alone, with no 95% limits around them, because no formula for their uncertainty is worked out for a learned rule. Nor is there a comparison with a recorded variable such as living alone: leaving a variable out would change the rules themselves.
Details: what the rule’s bound holds fixed
The reported value is the average of the ten fold rules’ values, so the bound treats the ten rules as fixed and asks how far a missing confounder could bias the estimate of that average. No simulation study covers this bound, so read it as a description. The technical reference gives the derivation and the conditions it needs, under “The point bound of a learned-rule value”.
What we can and can’t conclude#
For the program: a rule learned from these records, which offers navigation mainly to patients with a need score above 0, would have 71.7% of patients stay home for 30 days (95% interval 69.0% to 74.3%), the average over the ten versions the fit learned. If staff can cover only a quarter of patients, offering navigation at random to half of those with a need score above 0 raises the share by 2.6 per 100 against no offers (95% interval 1.1 to 4.2). Both answers hold for adults sent home from a participating hospital, if the conditions listed under “Name the columns, the question and its conditions” hold and the models are good enough.
Neither answer says what the best possible rule achieves, and the rule’s interval can be too narrow if the offer has no effect for a share of patients, or a weak effect for everyone at this size. A missing confounder weaker than 0.079 on both sides could not lower the rule’s value by 5 per 100; that bound holds the ten learned rules fixed and has no 95% limits.
Go deeper#
How we know the method works#
Simulation studies check each method over many repeated samples.
part of the page |
simulation study |
its data |
|---|---|---|
the learned rule |
learned-rule CV-TMLE (cross-validated TMLE) |
2,000 rows, ten folds and this page’s outcome model. On simulated data of the same shape (a need-like score, a yes-or-no characteristic, and an effect that changes steadily with the score) the 95% intervals contained the true value in 0.9465 of the samples (the target is 0.95); on data where the outcome model is wrong, 0.9413 |
the learned rule, at its limit |
simulated data where the offer has no effect for anyone, or a weak one. The interval covered only 0.8938 and 0.8948 |
|
the random offer |
other simulated data, with one three-level characteristic, compared with |
The random-offer study gives the method the true chances of the real offer, while this page estimates them, so the study does not test the treatment model. The technical entry lists the method’s evidence and limits.
A simulation we ran for this page redraws the data 400 times at the page’s size and refits each
sample with the page’s settings. It checks the page’s readings and does not validate the method.
Its script and log are in the cleverly repository at
reviews/notebook-review/probes/treatment-rules/. The learned rule’s interval covered the true
value of its fold rules in 0.9475 of the samples, and its standard error matched the spread of
the errors (ratio 0.9918). The random offer’s interval covered 0.9375.
Try to break the result#
These checks change the data in a known way and refit each fit 20 times. The placebo test
(placebo) shuffles the recorded offers among patients, so the share offered stays the same but
the offer can have no effect: the random offer’s gain should then be near
zero, and every rule is worth the plain share who stayed home, 0.6695. The noise test
(random_common_cause) adds a pure-noise column, so the estimate should barely move. The subset
test (subset) refits on random 70% samples, so the refits should spread about as much as the
standard error predicts.
None can detect a missing confounder. For the learned rule, the noise and subset tests keep the rule each patient got and the ten folds, so they check the estimate of these rules’ value.
print(f"share who stayed home: {frame['home_30'].mean():.4f}")
columns = [
"test",
"original",
"refuted_mean",
"refuted_sd",
"statistic_name",
"statistic",
"verdict",
]
refutations = {}
for label, fit, name in (
("random offer's gain", random_fit, RANDOM_OFFER),
("learned rule's value", learned, "ey_learned_rule[learned rule]"),
):
refutations[label] = fit.diagnostics.refute(
estimand=name, tests=("placebo", "subset", "random_common_cause"), random_state=61
)
print(label)
print(refutations[label].to_frame()[columns].round(4).to_string(index=False))
share who stayed home: 0.6695
random offer's gain
test original refuted_mean refuted_sd statistic_name statistic verdict
placebo 0.0262 0.0013 0.0067 t 0.8566 descriptive
subset 0.0262 0.0263 0.0048 scatter ratio rho 0.9421 descriptive
random_common_cause 0.0262 0.0264 0.0003 paired shift in standard errors 0.0230 descriptive
learned rule's value
test original refuted_mean refuted_sd statistic_name statistic verdict
placebo 0.7174 0.6692 0.0139 t -0.1006 descriptive
subset 0.7174 0.7161 0.0081 scatter ratio rho 0.9116 descriptive
random_common_cause 0.7174 0.7175 0.0005 paired shift in standard errors 0.0033 descriptive
With shuffled offers, the random offer’s gain averages near zero and the rules are worth about the
plain share who stayed home; the t column, each placebo mean’s distance from that expected value
in standard errors of the 20 refits’ mean, is below 1 for both. The noise column barely moves either
estimate: the paired shift, its move in standard errors, is near 0. The subset refits spread about
as the standard error predicts: the scatter ratio, the spread divided by the predicted spread, is
near 1 for both, and 20 refits leave wide room around 1.
The verdict reads descriptive: cleverly gives a pass or fail only when a simulation study backs
the check for this kind of fit, and here none does, so you judge the numbers.
The point-treatment example also tests the method on outcomes with a known effect. For a learned rule, those tests have no simulated truth yet.
Where to go next#
The interventions example compares a fixed screening rule and other plans with offering to everyone. The point-treatment TMLE reference states the conditions of the learned-rule value, and the estimands guide shows what a learned-rule result holds. The examples index lists every example.