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