HDiagnostic accuracy · diagnostic.decision_curve
Decision curve analysis (net benefit)
Would acting on a model's predicted risks do more good than harm compared with treating everyone or no one?
Net benefit of treating people whose predicted risk is at or above a threshold probability, across a range of thresholds, for one or more models against the treat-all and treat-none strategies (Vickers & Elkin 2006), with interventions avoided per 100 people and the range of thresholds where each model is the best choice. A stated prevalence handles case–control samples.
A real result
Example “Two models missing”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
At a threshold of 10%, risk score has the highest net benefit (0.280 vs 0.259 for treating everyone): 18.9 fewer unnecessary interventions per 100.
- Net benefit — p_base
- 0.2641
- Net benefit — risk score
- 0.2802
- Net benefit — treat all
- 0.2593
Plots
View data
| Net benefit | Strategy | Threshold probability |
|---|---|---|
| 0.3266 | p_base | 0.0100 |
| 0.3197 | p_base | 0.0200 |
| 0.3128 | p_base | 0.0300 |
| 0.3060 | p_base | 0.0400 |
| 0.2992 | p_base | 0.0500 |
| 0.2928 | p_base | 0.0600 |
| 0.2838 | p_base | 0.0700 |
| 0.2800 | p_base | 0.0800 |
| 0.2728 | p_base | 0.0900 |
| 0.2641 | p_base | 0.1000 |
| 0.2621 | p_base | 0.1100 |
| 0.2590 | p_base | 0.1200 |
| 0.2527 | p_base | 0.1300 |
| 0.2495 | p_base | 0.1400 |
| 0.2456 | p_base | 0.1500 |
| 0.2403 | p_base | 0.1600 |
| 0.2319 | p_base | 0.1700 |
| 0.2248 | p_base | 0.1800 |
| 0.2245 | p_base | 0.1900 |
| 0.2200 | p_base | 0.2000 |
| 0.2153 | p_base | 0.2100 |
| 0.2148 | p_base | 0.2200 |
| 0.2157 | p_base | 0.2300 |
| 0.2153 | p_base | 0.2400 |
| 0.2089 | p_base | 0.2500 |
| 0.2020 | p_base | 0.2600 |
| 0.1962 | p_base | 0.2700 |
| 0.1940 | p_base | 0.2800 |
| 0.1795 | p_base | 0.2900 |
| 0.1690 | p_base | 0.3000 |
| 0.1605 | p_base | 0.3100 |
| 0.1598 | p_base | 0.3200 |
| 0.1506 | p_base | 0.3300 |
| 0.1551 | p_base | 0.3400 |
| 0.1483 | p_base | 0.3500 |
| 0.1483 | p_base | 0.3600 |
| 0.1429 | p_base | 0.3700 |
| 0.1387 | p_base | 0.3800 |
| 0.1394 | p_base | 0.3900 |
| 0.1359 | p_base | 0.4000 |
| 0.1291 | p_base | 0.4100 |
| 0.1269 | p_base | 0.4200 |
| 0.1229 | p_base | 0.4300 |
| 0.1210 | p_base | 0.4400 |
| 0.1176 | p_base | 0.4500 |
| 0.1172 | p_base | 0.4600 |
| 0.1085 | p_base | 0.4700 |
| 0.1073 | p_base | 0.4800 |
| 0.1040 | p_base | 0.4900 |
| 0.1048 | p_base | 0.5000 |
| 0.3266 | risk score | 0.0100 |
| 0.3200 | risk score | 0.0200 |
| 0.3136 | risk score | 0.0300 |
| 0.3067 | risk score | 0.0400 |
| 0.3016 | risk score | 0.0500 |
| 0.2973 | risk score | 0.0600 |
| 0.2933 | risk score | 0.0700 |
| 0.2886 | risk score | 0.0800 |
| 0.2839 | risk score | 0.0900 |
| 0.2802 | risk score | 0.1000 |
First 60 of 200 rows.
Assumptions
- Predictions are calibrated — Net benefit reads the predictions as probabilities; check calibration (Diagnostic → Calibration) before trusting the curve.
- Plausible thresholds — Thresholds 0.01–0.5; interpret only the range someone would really act on.
At a threshold of 0.1
| Model | Net benefit | vs treat all | vs treat none | Interventions avoided / 100 | Sensitivity | Specificity | Best choice for thresholds |
|---|---|---|---|---|---|---|---|
| p_base | 0.2641 | 0.0049 | 0.2641 | 4.381 | 0.9600 | 0.2457 | 0.03–0.5 |
| risk score | 0.2802 | 0.0210 | 0.2802 | 18.857 | 0.9829 | 0.3600 | 0.02–0.5 |
Net benefit = TP/n − FP/n × t/(1 − t): true positives per person, minus false positives weighted by the odds at the threshold.
Net benefit by threshold
| Threshold | Treat all | p_base | risk score |
|---|---|---|---|
| 0.0100 | 0.3266 | 0.3266 | 0.3266 |
| 0.0200 | 0.3197 | 0.3197 | 0.3200 |
| 0.0300 | 0.3127 | 0.3128 | 0.3136 |
| 0.0400 | 0.3056 | 0.3060 | 0.3067 |
| 0.0500 | 0.2982 | 0.2992 | 0.3016 |
| 0.0600 | 0.2908 | 0.2928 | 0.2973 |
| 0.0700 | 0.2832 | 0.2838 | 0.2933 |
| 0.0800 | 0.2754 | 0.2800 | 0.2886 |
| 0.0900 | 0.2674 | 0.2728 | 0.2839 |
| 0.1000 | 0.2593 | 0.2641 | 0.2802 |
| 0.1100 | 0.2509 | 0.2621 | 0.2760 |
| 0.1200 | 0.2424 | 0.2590 | 0.2700 |
| 0.1300 | 0.2337 | 0.2527 | 0.2656 |
| 0.1400 | 0.2248 | 0.2495 | 0.2642 |
| 0.1500 | 0.2157 | 0.2456 | 0.2559 |
| 0.1600 | 0.2063 | 0.2403 | 0.2539 |
| 0.1700 | 0.1968 | 0.2319 | 0.2432 |
| 0.1800 | 0.1870 | 0.2248 | 0.2418 |
| 0.1900 | 0.1770 | 0.2245 | 0.2341 |
| 0.2000 | 0.1667 | 0.2200 | 0.2276 |
| 0.2100 | 0.1561 | 0.2153 | 0.2262 |
| 0.2200 | 0.1453 | 0.2148 | 0.2245 |
| 0.2300 | 0.1342 | 0.2157 | 0.2188 |
| 0.2400 | 0.1228 | 0.2153 | 0.2156 |
| 0.2500 | 0.1111 | 0.2089 | 0.2114 |
| 0.2600 | 0.0991 | 0.2020 | 0.2087 |
| 0.2700 | 0.0868 | 0.1962 | 0.2076 |
| 0.2800 | 0.0741 | 0.1940 | 0.2015 |
| 0.2900 | 0.0610 | 0.1795 | 0.1991 |
| 0.3000 | 0.0476 | 0.1690 | 0.1965 |
| 0.3100 | 0.0338 | 0.1605 | 0.1904 |
| 0.3200 | 0.0196 | 0.1598 | 0.1862 |
| 0.3300 | 0.0050 | 0.1506 | 0.1773 |
| 0.3400 | −0.0101 | 0.1551 | 0.1731 |
| 0.3500 | −0.0256 | 0.1483 | 0.1642 |
| 0.3600 | −0.0417 | 0.1483 | 0.1623 |
| 0.3700 | −0.0582 | 0.1429 | 0.1571 |
| 0.3800 | −0.0753 | 0.1387 | 0.1549 |
| 0.3900 | −0.0929 | 0.1394 | 0.1544 |
| 0.4000 | −0.1111 | 0.1359 | 0.1537 |
First 40 of 50 rows.
- 7 of 532 rows were left out because a value was missing.
- Event: diabetic = true; a person is treated when the predicted risk is at least the threshold. Prevalence from the sample: 0.333.
At a threshold of 10%, risk score has the highest net benefit (0.280 vs 0.259 for treating everyone): 18.9 fewer unnecessary interventions per 100.
- Net benefit — p_base
- 0.2641
- Net benefit — risk score
- 0.2802
- Net benefit — treat all
- 0.2593
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Predictions are calibrated — Net benefit reads the predictions as probabilities; check calibration (Diagnostic → Calibration) before trusting the curve.
- Plausible thresholds — Thresholds 0.01–0.5; interpret only the range someone would really act on.
At a threshold of 0.1
| Model | Net benefit | vs treat all | vs treat none | Interventions avoided / 100 | Sensitivity | Specificity | Best choice for thresholds |
|---|---|---|---|---|---|---|---|
| p_base | 0.2641 | 0.0049 | 0.2641 | 4.381 | 0.9600 | 0.2457 | 0.03–0.5 |
| risk score | 0.2802 | 0.0210 | 0.2802 | 18.857 | 0.9829 | 0.3600 | 0.02–0.5 |
Net benefit = TP/n − FP/n × t/(1 − t): true positives per person, minus false positives weighted by the odds at the threshold.
Net benefit by threshold
| Threshold | Treat all | p_base | risk score |
|---|---|---|---|
| 0.0100 | 0.3266 | 0.3266 | 0.3266 |
| 0.0200 | 0.3197 | 0.3197 | 0.3200 |
| 0.0300 | 0.3127 | 0.3128 | 0.3136 |
| 0.0400 | 0.3056 | 0.3060 | 0.3067 |
| 0.0500 | 0.2982 | 0.2992 | 0.3016 |
| 0.0600 | 0.2908 | 0.2928 | 0.2973 |
| 0.0700 | 0.2832 | 0.2838 | 0.2933 |
| 0.0800 | 0.2754 | 0.2800 | 0.2886 |
| 0.0900 | 0.2674 | 0.2728 | 0.2839 |
| 0.1000 | 0.2593 | 0.2641 | 0.2802 |
| 0.1100 | 0.2509 | 0.2621 | 0.2760 |
| 0.1200 | 0.2424 | 0.2590 | 0.2700 |
| 0.1300 | 0.2337 | 0.2527 | 0.2656 |
| 0.1400 | 0.2248 | 0.2495 | 0.2642 |
| 0.1500 | 0.2157 | 0.2456 | 0.2559 |
| 0.1600 | 0.2063 | 0.2403 | 0.2539 |
| 0.1700 | 0.1968 | 0.2319 | 0.2432 |
| 0.1800 | 0.1870 | 0.2248 | 0.2418 |
| 0.1900 | 0.1770 | 0.2245 | 0.2341 |
| 0.2000 | 0.1667 | 0.2200 | 0.2276 |
| 0.2100 | 0.1561 | 0.2153 | 0.2262 |
| 0.2200 | 0.1453 | 0.2148 | 0.2245 |
| 0.2300 | 0.1342 | 0.2157 | 0.2188 |
| 0.2400 | 0.1228 | 0.2153 | 0.2156 |
| 0.2500 | 0.1111 | 0.2089 | 0.2114 |
| 0.2600 | 0.0991 | 0.2020 | 0.2087 |
| 0.2700 | 0.0868 | 0.1962 | 0.2076 |
| 0.2800 | 0.0741 | 0.1940 | 0.2015 |
| 0.2900 | 0.0610 | 0.1795 | 0.1991 |
| 0.3000 | 0.0476 | 0.1690 | 0.1965 |
| 0.3100 | 0.0338 | 0.1605 | 0.1904 |
| 0.3200 | 0.0196 | 0.1598 | 0.1862 |
| 0.3300 | 0.0050 | 0.1506 | 0.1773 |
| 0.3400 | −0.0101 | 0.1551 | 0.1731 |
| 0.3500 | −0.0256 | 0.1483 | 0.1642 |
| 0.3600 | −0.0417 | 0.1483 | 0.1623 |
| 0.3700 | −0.0582 | 0.1429 | 0.1571 |
| 0.3800 | −0.0753 | 0.1387 | 0.1549 |
| 0.3900 | −0.0929 | 0.1394 | 0.1544 |
| 0.4000 | −0.1111 | 0.1359 | 0.1537 |
First 40 of 50 rows.
- 7 of 532 rows were left out because a value was missing.
- Event: diabetic = true; a person is treated when the predicted risk is at least the threshold. Prevalence from the sample: 0.333.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Two models missings5_risk · outcome: diabetic · predictors: p_base, risk score
- Overfit wide ranges5_risk · outcome: type · predictors: p_base, p_overfit
- Case control prevalences5_risk · outcome: diabetic · predictors: lp_full
- Ties groupss5_ties · outcome: event · predictors: p_group, p_edge
- Degenerate n1s5_risk · outcome: diabetic · predictors: p_base, risk score
- Degenerate tiess5_risk · outcome: diabetic · predictors: p_base, risk score
In the guides
Where it sits in the decision guides
- Multiple predictors: logistic / ML · Statistics Guide · H — Diagnostic accuracy
- PR curves, calibration, decision curves · Statistics Guide · H — Diagnostic accuracy
- Probabilistic forecasting (Bayesian, deep ensembles) · DS & ML Decision Guide · Predict — forecast or classify outcomes
What you need
- Observed outcomecategorical / boolean · 1 column · 2–2 levels
- What happened (two levels).
- Predicted risksnumeric · 1–6 columns
- One column of predicted risks per model to compare.
Choices you make
hypothesis
- Event leveldefault —
The outcome level the risks predict (default the last stored level — true for true/false columns).
- Scale of the predictionsdefault probability
The units of your prediction column: probabilities, percentages or log-odds. All are converted to probabilities.
- Probability (0–1)(default) — Your column holds probabilities from 0 to 1, so nothing is converted.
- Percent (0–100) — Your column holds percentages from 0 to 100, which are divided by 100.
- Log-odds (linear predictor) — Your column holds log-odds, such as a model's linear predictor, which are converted to probabilities.
- Decision threshold of interestdefault 0.1
The risk at which you would act (treat, refer, investigate) — it encodes how many false positives one true positive is worth (odds t/(1 − t)).
plots
- Lowest threshold plotteddefault 0.01
Lowest risk threshold on the decision curve.
- Highest threshold plotteddefault 0.5
Highest risk threshold on the decision curve. Keep it within the range where decisions are realistic.
- Threshold stepdefault 0.01
Spacing between thresholds on the decision curve.
statistics
- Population prevalencedefault —
Set it for case–control samples, where the sample's event rate is fixed by design.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Predictions are calibrated
Net benefit treats the predicted risk as a probability; check calibration first — a miscalibrated model can show a misleading net benefit.
Plausible thresholds
Read the curve only over thresholds someone would really use; a model is useful where its curve lies above both treat-all and treat-none.
What it reports
- n
- How many independent units the analysis used; it sets precision and power.
- n_events
- How many independent units the analysis used; it sets precision and power.
- prevalence
- How common the condition is in the population tested; it drives predictive values.
- positive_level
- Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
- threshold
- The probability above which the model predicts the positive class; 0.5 is rarely the best choice.
- nb_all_at
- True positives per person, minus false positives per person weighted by the odds at the decision threshold.
- best_predictor
- The predictor column with the highest net benefit at the chosen threshold; a tie goes to the one listed first.
- best_nb
- True positives per person, minus false positives per person weighted by the odds at the decision threshold.
- best_avoided
- True positives per person, minus false positives per person weighted by the odds at the decision threshold.
- n_thresholds
- How many independent units the analysis used; it sets precision and power.
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Both engines use the codesplash net-benefit twin (treat when risk ≥ t); R's dcurves::dca computes the same net benefit.
The exact script CodeSplash ran for example “Two models missing” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Decision curve analysis (net benefit)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method diagnostic.decision_curve 1.0.1 · spec f919fe8cdcdb6676
# Dataset: s5_risk (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.stats import calibration as cal # net benefit, threshold grid (twins of codesplashr cs_cal_*)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/s5_risk.parquet", columns=["diabetic", "p_base", "risk score"])
n_input = len(df)
df["diabetic"] = pd.Categorical(df["diabetic"], categories=["false", "true"]) # stored level order
df = df.dropna(subset=["diabetic", "p_base", "risk score"]) # listwise deletion over the analysis columns
df["diabetic"] = df["diabetic"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["diabetic", "p_base", "risk score"]) # infinite values stop the run (registry/errors.yaml)
# %% Predictions
yc = "diabetic"
predictors = ["p_base", "risk score"]
y_levels = ["false", "true"] # stored level order
event = y_levels[-1] # default: the last level ("true")
y = (df[yc].astype(str) == event).to_numpy()
scale = "probability"
risks = {}
for c in predictors:
raw = df[c].to_numpy(dtype=float)
p = raw / 100.0 if scale == "percent" else (1.0 / (1.0 + np.exp(-raw)) if scale == "logit" else raw)
n_outside = int(np.sum((p < 0) | (p > 1)))
if n_outside:
cs.cs_error("CS_E_INVALID_VALUES", column=c, requirement="a risk between 0 and 1 on the chosen scale (percent or log-odds otherwise)", count=n_outside)
risks[c] = p
n, n_events = len(y), int(y.sum())
if n_events == 0 or n_events == n:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=yc, min=2, k=1) # needs events and non-events
prevalence = None # None: the sample's event rate
t_key = 0.1
ts = cal.thresholds(0.01, 0.5, 0.01)
ts = ts[ts < 1]
# %% Net benefit
curves = {c: cal.net_benefit(y, p, ts, prevalence) for c, p in risks.items()}
at_key = {c: cal.net_benefit(y, p, [t_key], prevalence) for c, p in risks.items()}
pi = next(iter(at_key.values()))["prevalence"]
odds_key = t_key / (1 - t_key)
nb_all_at = float(pi - (1 - pi) * odds_key)
values = {"n": n, "n_events": n_events, "prevalence": pi, "positive_level": event, "threshold": t_key, "nb_all_at": nb_all_at,
"n_thresholds": len(ts)}
rows_key = []
for c in predictors:
nb = float(at_key[c]["nb"][0])
avoided = (nb - nb_all_at) / odds_key * 100
tp, fp = int(at_key[c]["tp"][0]), int(at_key[c]["fp"][0])
cur = curves[c]
best = (cur["nb"] > np.maximum(cur["nb_all"], 0.0))
useful_low = float(ts[best][0]) if best.any() else None
useful_high = float(ts[best][-1]) if best.any() else None
values.update({f"nb[{c}]": nb, f"avoided[{c}]": avoided, f"useful_low[{c}]": useful_low, f"useful_high[{c}]": useful_high})
rows_key.append({"model": c, "nb": nb, "diff_all": nb - nb_all_at, "diff_none": nb, "avoided": avoided,
"sensitivity": tp / n_events, "specificity": 1 - fp / (n - n_events),
"useful": (f"{useful_low:g}–{useful_high:g}" if useful_low is not None else "none")})
best_c = max(predictors, key=lambda c: (values[f"nb[{c}]"], -predictors.index(c))) # ties: the first listed
values.update({"best_predictor": best_c, "best_nb": values[f"nb[{best_c}]"], "best_avoided": values[f"avoided[{best_c}]"]})
# %% Assumptions
assumptions = [
{"key": "calibration", "label": "Predictions are calibrated", "status": "info",
"detail": "Net benefit reads the predictions as probabilities; check calibration (Diagnostic → Calibration) before trusting the curve."},
{"key": "threshold_range", "label": "Plausible thresholds", "status": "info",
"detail": f"Thresholds {ts[0]:g}–{ts[-1]:g}; interpret only the range someone would really act on."},
]
if values["best_nb"] <= max(nb_all_at, 0.0):
warnings.append(f"At a threshold of {t_key:g} no model beats both treating everyone and treating no one.")
# %% Result
strategy, thr_col, nb_col = [], [], []
for c in predictors:
strategy += [c] * len(ts)
thr_col += ts.tolist()
nb_col += curves[c]["nb"].tolist()
strategy += ["Treat all"] * len(ts) + ["Treat none"] * len(ts)
thr_col += ts.tolist() * 2
nb_col += curves[predictors[0]]["nb_all"].tolist() + [0.0] * len(ts)
grid_rows = [{"threshold": float(t), "treat_all": float(curves[predictors[0]]["nb_all"][i]),
**{f"nb_{j}": float(curves[c]["nb"][i]) for j, c in enumerate(predictors)}} for i, t in enumerate(ts)]
summary = (f"At a threshold of {t_key:.0%}, {best_c} has the highest net benefit ({values['best_nb']:.3f} vs {nb_all_at:.3f} for treating everyone): "
f"{values['best_avoided']:.1f} fewer unnecessary interventions per 100.")
cs.publish({
"method": "diagnostic.decision_curve",
"methodVersion": "1.0.1",
"title": "Decision curve analysis",
"engine": cs.engine_info("pandas", "numpy"),
"n": n,
"summary": summary,
"statistics": [{"key": f"nb[{c}]", "label": f"Net benefit — {c}", "value": values[f"nb[{c}]"]} for c in predictors]
+ [{"key": "nb_all_at", "label": "Net benefit — treat all", "value": nb_all_at}],
"tables": [
{"key": "at_threshold", "title": f"At a threshold of {t_key:g}", "columns": [
{"key": "model", "label": "Model", "type": "string"}, {"key": "nb", "label": "Net benefit", "type": "number"},
{"key": "diff_all", "label": "vs treat all", "type": "number"}, {"key": "diff_none", "label": "vs treat none", "type": "number"},
{"key": "avoided", "label": "Interventions avoided / 100", "type": "number"},
{"key": "sensitivity", "label": "Sensitivity", "type": "number"}, {"key": "specificity", "label": "Specificity", "type": "number"},
{"key": "useful", "label": "Best choice for thresholds", "type": "string"}],
"rows": rows_key,
"note": "Net benefit = TP/n − FP/n × t/(1 − t): true positives per person, minus false positives weighted by the odds at the threshold."},
{"key": "curve", "title": "Net benefit by threshold", "columns": [
{"key": "threshold", "label": "Threshold", "type": "number"}, {"key": "treat_all", "label": "Treat all", "type": "number"}]
+ [{"key": f"nb_{j}", "label": c, "type": "number"} for j, c in enumerate(predictors)],
"rows": grid_rows},
],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Event: {yc} = {event}; a person is treated when the predicted risk is at least the threshold. "
+ (f"Prevalence set to {pi:g} (case–control correction)." if prevalence is not None else f"Prevalence from the sample: {pi:.3f}.")],
"charts": [cs.chart("dca", "decision-curve", "Decision curve", {
"threshold": cs.col("Threshold probability", thr_col), "net_benefit": cs.col("Net benefit", nb_col),
"strategy": cs.col("Strategy", strategy, kind="categorical")})],
"values": values,
})
The exact script CodeSplash ran for example “Two models missing” · R version 4.5.1 (2025-06-13)
# Decision curve analysis (net benefit)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method diagnostic.decision_curve 1.0.1 · spec f919fe8cdcdb6676
# Dataset: s5_risk (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_cal_net_benefit, cs_cal_thresholds (same net benefit as dcurves::dca)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s5_risk.parquet", col_select = c("diabetic", "p_base", "risk score")))
n_input <- nrow(df)
df[["diabetic"]] <- factor(df[["diabetic"]], levels = c("false", "true")) # stored level order
df <- df[stats::complete.cases(df[c("diabetic", "p_base", "risk score")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("diabetic", "p_base", "risk score")) # infinite values stop the run (registry/errors.yaml)
# %% Predictions
yc <- "diabetic"
predictors <- c("p_base", "risk score")
y_levels <- c("false", "true") # stored level order
event <- y_levels[length(y_levels)] # default: the last level ("true")
y <- as.character(df[[yc]]) == event
scale <- "probability"
risks <- list()
for (c in predictors) {
raw <- as.numeric(df[[c]])
p <- if (scale == "percent") raw / 100 else if (scale == "logit") 1 / (1 + exp(-raw)) else raw
n_outside <- sum(p < 0 | p > 1)
if (n_outside > 0) cs_error("CS_E_INVALID_VALUES", column = c, requirement = "a risk between 0 and 1 on the chosen scale (percent or log-odds otherwise)", count = n_outside)
risks[[c]] <- p
}
n <- length(y)
n_events <- sum(y)
if (n_events == 0 || n_events == n) cs_error("CS_E_TOO_FEW_GROUPS", column = yc, min = 2, k = 1) # needs events and non-events
prevalence <- NULL # NULL: the sample's event rate
t_key <- 0.1
ts <- cs_cal_thresholds(0.01, 0.5, 0.01)
ts <- ts[ts < 1]
# %% Net benefit
curves <- lapply(risks, function(p) cs_cal_net_benefit(y, p, ts, prevalence))
at_key <- lapply(risks, function(p) cs_cal_net_benefit(y, p, t_key, prevalence))
pi <- at_key[[1]]$prevalence
odds_key <- t_key / (1 - t_key)
nb_all_at <- pi - (1 - pi) * odds_key
values <- list(n = n, n_events = n_events, prevalence = pi, positive_level = event, threshold = t_key, nb_all_at = nb_all_at,
n_thresholds = length(ts))
rows_key <- list()
for (c in predictors) {
nb <- at_key[[c]]$nb[1]
avoided <- (nb - nb_all_at) / odds_key * 100
tp <- at_key[[c]]$tp[1]
fp <- at_key[[c]]$fp[1]
cur <- curves[[c]]
best <- cur$nb > pmax(cur$nb_all, 0)
useful_low <- if (any(best)) ts[best][1] else NA
useful_high <- if (any(best)) ts[best][sum(best)] else NA
values[[sprintf("nb[%s]", c)]] <- nb
values[[sprintf("avoided[%s]", c)]] <- avoided
values[[sprintf("useful_low[%s]", c)]] <- useful_low
values[[sprintf("useful_high[%s]", c)]] <- useful_high
rows_key[[length(rows_key) + 1]] <- list(model = c, nb = nb, diff_all = nb - nb_all_at, diff_none = nb, avoided = avoided,
sensitivity = tp / n_events, specificity = 1 - fp / (n - n_events),
useful = if (any(best)) sprintf("%g–%g", useful_low, useful_high) else "none")
}
nbs <- vapply(predictors, function(c) values[[sprintf("nb[%s]", c)]], numeric(1))
best_c <- predictors[which.max(nbs)] # ties: the first listed
values$best_predictor <- best_c
values$best_nb <- values[[sprintf("nb[%s]", best_c)]]
values$best_avoided <- values[[sprintf("avoided[%s]", best_c)]]
# %% Assumptions
assumptions <- list(
list(key = "calibration", label = "Predictions are calibrated", status = "info",
detail = "Net benefit reads the predictions as probabilities; check calibration (Diagnostic → Calibration) before trusting the curve."),
list(key = "threshold_range", label = "Plausible thresholds", status = "info",
detail = sprintf("Thresholds %g–%g; interpret only the range someone would really act on.", ts[1], ts[length(ts)]))
)
if (values$best_nb <= max(nb_all_at, 0)) {
warnings <- c(warnings, sprintf("At a threshold of %g no model beats both treating everyone and treating no one.", t_key))
}
# %% Result
strategy <- c(rep(predictors, each = length(ts)), rep("Treat all", length(ts)), rep("Treat none", length(ts)))
thr_col <- c(rep(ts, length(predictors)), ts, ts)
nb_col <- c(unlist(lapply(predictors, function(c) curves[[c]]$nb), use.names = FALSE), curves[[1]]$nb_all, rep(0, length(ts)))
grid_rows <- lapply(seq_along(ts), function(i) {
row <- list(threshold = ts[i], treat_all = curves[[1]]$nb_all[i])
for (j in seq_along(predictors)) row[[sprintf("nb_%d", j - 1)]] <- curves[[predictors[j]]]$nb[i]
row
})
curve_cols <- c(list(list(key = "threshold", label = "Threshold", type = "number"), list(key = "treat_all", label = "Treat all", type = "number")),
lapply(seq_along(predictors), function(j) list(key = sprintf("nb_%d", j - 1), label = predictors[j], type = "number")))
summary <- sprintf("At a threshold of %.0f%%, %s has the highest net benefit (%.3f vs %.3f for treating everyone): %.1f fewer unnecessary interventions per 100.",
100 * t_key, best_c, values$best_nb, nb_all_at, values$best_avoided)
cs_publish(list(
method = "diagnostic.decision_curve",
methodVersion = "1.0.1",
title = "Decision curve analysis",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
statistics = c(lapply(predictors, function(c) list(key = sprintf("nb[%s]", c), label = sprintf("Net benefit — %s", c), value = values[[sprintf("nb[%s]", c)]])),
list(list(key = "nb_all_at", label = "Net benefit — treat all", value = nb_all_at))),
tables = list(
list(key = "at_threshold", title = sprintf("At a threshold of %g", t_key),
columns = list(list(key = "model", label = "Model", type = "string"), list(key = "nb", label = "Net benefit", type = "number"),
list(key = "diff_all", label = "vs treat all", type = "number"), list(key = "diff_none", label = "vs treat none", type = "number"),
list(key = "avoided", label = "Interventions avoided / 100", type = "number"),
list(key = "sensitivity", label = "Sensitivity", type = "number"), list(key = "specificity", label = "Specificity", type = "number"),
list(key = "useful", label = "Best choice for thresholds", type = "string")),
rows = rows_key,
note = "Net benefit = TP/n − FP/n × t/(1 − t): true positives per person, minus false positives weighted by the odds at the threshold."),
list(key = "curve", title = "Net benefit by threshold", columns = curve_cols, rows = grid_rows)
),
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(sprintf("Event: %s = %s; a person is treated when the predicted risk is at least the threshold. ", yc, event),
if (!is.null(prevalence)) sprintf("Prevalence set to %g (case–control correction).", pi) else sprintf("Prevalence from the sample: %.3f.", pi))),
charts = list(cs_chart("dca", "decision-curve", "Decision curve",
list(threshold = cs_col("Threshold probability", thr_col), net_benefit = cs_col("Net benefit", nb_col),
strategy = cs_col("Strategy", strategy, kind = "categorical")))),
values = values
))
Sources
- Vickers, A. J., & Elkin, E. B. (2006). Decision curve analysis: a novel method for evaluating prediction models. Medical Decision Making, 26, 565–574.
- Vickers, A. J., Van Calster, B., & Steyerberg, E. W. (2016). Net benefit approaches to the evaluation of prediction models, molecular markers, and diagnostic tests. BMJ, 352, i6.
- Pfeiffer, R. M., & Gail, M. H. (2020). Estimating the decision curve and its precision from three study designs. Biometrical Journal, 62, 764–776.
From the CodeSplash method registry · diagnostic.decision_curve v1.0.1.