Decision curves and net benefit
Would acting on a model beat treating everyone or no one? Net benefit answers in units of true positives, using the trade-off your threshold already implies.
What runs in CodeSplash
- Decision curve analysis (net benefit) Verified in Python and R
You will be able to
- Translate a risk threshold into the trade-off it implies
- Compute net benefit and compare a model with treat-all and treat-none
- Read a decision curve over the thresholds someone would really use
Read first
A better model, or a better decision?
ReadAUC and calibration describe the predictions. Neither says whether acting on them beats the obvious alternatives: treat everyone, or treat no one.
Decision curve analysisDecision curvePlots net benefit against the threshold, for a model and for treating everyone or no one. (Vickers and Elkin, 2006) answers that. You treat everyone whose predicted risk is at least a threshold , then score the result in net benefitNet benefitTrue positives per person, minus false positives per person weighted by the odds at the decision threshold.:
True positives count in full. False positives are weighted by the odds at the threshold.
The threshold is a trade
PredictPredict first
A clinician says, "I would biopsy anyone whose risk is at least 10%." How many unnecessary biopsies is she accepting for each cancer found?
Reveal
Nine. At that risk, 1 person in 10 has cancer and 9 don't, and she still acts. So one cancer found is worth nine needless biopsies to her, and that's where the weight comes from: .
A threshold is a statement of values, which is why it isn't estimated from the data.
The two default strategies
CheckpointTreat no one, and net benefit is 0. Treat everyone, and every case is a true positive and every non-case a false positive:
Check yourself
Prevalence is one third and the threshold is 10%. What is the net benefit of treating everyone? Give three decimals.
Show the answer
Answer: 0.259259259259259
1/3 − (2/3) × (1/9) = 0.333 − 0.074 = 0.259.
Read the card
In the appThese models predict diabetes. Decision threshold of interest sets the table's threshold.
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.
The exact R script · R 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
))
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.
The exact Python script · Python 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,
})
At 10%, risk score has net benefit 0.280, against 0.259 for treating everyone. That's as good as about 28 true positives per 100 people with no false positives at all. It equals 18.9 fewer unnecessary interventions per 100, for the same true positives.
Read the curve
ReadView data
| threshold probability | net benefit | strategy |
|---|---|---|
| 0.0100 | 0.1913 | Full model |
| 0.0100 | 0.1905 | Clinical score |
| 0.0100 | 0.1913 | Treat all |
| 0.0100 | 0 | Treat none |
| 0.0200 | 0.1832 | Full model |
| 0.0200 | 0.1810 | Clinical score |
| 0.0200 | 0.1830 | Treat all |
| 0.0200 | 0 | Treat none |
| 0.0300 | 0.1750 | Full model |
| 0.0300 | 0.1732 | Clinical score |
| 0.0300 | 0.1746 | Treat all |
| 0.0300 | 0 | Treat none |
| 0.0400 | 0.1676 | Full model |
| 0.0400 | 0.1648 | Clinical score |
| 0.0400 | 0.1660 | Treat all |
| 0.0400 | 0 | Treat none |
| 0.0500 | 0.1581 | Full model |
| 0.0500 | 0.1545 | Clinical score |
| 0.0500 | 0.1572 | Treat all |
| 0.0500 | 0 | Treat none |
| 0.0600 | 0.1512 | Full model |
| 0.0600 | 0.1459 | Clinical score |
| 0.0600 | 0.1482 | Treat all |
| 0.0600 | 0 | Treat none |
| 0.0700 | 0.1462 | Full model |
| 0.0700 | 0.1385 | Clinical score |
| 0.0700 | 0.1391 | Treat all |
| 0.0700 | 0 | Treat none |
| 0.0800 | 0.1384 | Full model |
| 0.0800 | 0.1306 | Clinical score |
| 0.0800 | 0.1297 | Treat all |
| 0.0800 | 0 | Treat none |
| 0.0900 | 0.1317 | Full model |
| 0.0900 | 0.1229 | Clinical score |
| 0.0900 | 0.1202 | Treat all |
| 0.0900 | 0 | Treat none |
| 0.1000 | 0.1255 | Full model |
| 0.1000 | 0.1146 | Clinical score |
| 0.1000 | 0.1104 | Treat all |
| 0.1000 | 0 | Treat none |
| 0.1100 | 0.1183 | Full model |
| 0.1100 | 0.1086 | Clinical score |
| 0.1100 | 0.1004 | Treat all |
| 0.1100 | 0 | Treat none |
| 0.1200 | 0.1146 | Full model |
| 0.1200 | 0.1026 | Clinical score |
| 0.1200 | 0.0901 | Treat all |
| 0.1200 | 0 | Treat none |
| 0.1300 | 0.1095 | Full model |
| 0.1300 | 0.0974 | Clinical score |
| 0.1300 | 0.0797 | Treat all |
| 0.1300 | 0 | Treat none |
| 0.1400 | 0.1025 | Full model |
| 0.1400 | 0.0907 | Clinical score |
| 0.1400 | 0.0690 | Treat all |
| 0.1400 | 0 | Treat none |
| 0.1500 | 0.0983 | Full model |
| 0.1500 | 0.0840 | Clinical score |
| 0.1500 | 0.0580 | Treat all |
| 0.1500 | 0 | Treat none |
First 60 of 200 rows.
- Treat none is the line at 0.
- Treat all starts near the prevalence, falls as the threshold rises, and crosses 0 when the threshold equals the prevalence.
- A model helps where its curve lies above both.
Only read the thresholds someone would really use. Set them with Lowest threshold plotted and Highest threshold plotted. A model that wins at 60% is no use if everyone would act at 10%. The table's Best choice for thresholds column gives each model's winning range.
When the risks are wrong
PredictPredict first
A model's risks are all too high, though its ranking is intact. You use a threshold of 10%. What can happen?
Reveal
Net benefit can fall, even below treat-all. People whose true risk is well under 10% now cross the line, so you treat people you meant to leave alone. Net benefit reads predicted risk as a probability, so check calibration first (Van Calster and Vickers, 2015).
When you chose the sample's mix
In the appIn a case–control sample, the event rate is your own design. Population prevalence, which is From the sample by default, lets you state the real one.
At a threshold of 5%, lp_full has the highest net benefit (0.059 vs 0.053 for treating everyone): 12.1 fewer unnecessary interventions per 100.
- Net benefit — lp_full
- 0.0590
- Net benefit — treat all
- 0.0526
Plots
View data
| Net benefit | Strategy | Threshold probability |
|---|---|---|
| 0.0909 | lp_full | 0.0100 |
| 0.0819 | lp_full | 0.0200 |
| 0.0733 | lp_full | 0.0300 |
| 0.0659 | lp_full | 0.0400 |
| 0.0590 | lp_full | 0.0500 |
| 0.0535 | lp_full | 0.0600 |
| 0.0483 | lp_full | 0.0700 |
| 0.0440 | lp_full | 0.0800 |
| 0.0396 | lp_full | 0.0900 |
| 0.0346 | lp_full | 0.1000 |
| 0.0310 | lp_full | 0.1100 |
| 0.0268 | lp_full | 0.1200 |
| 0.0229 | lp_full | 0.1300 |
| 0.0209 | lp_full | 0.1400 |
| 0.0177 | lp_full | 0.1500 |
| 0.0169 | lp_full | 0.1600 |
| 0.0105 | lp_full | 0.1700 |
| 0.0086 | lp_full | 0.1800 |
| 0.0042 | lp_full | 0.1900 |
| 0.0014 | lp_full | 0.2000 |
| 0.0021 | lp_full | 0.2100 |
| 0.0036 | lp_full | 0.2200 |
| −6.858e-5 | lp_full | 0.2300 |
| −0.0023 | lp_full | 0.2400 |
| −0.0040 | lp_full | 0.2500 |
| −0.0057 | lp_full | 0.2600 |
| −0.0053 | lp_full | 0.2700 |
| −0.0075 | lp_full | 0.2800 |
| −0.0069 | lp_full | 0.2900 |
| −0.0084 | lp_full | 0.3000 |
| −0.0126 | lp_full | 0.3100 |
| −0.0162 | lp_full | 0.3200 |
| −0.0203 | lp_full | 0.3300 |
| −0.0239 | lp_full | 0.3400 |
| −0.0279 | lp_full | 0.3500 |
| −0.0286 | lp_full | 0.3600 |
| −0.0321 | lp_full | 0.3700 |
| −0.0350 | lp_full | 0.3800 |
| −0.0337 | lp_full | 0.3900 |
| −0.0308 | lp_full | 0.4000 |
| −0.0302 | lp_full | 0.4100 |
| −0.0323 | lp_full | 0.4200 |
| −0.0293 | lp_full | 0.4300 |
| −0.0284 | lp_full | 0.4400 |
| −0.0321 | lp_full | 0.4500 |
| −0.0345 | lp_full | 0.4600 |
| −0.0323 | lp_full | 0.4700 |
| −0.0367 | lp_full | 0.4800 |
| −0.0407 | lp_full | 0.4900 |
| −0.0384 | lp_full | 0.5000 |
| 0.0909 | Treat all | 0.0100 |
| 0.0816 | Treat all | 0.0200 |
| 0.0722 | Treat all | 0.0300 |
| 0.0625 | Treat all | 0.0400 |
| 0.0526 | Treat all | 0.0500 |
| 0.0426 | Treat all | 0.0600 |
| 0.0323 | Treat all | 0.0700 |
| 0.0217 | Treat all | 0.0800 |
| 0.0110 | Treat all | 0.0900 |
| 0 | Treat all | 0.1000 |
First 60 of 150 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.05
| Model | Net benefit | vs treat all | vs treat none | Interventions avoided / 100 | Sensitivity | Specificity | Best choice for thresholds |
|---|---|---|---|---|---|---|---|
| lp_full | 0.0590 | 0.0064 | 0.0590 | 12.110 | 0.9944 | 0.1465 | 0.02–0.22 |
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 | lp_full |
|---|---|---|
| 0.0100 | 0.0909 | 0.0909 |
| 0.0200 | 0.0816 | 0.0819 |
| 0.0300 | 0.0722 | 0.0733 |
| 0.0400 | 0.0625 | 0.0659 |
| 0.0500 | 0.0526 | 0.0590 |
| 0.0600 | 0.0426 | 0.0535 |
| 0.0700 | 0.0323 | 0.0483 |
| 0.0800 | 0.0217 | 0.0440 |
| 0.0900 | 0.0110 | 0.0396 |
| 0.1000 | 0 | 0.0346 |
| 0.1100 | −0.0112 | 0.0310 |
| 0.1200 | −0.0227 | 0.0268 |
| 0.1300 | −0.0345 | 0.0229 |
| 0.1400 | −0.0465 | 0.0209 |
| 0.1500 | −0.0588 | 0.0177 |
| 0.1600 | −0.0714 | 0.0169 |
| 0.1700 | −0.0843 | 0.0105 |
| 0.1800 | −0.0976 | 0.0086 |
| 0.1900 | −0.1111 | 0.0042 |
| 0.2000 | −0.1250 | 0.0014 |
| 0.2100 | −0.1392 | 0.0021 |
| 0.2200 | −0.1538 | 0.0036 |
| 0.2300 | −0.1688 | −6.858e-5 |
| 0.2400 | −0.1842 | −0.0023 |
| 0.2500 | −0.2000 | −0.0040 |
| 0.2600 | −0.2162 | −0.0057 |
| 0.2700 | −0.2329 | −0.0053 |
| 0.2800 | −0.2500 | −0.0075 |
| 0.2900 | −0.2676 | −0.0069 |
| 0.3000 | −0.2857 | −0.0084 |
| 0.3100 | −0.3043 | −0.0126 |
| 0.3200 | −0.3235 | −0.0162 |
| 0.3300 | −0.3433 | −0.0203 |
| 0.3400 | −0.3636 | −0.0239 |
| 0.3500 | −0.3846 | −0.0279 |
| 0.3600 | −0.4063 | −0.0286 |
| 0.3700 | −0.4286 | −0.0321 |
| 0.3800 | −0.4516 | −0.0350 |
| 0.3900 | −0.4754 | −0.0337 |
| 0.4000 | −0.5000 | −0.0308 |
First 40 of 50 rows.
- Event: diabetic = true; a person is treated when the predicted risk is at least the threshold. Prevalence set to 0.1 (case–control correction).
The exact R script · R 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 99f4eff655355c3b
# 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", "lp_full")))
n_input <- nrow(df)
df[["diabetic"]] <- factor(df[["diabetic"]], levels = c("false", "true")) # stored level order
df <- df[stats::complete.cases(df[c("diabetic", "lp_full")]), , 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", "lp_full")) # infinite values stop the run (registry/errors.yaml)
# %% Predictions
yc <- "diabetic"
predictors <- c("lp_full")
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 <- "logit"
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 <- 0.1 # NULL: the sample's event rate
t_key <- 0.05
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
))
At a threshold of 5%, lp_full has the highest net benefit (0.059 vs 0.053 for treating everyone): 12.1 fewer unnecessary interventions per 100.
- Net benefit — lp_full
- 0.0590
- Net benefit — treat all
- 0.0526
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.05
| Model | Net benefit | vs treat all | vs treat none | Interventions avoided / 100 | Sensitivity | Specificity | Best choice for thresholds |
|---|---|---|---|---|---|---|---|
| lp_full | 0.0590 | 0.0064 | 0.0590 | 12.110 | 0.9944 | 0.1465 | 0.02–0.22 |
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 | lp_full |
|---|---|---|
| 0.0100 | 0.0909 | 0.0909 |
| 0.0200 | 0.0816 | 0.0819 |
| 0.0300 | 0.0722 | 0.0733 |
| 0.0400 | 0.0625 | 0.0659 |
| 0.0500 | 0.0526 | 0.0590 |
| 0.0600 | 0.0426 | 0.0535 |
| 0.0700 | 0.0323 | 0.0483 |
| 0.0800 | 0.0217 | 0.0440 |
| 0.0900 | 0.0110 | 0.0396 |
| 0.1000 | 0 | 0.0346 |
| 0.1100 | −0.0112 | 0.0310 |
| 0.1200 | −0.0227 | 0.0268 |
| 0.1300 | −0.0345 | 0.0229 |
| 0.1400 | −0.0465 | 0.0209 |
| 0.1500 | −0.0588 | 0.0177 |
| 0.1600 | −0.0714 | 0.0169 |
| 0.1700 | −0.0843 | 0.0105 |
| 0.1800 | −0.0976 | 0.0086 |
| 0.1900 | −0.1111 | 0.0042 |
| 0.2000 | −0.1250 | 0.0014 |
| 0.2100 | −0.1392 | 0.0021 |
| 0.2200 | −0.1538 | 0.0036 |
| 0.2300 | −0.1688 | −6.858e-5 |
| 0.2400 | −0.1842 | −0.0023 |
| 0.2500 | −0.2000 | −0.0040 |
| 0.2600 | −0.2162 | −0.0057 |
| 0.2700 | −0.2329 | −0.0053 |
| 0.2800 | −0.2500 | −0.0075 |
| 0.2900 | −0.2676 | −0.0069 |
| 0.3000 | −0.2857 | −0.0084 |
| 0.3100 | −0.3043 | −0.0126 |
| 0.3200 | −0.3235 | −0.0162 |
| 0.3300 | −0.3433 | −0.0203 |
| 0.3400 | −0.3636 | −0.0239 |
| 0.3500 | −0.3846 | −0.0279 |
| 0.3600 | −0.4063 | −0.0286 |
| 0.3700 | −0.4286 | −0.0321 |
| 0.3800 | −0.4516 | −0.0350 |
| 0.3900 | −0.4754 | −0.0337 |
| 0.4000 | −0.5000 | −0.0308 |
First 40 of 50 rows.
- Event: diabetic = true; a person is treated when the predicted risk is at least the threshold. Prevalence set to 0.1 (case–control correction).
The exact Python script · Python 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 99f4eff655355c3b
# 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", "lp_full"])
n_input = len(df)
df["diabetic"] = pd.Categorical(df["diabetic"], categories=["false", "true"]) # stored level order
df = df.dropna(subset=["diabetic", "lp_full"]) # 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", "lp_full"]) # infinite values stop the run (registry/errors.yaml)
# %% Predictions
yc = "diabetic"
predictors = ["lp_full"]
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 = "logit"
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 = 0.1 # None: the sample's event rate
t_key = 0.05
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,
})
Sensitivity and specificity still come from the sample, and the prevalence you set weights them: . With 10% prevalence and a threshold of 5%, the model scores 0.059 and treat-all 0.053.
Same sum, two dialects
ReadNet benefit is short enough to write by hand, which is the best way to trust it.
import pandas as pd
df = pd.read_csv("s5_risk.csv").dropna(subset=["risk score"])
y, p = df["diabetic"], df["risk score"]
t = 0.10
odds = t / (1 - t)
tp = (y & (p >= t)).sum()
fp = (~y & (p >= t)).sum()
n, prevalence = len(y), y.mean()
print(tp / n - fp / n * odds, prevalence - (1 - prevalence) * odds)df <- read.csv("s5_risk.csv", check.names = FALSE)
df <- df[!is.na(df[["risk score"]]), ]
y <- df$diabetic == "true"; p <- df[["risk score"]]
t <- 0.10
odds <- t / (1 - t)
tp <- sum(y & p >= t)
fp <- sum(!y & p >= t)
n <- length(y); prevalence <- mean(y)
c(model = tp / n - fp / n * odds, treat_all = prevalence - (1 - prevalence) * odds)Check your understanding
CheckpointCheck yourself
Among 100 people at a threshold of 10%, a model treats 20 true positives and 30 false positives. What is its net benefit? Give three decimals.
Show the answer
Answer: 0.167
20/100 − (30/100) × (1/9) = 0.200 − 0.033 = 0.167.
Check yourself
Someone acts at a threshold of 20%. How many false positives are they accepting per true positive?
Show the answer
Answer: 4
The odds at 20% are 1 to 4, so four false positives for each true positive.
Check yourself
A model's curve lies above both default lines between 15% and 40%, and on treat-all below 15%. Clinicians act at about 5%. What should you conclude?
Show the answer
Answer: b
Only the thresholds in real use count. The threshold reflects values, and you don't adjust it to favor the model.
Check yourself
Where does the treat-all line cross zero?
Show the answer
Answer: b
Setting π − (1 − π) · t/(1 − t) = 0 gives t = π.
Recap
Recap- A threshold states a trade: false positives per true positive.
- Net benefit scores a model in true positives, against treat-all and treat-none.
- A model is useful only where its curve is above both, at thresholds in real use.
- Check calibration first, and set the prevalence when you chose the sample's mix.
Concepts in this lesson