Skip to content

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.

Advanced ~13 min10 steps

What runs in CodeSplash

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

01

A better model, or a better decision?

Read

AUC 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 tt, then score the result in net benefitNet benefitTrue positives per person, minus false positives per person weighted by the odds at the decision threshold.:

NB(t)=TPn−FPn⋅t1−t\text{NB}(t) = \frac{TP}{n} - \frac{FP}{n} \cdot \frac{t}{1 - t}

True positives count in full. False positives are weighted by the odds at the threshold.

02

The threshold is a trade

Predict

Predict 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?

191090
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: t/(1−t)=1/9t / (1 - t) = 1/9.

A threshold is a statement of values, which is why it isn't estimated from the data.

03

The two default strategies

Checkpoint

Treat no one, and net benefit is 0. Treat everyone, and every case is a true positive and every non-case a false positive:

NBall(t)=π−(1−π)t1−t\text{NB}_{\text{all}}(t) = \pi - (1 - \pi)\frac{t}{1 - t}

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.

04

Read the card

In the app

These models predict diabetes. Decision threshold of interest sets the table's threshold.

Decision curve analysisRecorded · Python and R agreeRecorded 2026-11-17 · 18 values compared
R

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

Decision curveAcross the range of risk thresholds a clinician might use, does acting on the model do more good than treating everyone or no one?
View data
Net benefitStrategyThreshold probability
0.3266p_base0.0100
0.3197p_base0.0200
0.3128p_base0.0300
0.3060p_base0.0400
0.2992p_base0.0500
0.2928p_base0.0600
0.2838p_base0.0700
0.2800p_base0.0800
0.2728p_base0.0900
0.2641p_base0.1000
0.2621p_base0.1100
0.2590p_base0.1200
0.2527p_base0.1300
0.2495p_base0.1400
0.2456p_base0.1500
0.2403p_base0.1600
0.2319p_base0.1700
0.2248p_base0.1800
0.2245p_base0.1900
0.2200p_base0.2000
0.2153p_base0.2100
0.2148p_base0.2200
0.2157p_base0.2300
0.2153p_base0.2400
0.2089p_base0.2500
0.2020p_base0.2600
0.1962p_base0.2700
0.1940p_base0.2800
0.1795p_base0.2900
0.1690p_base0.3000
0.1605p_base0.3100
0.1598p_base0.3200
0.1506p_base0.3300
0.1551p_base0.3400
0.1483p_base0.3500
0.1483p_base0.3600
0.1429p_base0.3700
0.1387p_base0.3800
0.1394p_base0.3900
0.1359p_base0.4000
0.1291p_base0.4100
0.1269p_base0.4200
0.1229p_base0.4300
0.1210p_base0.4400
0.1176p_base0.4500
0.1172p_base0.4600
0.1085p_base0.4700
0.1073p_base0.4800
0.1040p_base0.4900
0.1048p_base0.5000
0.3266risk score0.0100
0.3200risk score0.0200
0.3136risk score0.0300
0.3067risk score0.0400
0.3016risk score0.0500
0.2973risk score0.0600
0.2933risk score0.0700
0.2886risk score0.0800
0.2839risk score0.0900
0.2802risk score0.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

ModelNet benefitvs treat allvs treat noneInterventions avoided / 100SensitivitySpecificityBest choice for thresholds
p_base0.26410.00490.26414.3810.96000.24570.03–0.5
risk score0.28020.02100.280218.8570.98290.36000.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

ThresholdTreat allp_baserisk score
0.01000.32660.32660.3266
0.02000.31970.31970.3200
0.03000.31270.31280.3136
0.04000.30560.30600.3067
0.05000.29820.29920.3016
0.06000.29080.29280.2973
0.07000.28320.28380.2933
0.08000.27540.28000.2886
0.09000.26740.27280.2839
0.10000.25930.26410.2802
0.11000.25090.26210.2760
0.12000.24240.25900.2700
0.13000.23370.25270.2656
0.14000.22480.24950.2642
0.15000.21570.24560.2559
0.16000.20630.24030.2539
0.17000.19680.23190.2432
0.18000.18700.22480.2418
0.19000.17700.22450.2341
0.20000.16670.22000.2276
0.21000.15610.21530.2262
0.22000.14530.21480.2245
0.23000.13420.21570.2188
0.24000.12280.21530.2156
0.25000.11110.20890.2114
0.26000.09910.20200.2087
0.27000.08680.19620.2076
0.28000.07410.19400.2015
0.29000.06100.17950.1991
0.30000.04760.16900.1965
0.31000.03380.16050.1904
0.32000.01960.15980.1862
0.33000.00500.15060.1773
0.3400−0.01010.15510.1731
0.3500−0.02560.14830.1642
0.3600−0.04170.14830.1623
0.3700−0.05820.14290.1571
0.3800−0.07530.13870.1549
0.3900−0.09290.13940.1544
0.4000−0.11110.13590.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
))
Python

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

ModelNet benefitvs treat allvs treat noneInterventions avoided / 100SensitivitySpecificityBest choice for thresholds
p_base0.26410.00490.26414.3810.96000.24570.03–0.5
risk score0.28020.02100.280218.8570.98290.36000.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

ThresholdTreat allp_baserisk score
0.01000.32660.32660.3266
0.02000.31970.31970.3200
0.03000.31270.31280.3136
0.04000.30560.30600.3067
0.05000.29820.29920.3016
0.06000.29080.29280.2973
0.07000.28320.28380.2933
0.08000.27540.28000.2886
0.09000.26740.27280.2839
0.10000.25930.26410.2802
0.11000.25090.26210.2760
0.12000.24240.25900.2700
0.13000.23370.25270.2656
0.14000.22480.24950.2642
0.15000.21570.24560.2559
0.16000.20630.24030.2539
0.17000.19680.23190.2432
0.18000.18700.22480.2418
0.19000.17700.22450.2341
0.20000.16670.22000.2276
0.21000.15610.21530.2262
0.22000.14530.21480.2245
0.23000.13420.21570.2188
0.24000.12280.21530.2156
0.25000.11110.20890.2114
0.26000.09910.20200.2087
0.27000.08680.19620.2076
0.28000.07410.19400.2015
0.29000.06100.17950.1991
0.30000.04760.16900.1965
0.31000.03380.16050.1904
0.32000.01960.15980.1862
0.33000.00500.15060.1773
0.3400−0.01010.15510.1731
0.3500−0.02560.14830.1642
0.3600−0.04170.14830.1623
0.3700−0.05820.14290.1571
0.3800−0.07530.13870.1549
0.3900−0.09290.13940.1544
0.4000−0.11110.13590.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.

05

Read the curve

Read
Decision curveAcross the range of risk thresholds a clinician might use, does acting on the model do more good than treating everyone or no one?
View data
threshold probabilitynet benefitstrategy
0.01000.1913Full model
0.01000.1905Clinical score
0.01000.1913Treat all
0.01000Treat none
0.02000.1832Full model
0.02000.1810Clinical score
0.02000.1830Treat all
0.02000Treat none
0.03000.1750Full model
0.03000.1732Clinical score
0.03000.1746Treat all
0.03000Treat none
0.04000.1676Full model
0.04000.1648Clinical score
0.04000.1660Treat all
0.04000Treat none
0.05000.1581Full model
0.05000.1545Clinical score
0.05000.1572Treat all
0.05000Treat none
0.06000.1512Full model
0.06000.1459Clinical score
0.06000.1482Treat all
0.06000Treat none
0.07000.1462Full model
0.07000.1385Clinical score
0.07000.1391Treat all
0.07000Treat none
0.08000.1384Full model
0.08000.1306Clinical score
0.08000.1297Treat all
0.08000Treat none
0.09000.1317Full model
0.09000.1229Clinical score
0.09000.1202Treat all
0.09000Treat none
0.10000.1255Full model
0.10000.1146Clinical score
0.10000.1104Treat all
0.10000Treat none
0.11000.1183Full model
0.11000.1086Clinical score
0.11000.1004Treat all
0.11000Treat none
0.12000.1146Full model
0.12000.1026Clinical score
0.12000.0901Treat all
0.12000Treat none
0.13000.1095Full model
0.13000.0974Clinical score
0.13000.0797Treat all
0.13000Treat none
0.14000.1025Full model
0.14000.0907Clinical score
0.14000.0690Treat all
0.14000Treat none
0.15000.0983Full model
0.15000.0840Clinical score
0.15000.0580Treat all
0.15000Treat 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.

06

When the risks are wrong

Predict

Predict first

A model's risks are all too high, though its ranking is intact. You use a threshold of 10%. What can happen?

Net benefit risesNet benefit can't change, since the AUC is the sameNet benefit can fall, even below treat-all
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).

07

When you chose the sample's mix

In the app

In 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.

Decision curve analysisRecorded · Python and R agreeRecorded 2026-11-17 · 14 values compared
R

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

Decision curveAcross the range of risk thresholds a clinician might use, does acting on the model do more good than treating everyone or no one?
View data
Net benefitStrategyThreshold probability
0.0909lp_full0.0100
0.0819lp_full0.0200
0.0733lp_full0.0300
0.0659lp_full0.0400
0.0590lp_full0.0500
0.0535lp_full0.0600
0.0483lp_full0.0700
0.0440lp_full0.0800
0.0396lp_full0.0900
0.0346lp_full0.1000
0.0310lp_full0.1100
0.0268lp_full0.1200
0.0229lp_full0.1300
0.0209lp_full0.1400
0.0177lp_full0.1500
0.0169lp_full0.1600
0.0105lp_full0.1700
0.0086lp_full0.1800
0.0042lp_full0.1900
0.0014lp_full0.2000
0.0021lp_full0.2100
0.0036lp_full0.2200
−6.858e-5lp_full0.2300
−0.0023lp_full0.2400
−0.0040lp_full0.2500
−0.0057lp_full0.2600
−0.0053lp_full0.2700
−0.0075lp_full0.2800
−0.0069lp_full0.2900
−0.0084lp_full0.3000
−0.0126lp_full0.3100
−0.0162lp_full0.3200
−0.0203lp_full0.3300
−0.0239lp_full0.3400
−0.0279lp_full0.3500
−0.0286lp_full0.3600
−0.0321lp_full0.3700
−0.0350lp_full0.3800
−0.0337lp_full0.3900
−0.0308lp_full0.4000
−0.0302lp_full0.4100
−0.0323lp_full0.4200
−0.0293lp_full0.4300
−0.0284lp_full0.4400
−0.0321lp_full0.4500
−0.0345lp_full0.4600
−0.0323lp_full0.4700
−0.0367lp_full0.4800
−0.0407lp_full0.4900
−0.0384lp_full0.5000
0.0909Treat all0.0100
0.0816Treat all0.0200
0.0722Treat all0.0300
0.0625Treat all0.0400
0.0526Treat all0.0500
0.0426Treat all0.0600
0.0323Treat all0.0700
0.0217Treat all0.0800
0.0110Treat all0.0900
0Treat all0.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

ModelNet benefitvs treat allvs treat noneInterventions avoided / 100SensitivitySpecificityBest choice for thresholds
lp_full0.05900.00640.059012.1100.99440.14650.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

ThresholdTreat alllp_full
0.01000.09090.0909
0.02000.08160.0819
0.03000.07220.0733
0.04000.06250.0659
0.05000.05260.0590
0.06000.04260.0535
0.07000.03230.0483
0.08000.02170.0440
0.09000.01100.0396
0.100000.0346
0.1100−0.01120.0310
0.1200−0.02270.0268
0.1300−0.03450.0229
0.1400−0.04650.0209
0.1500−0.05880.0177
0.1600−0.07140.0169
0.1700−0.08430.0105
0.1800−0.09760.0086
0.1900−0.11110.0042
0.2000−0.12500.0014
0.2100−0.13920.0021
0.2200−0.15380.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
))
Python

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

ModelNet benefitvs treat allvs treat noneInterventions avoided / 100SensitivitySpecificityBest choice for thresholds
lp_full0.05900.00640.059012.1100.99440.14650.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

ThresholdTreat alllp_full
0.01000.09090.0909
0.02000.08160.0819
0.03000.07220.0733
0.04000.06250.0659
0.05000.05260.0590
0.06000.04260.0535
0.07000.03230.0483
0.08000.02170.0440
0.09000.01100.0396
0.100000.0346
0.1100−0.01120.0310
0.1200−0.02270.0268
0.1300−0.03450.0229
0.1400−0.04650.0209
0.1500−0.05880.0177
0.1600−0.07140.0169
0.1700−0.08430.0105
0.1800−0.09760.0086
0.1900−0.11110.0042
0.2000−0.12500.0014
0.2100−0.13920.0021
0.2200−0.15380.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: NB=Se π−(1−Sp)(1−π) t/(1−t)\text{NB} = \text{Se}\,\pi - (1 - \text{Sp})(1 - \pi)\,t/(1-t). With 10% prevalence and a threshold of 5%, the model scores 0.059 and treat-all 0.053.

08

Same sum, two dialects

Read

Net benefit is short enough to write by hand, which is the best way to trust it.

Python
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)
R
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)
09

Check your understanding

Checkpoint

Check 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 = π.

10

Recap

Recap
  • A threshold states a trade: t/(1−t)t / (1 - t) 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