Choosing a cut-off
Youden's J, the closest corner and expected cost can each name an "optimal" cut-off. Only you can say which errors matter, and the winner on your data will look better than it is.
What runs in CodeSplash
- ROC curve and AUC (DeLong) Verified in Python and R
You will be able to
- Choose a cut-off with Youden's J, the closest corner or expected cost
- Predict how costs and prevalence move the best cut-off
- Explain why a cut-off chosen on the data overstates its own performance
Read first
Three rules
Read| Rule | Picks the threshold that | Assumes |
|---|---|---|
| Youden's JYouden's JSensitivity + specificity − 1; the threshold that maximizes it weighs both errors equally. | maximizes | Sensitivity and specificity matter equally |
| Closest to the top-left corner | minimizes | A geometric convenience, with no costs |
| Minimum expected cost | minimizes | You've stated the costs and the prevalence |
The first two can pick different points on the same curve (Perkins and Schisterman, 2006). Only the third uses what an error costs and how common the condition is.
Make errors unequal
PredictPredict first
Higher glucose indicates diabetes. You decide a missed case costs ten times as much as a false alarm. Where should the cut-off go, compared with treating both errors alike?
Reveal
Lower. You accept more false alarms to miss fewer cases. Sensitivity rises and specificity falls, moving you up and to the right along the same curve. The curve doesn't change: only your position on it.
Find the cheapest threshold
ExploreSet A miss costs this many false alarms, then move Decision threshold until the cost is close to the lowest possible. Now change Share of positives and look for the new best threshold. The walkthrough below does the same on a real model that predicts {{target}}.
HExplorable · Rare events and the decision threshold
Why can a 98% accurate model be useless, and where should the threshold go?
A lazy model calls every case negative. What accuracy does it score?
| flagged | passed | |
|---|---|---|
| pos | 52 | 62 |
| neg | 312 | 4574 |
Bars are drawn to one count scale, so a rare positive class looks as rare as it is. The ROC curve barely notices the imbalance; the precision–recall curve shows it. Cheapest threshold here: 1.14; the binormal formula gives 1.35.
Commit your prediction above to see the result
Make your prediction to see the result.
Read the cut-off table
In the appThe card's cut-off table follows Optimal cut-off. Choosing Minimum expected cost reveals Cost of a false negative ÷ cost of a false positive.
AUC = .79, 95% CI [.75, .83], p < .001
- AUC
- 0.7940
- SE (DeLong)
- 0.0209
- z (AUC = 0.5)
- 14.076
- p
- < .001
Effect size
- AUC 0.7940 95% CI [0.7530, 0.8349]
Plots
View data
| 1 − specificity | optimal | Sensitivity |
|---|---|---|
| 0 | false | 0 |
| 0 | false | 0.0056 |
| 0 | false | 0.0113 |
| 0.0028 | false | 0.0226 |
| 0.0028 | false | 0.0339 |
| 0.0028 | false | 0.0395 |
| 0.0028 | false | 0.0452 |
| 0.0056 | false | 0.0508 |
| 0.0085 | false | 0.0508 |
| 0.0113 | false | 0.0678 |
| 0.0113 | false | 0.0734 |
| 0.0113 | false | 0.0960 |
| 0.0113 | false | 0.1017 |
| 0.0113 | false | 0.1186 |
| 0.0113 | false | 0.1469 |
| 0.0141 | false | 0.1638 |
| 0.0169 | false | 0.1808 |
| 0.0169 | false | 0.1864 |
| 0.0169 | false | 0.1977 |
| 0.0169 | false | 0.2034 |
| 0.0169 | false | 0.2147 |
| 0.0197 | false | 0.2373 |
| 0.0197 | false | 0.2429 |
| 0.0197 | false | 0.2542 |
| 0.0197 | false | 0.2655 |
| 0.0197 | false | 0.2712 |
| 0.0197 | false | 0.2825 |
| 0.0197 | false | 0.2938 |
| 0.0197 | false | 0.2994 |
| 0.0282 | false | 0.2994 |
| 0.0310 | false | 0.3051 |
| 0.0310 | false | 0.3164 |
| 0.0310 | false | 0.3333 |
| 0.0310 | false | 0.3390 |
| 0.0310 | false | 0.3446 |
| 0.0338 | false | 0.3616 |
| 0.0394 | false | 0.3616 |
| 0.0394 | false | 0.3672 |
| 0.0423 | false | 0.3898 |
| 0.0563 | false | 0.3955 |
| 0.0620 | false | 0.3955 |
| 0.0648 | false | 0.4124 |
| 0.0704 | false | 0.4294 |
| 0.0732 | false | 0.4350 |
| 0.0732 | false | 0.4407 |
| 0.0761 | false | 0.4576 |
| 0.0817 | false | 0.4633 |
| 0.0873 | false | 0.4689 |
| 0.0901 | false | 0.4859 |
| 0.0986 | false | 0.5085 |
| 0.1070 | false | 0.5141 |
| 0.1155 | false | 0.5198 |
| 0.1211 | false | 0.5198 |
| 0.1268 | false | 0.5311 |
| 0.1380 | false | 0.5367 |
| 0.1380 | false | 0.5480 |
| 0.1493 | false | 0.5537 |
| 0.1549 | false | 0.5706 |
| 0.1577 | false | 0.5763 |
| 0.1634 | false | 0.5876 |
First 60 of 127 rows.
View data
| type | glu |
|---|---|
| No | 86 |
| Yes | 195 |
| No | 77 |
| No | 165 |
| No | 107 |
| Yes | 97 |
| No | 83 |
| No | 193 |
| No | 142 |
| Yes | 128 |
| Yes | 137 |
| No | 154 |
| Yes | 189 |
| Yes | 92 |
| No | 86 |
| No | 99 |
| No | 109 |
| Yes | 143 |
| Yes | 149 |
| No | 139 |
| No | 99 |
| No | 100 |
| No | 83 |
| No | 101 |
| No | 87 |
| Yes | 164 |
| No | 99 |
| Yes | 140 |
| No | 108 |
| No | 110 |
| No | 79 |
| No | 148 |
| Yes | 121 |
| No | 158 |
| Yes | 105 |
| No | 145 |
| No | 79 |
| No | 71 |
| No | 102 |
| No | 119 |
| Yes | 176 |
| No | 97 |
| No | 129 |
| No | 97 |
| No | 86 |
| No | 125 |
| No | 123 |
| No | 92 |
| Yes | 171 |
| Yes | 199 |
| No | 116 |
| No | 83 |
| Yes | 154 |
| No | 114 |
| No | 106 |
| No | 127 |
| No | 124 |
| No | 109 |
| No | 123 |
| Yes | 167 |
First 60 of 532 rows.
Assumptions
- Enough cases and non-cases — 177 with type = Yes and 355 without.
- Data-driven cut-off — The cut-off was chosen on these data, so its sensitivity and specificity are optimistic; validate it on new data.
Youden cut-off
| Measure | Value |
|---|---|
| Cut-off (glu ≥) | 128 |
| Sensitivity | 0.6667 |
| Specificity | 0.8000 |
| Youden's J | 0.4667 |
| PPV (sample prevalence) | 0.6243 |
| NPV (sample prevalence) | 0.8280 |
- Condition present: type = Yes; higher values of glu indicate the condition; a cut-off c classifies glu ≥ c as positive. Ties count one half in the AUC.
The exact R script · R R version 4.5.1 (2025-06-13)
# ROC curve and AUC (DeLong)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method diagnostic.roc 1.0.1 · spec 4a19a7def26ef18e
# Dataset: pima (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_auc_delong, cs_roc_points, cs_optimal_cutoff (twins of codesplash.stats.roc)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/pima.parquet", col_select = c("glu", "type")))
n_input <- nrow(df)
df[["type"]] <- factor(df[["type"]], levels = c("No", "Yes")) # stored level order
df <- df[stats::complete.cases(df[c("glu", "type")]), , 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("glu", "type")) # infinite values stop the run (registry/errors.yaml)
# %% Test
mk <- "glu"
r <- "type"
ref_levels <- c("No", "Yes") # stored level order
pos_level <- ref_levels[length(ref_levels)] # default: the last level ("true")
direction <- "higher" # explicit; never flipped automatically
sgn <- if (direction == "higher") 1 else -1 # "lower": analyze -marker
is_pos <- as.character(df[[r]]) == pos_level
x <- as.numeric(df[[mk]])
pos <- sgn * x[is_pos]
neg <- sgn * x[!is_pos]
m <- length(pos)
n <- length(neg)
if (m == 0 || n == 0) cs_error("CS_E_TOO_FEW_GROUPS", column = r, min = 2, k = 1) # needs positives and negatives
conf <- 0.95
method <- "youden"
auc <- cs_auc_delong(pos, neg, conf) # AUC, DeLong SE, interval clipped to [0, 1], z test of 0.5
se_ok <- min(m, n) >= 2 # DeLong's SE needs two or more of each class; otherwise the SE, interval and test are left empty
pts <- cs_roc_points(pos, neg)
prev <- m / (m + n)
best <- cs_optimal_cutoff(pts, method = method, cost_ratio = 1, prevalence = prev)
cut <- sgn * pts$threshold[best] # back on the marker's scale
se_c <- pts$tpr[best]
sp_c <- 1 - pts$fpr[best]
tp_c <- se_c * m
fp_c <- (1 - sp_c) * n
ppv_c <- if (tp_c + fp_c > 0) tp_c / (tp_c + fp_c) else NaN
npv_c <- if (sp_c * n + (1 - se_c) * m > 0) sp_c * n / (sp_c * n + (1 - se_c) * m) else NaN
rule <- if (direction == "higher") "≥" else "≤"
labels <- c(youden = "Youden", "closest-topleft" = "closest-to-top-left", cost = "minimum-cost")
# %% Assumptions
assumptions <- list(
list(key = "sample_size", label = "Enough cases and non-cases", status = if (min(m, n) < 10) "warn" else "pass",
detail = sprintf("%d with %s = %s and %d without%s", m, r, pos_level, n, if (min(m, n) < 10) "; the DeLong interval is rough." else ".")),
list(key = "cutoff_optimism", label = "Data-driven cut-off", status = "info",
detail = "The cut-off was chosen on these data, so its sensitivity and specificity are optimistic; validate it on new data.")
)
if (auc$auc < 0.5) {
warnings <- c(warnings, sprintf("AUC is below 0.5: %s works in the opposite direction to the one chosen (%s values indicate %s).", mk, direction, pos_level))
}
# %% Result
k <- length(pts$tpr)
keep <- sort(unique(c(round(seq(1, k, length.out = min(k, 2000))), best))) # thin long curves
chart_rows <- unique(round(seq(1, length(x), length.out = min(length(x), 5000))))
pct <- sprintf("%.0f%%", conf * 100)
summary <- sprintf("AUC = %.3f, %s CI [%.3f, %.3f] (%s); %s cut-off %s %s %s: sensitivity %.1f%%, specificity %.1f%%.",
auc$auc, pct, auc$low, auc$high, cs_fmt_p(auc$p), labels[[method]], mk, rule, format(cut), 100 * se_c, 100 * sp_c)
cs_publish(list(
method = "diagnostic.roc",
methodVersion = "1.0.1",
title = "ROC analysis",
engine = cs_engine_info("stats", "nanoparquet"),
n = m + n,
summary = summary,
apa = sprintf("AUC = %s, %s CI [%s, %s], %s", cs_fmt_num(auc$auc, leading_zero = FALSE), pct, cs_fmt_num(auc$low, leading_zero = FALSE),
cs_fmt_num(auc$high, leading_zero = FALSE), cs_fmt_p(auc$p)),
statistics = list(
list(key = "auc", label = "AUC", value = auc$auc), list(key = "auc_se", label = "SE (DeLong)", value = auc$se),
list(key = "z", label = "z (AUC = 0.5)", value = auc$z), list(key = "p", label = "p", value = auc$p, format = "p")
),
tables = list(list(
key = "cutoff", title = paste0(toupper(substr(labels[[method]], 1, 1)), substring(labels[[method]], 2), " cut-off"),
columns = list(list(key = "measure", label = "Measure", type = "string"), list(key = "value", label = "Value", type = "number")),
rows = list(list(measure = sprintf("Cut-off (%s %s)", mk, rule), value = cut), list(measure = "Sensitivity", value = se_c),
list(measure = "Specificity", value = sp_c), list(measure = "Youden's J", value = se_c + sp_c - 1),
list(measure = "PPV (sample prevalence)", value = ppv_c), list(measure = "NPV (sample prevalence)", value = npv_c))
)),
effectSizes = list(list(key = "auc", label = "AUC", value = auc$auc, ciLow = auc$low, ciHigh = auc$high, ciLevel = conf,
method = "Mann–Whitney estimate, DeLong standard error")),
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Condition present: %s = %s; %s values of %s indicate the condition; a cut-off c classifies %s %s c as positive. Ties count one half in the AUC.",
r, pos_level, direction, mk, mk, rule)),
charts = list(
cs_chart("roc", "roc-curve", sprintf("ROC curve of %s", mk),
list(fpr = cs_col("1 − specificity", pts$fpr[keep]), tpr = cs_col("Sensitivity", pts$tpr[keep]), optimal = cs_col("optimal", keep == best))),
cs_chart("distribution", "raincloud", sprintf("%s by %s", mk, r),
list(y = cs_col(mk, x[chart_rows]), group = cs_col(r, as.character(df[[r]])[chart_rows], levels = ref_levels)))
),
values = list(
n_pos = m, n_neg = n, auc = auc$auc, auc_se = if (se_ok) auc$se else NA,
auc_ci_low = if (se_ok) auc$low else NA, auc_ci_high = if (se_ok) auc$high else NA,
z = if (se_ok) auc$z else NA, p = if (se_ok) auc$p else NA, cutoff = cut, cutoff_sensitivity = se_c, cutoff_specificity = sp_c, cutoff_youden = se_c + sp_c - 1,
cutoff_ppv = ppv_c, cutoff_npv = npv_c, n_thresholds = k - 1, positive_level = pos_level, cutoff_rule = rule,
cutoff_label = labels[[method]], cutoff_text = sprintf("%g", cut) # %g: same text in Python
)
))
AUC = .79, 95% CI [.75, .83], p < .001
- AUC
- 0.7940
- SE (DeLong)
- 0.0209
- z (AUC = 0.5)
- 14.076
- p
- < .001
Effect size
- AUC 0.7940 95% CI [0.7530, 0.8349]
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Enough cases and non-cases — 177 with type = Yes and 355 without.
- Data-driven cut-off — The cut-off was chosen on these data, so its sensitivity and specificity are optimistic; validate it on new data.
Youden cut-off
| Measure | Value |
|---|---|
| Cut-off (glu ≥) | 128 |
| Sensitivity | 0.6667 |
| Specificity | 0.8000 |
| Youden's J | 0.4667 |
| PPV (sample prevalence) | 0.6243 |
| NPV (sample prevalence) | 0.8280 |
- Condition present: type = Yes; higher values of glu indicate the condition; a cut-off c classifies glu ≥ c as positive. Ties count one half in the AUC.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# ROC curve and AUC (DeLong)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method diagnostic.roc 1.0.1 · spec 4a19a7def26ef18e
# Dataset: pima (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 roc as csr # DeLong AUC, ROC points, cut-offs (twins of codesplashr)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/pima.parquet", columns=["glu", "type"])
n_input = len(df)
df["type"] = pd.Categorical(df["type"], categories=["No", "Yes"]) # stored level order
df = df.dropna(subset=["glu", "type"]) # listwise deletion over the analysis columns
df["type"] = df["type"].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, ["glu", "type"]) # infinite values stop the run (registry/errors.yaml)
# %% Test
mk, r = "glu", "type"
ref_levels = ["No", "Yes"] # stored level order
pos_level = ref_levels[-1] # default: the last level ("true")
direction = "higher" # explicit; never flipped automatically
sign = 1.0 if direction == "higher" else -1.0 # "lower": analyze −marker
is_pos = (df[r].astype(str) == pos_level).to_numpy()
x = df[mk].to_numpy(dtype=float)
pos, neg = sign * x[is_pos], sign * x[~is_pos]
m, n = len(pos), len(neg)
if m == 0 or n == 0:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=r, min=2, k=1) # needs positives and negatives
conf = 0.95
method = "youden"
auc = csr.auc_delong(pos, neg, conf) # AUC, DeLong SE, interval clipped to [0, 1], z test of 0.5
se_ok = min(m, n) >= 2 # DeLong's SE needs two or more of each class; otherwise the SE, interval and test are left empty
pts = csr.roc_points(pos, neg)
prev = m / (m + n)
best = csr.optimal_cutoff(pts, method=method, cost_ratio=1, prevalence=prev)
cut = sign * float(pts["threshold"][best]) # back on the marker's scale
se_c, sp_c = float(pts["tpr"][best]), 1.0 - float(pts["fpr"][best])
tp_c, fp_c = se_c * m, (1 - sp_c) * n
ppv_c = tp_c / (tp_c + fp_c) if tp_c + fp_c > 0 else math.nan
npv_c = sp_c * n / (sp_c * n + (1 - se_c) * m) if sp_c * n + (1 - se_c) * m > 0 else math.nan
rule = "≥" if direction == "higher" else "≤"
labels = {"youden": "Youden", "closest-topleft": "closest-to-top-left", "cost": "minimum-cost"}
# %% Assumptions
assumptions = [
{"key": "sample_size", "label": "Enough cases and non-cases", "status": "warn" if min(m, n) < 10 else "pass",
"detail": f"{m} with {r} = {pos_level} and {n} without" + ("; the DeLong interval is rough." if min(m, n) < 10 else ".")},
{"key": "cutoff_optimism", "label": "Data-driven cut-off", "status": "info",
"detail": "The cut-off was chosen on these data, so its sensitivity and specificity are optimistic; validate it on new data."},
]
if auc["auc"] < 0.5:
warnings.append(f"AUC is below 0.5: {mk} works in the opposite direction to the one chosen ({direction} values indicate {pos_level}).")
# %% Result
k = len(pts["tpr"])
keep = np.unique(np.concatenate([np.round(np.linspace(0, k - 1, min(k, 2000))).astype(int), [best]])) # thin long curves
fpr, tpr = pts["fpr"][keep], pts["tpr"][keep]
chart_rows = np.unique(np.round(np.linspace(0, len(x) - 1, min(len(x), 5000))).astype(int))
summary = f"AUC = {auc['auc']:.3f}, {conf:.0%} CI [{auc['low']:.3f}, {auc['high']:.3f}] ({cs.fmt_p(auc['p'])}); {labels[method]} cut-off {mk} {rule} {cut:g}: sensitivity {se_c:.1%}, specificity {sp_c:.1%}."
cs.publish({
"method": "diagnostic.roc",
"methodVersion": "1.0.1",
"title": "ROC analysis",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": m + n,
"summary": summary,
"apa": f"AUC = {cs.fmt_num(auc['auc'], leading_zero=False)}, {conf:.0%} CI [{cs.fmt_num(auc['low'], leading_zero=False)}, {cs.fmt_num(auc['high'], leading_zero=False)}], {cs.fmt_p(auc['p'])}",
"statistics": [
{"key": "auc", "label": "AUC", "value": auc["auc"]}, {"key": "auc_se", "label": "SE (DeLong)", "value": auc["se"]},
{"key": "z", "label": "z (AUC = 0.5)", "value": auc["z"]}, {"key": "p", "label": "p", "value": auc["p"], "format": "p"},
],
"tables": [{
"key": "cutoff", "title": f"{labels[method].capitalize()} cut-off",
"columns": [{"key": "measure", "label": "Measure", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
"rows": [{"measure": f"Cut-off ({mk} {rule})", "value": cut}, {"measure": "Sensitivity", "value": se_c},
{"measure": "Specificity", "value": sp_c}, {"measure": "Youden's J", "value": se_c + sp_c - 1},
{"measure": "PPV (sample prevalence)", "value": ppv_c}, {"measure": "NPV (sample prevalence)", "value": npv_c}],
}],
"effectSizes": [{"key": "auc", "label": "AUC", "value": auc["auc"], "ciLow": auc["low"], "ciHigh": auc["high"], "ciLevel": conf,
"method": "Mann–Whitney estimate, DeLong standard error"}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Condition present: {r} = {pos_level}; {direction} values of {mk} indicate the condition; a cut-off c classifies {mk} {rule} c as positive. Ties count one half in the AUC."],
"charts": [
cs.chart("roc", "roc-curve", f"ROC curve of {mk}",
{"fpr": cs.col("1 − specificity", fpr), "tpr": cs.col("Sensitivity", tpr), "optimal": cs.col("optimal", (keep == best).tolist())}),
cs.chart("distribution", "raincloud", f"{mk} by {r}",
{"y": cs.col(mk, x[chart_rows]), "group": cs.col(r, df[r].astype(str).to_numpy()[chart_rows], levels=ref_levels)}),
],
"values": {
"n_pos": m, "n_neg": n, "auc": auc["auc"], "auc_se": auc["se"] if se_ok else None,
"auc_ci_low": auc["low"] if se_ok else None, "auc_ci_high": auc["high"] if se_ok else None,
"z": auc["z"] if se_ok else None, "p": auc["p"] if se_ok else None, "cutoff": cut, "cutoff_sensitivity": se_c, "cutoff_specificity": sp_c, "cutoff_youden": se_c + sp_c - 1,
"cutoff_ppv": ppv_c, "cutoff_npv": npv_c, "n_thresholds": k - 1, "positive_level": pos_level, "cutoff_rule": rule,
"cutoff_label": labels[method], "cutoff_text": f"{cut:g}", # %g: same text in R
},
})
Youden picks glucose ≥ 128: sensitivity 0.67, specificity 0.80, = 0.47. The PPV of 0.62 is labeled sample prevalence, because it holds only at this mix of patients.
With a false negative costing twice a false positive, and lower weight indicating a manual car, the rule below picks weight ≤ 3.17.
AUC = .93, 95% CI [.84, 1.00], p < .001
- AUC
- 0.9332
- SE (DeLong)
- 0.0481
- z (AUC = 0.5)
- 9.004
- p
- < .001
Effect size
- AUC 0.9332 95% CI [0.8389, 1]
Plots
View data
| 1 − specificity | optimal | Sensitivity |
|---|---|---|
| 0 | false | 0 |
| 0 | false | 0.0769 |
| 0 | false | 0.1538 |
| 0 | false | 0.2308 |
| 0 | false | 0.3077 |
| 0 | false | 0.3846 |
| 0 | false | 0.4615 |
| 0 | false | 0.5385 |
| 0.0526 | false | 0.5385 |
| 0.0526 | false | 0.6154 |
| 0.0526 | false | 0.6923 |
| 0.0526 | false | 0.7692 |
| 0.0526 | false | 0.8462 |
| 0.1053 | false | 0.8462 |
| 0.1053 | true | 0.9231 |
| 0.1579 | false | 0.9231 |
| 0.2105 | false | 0.9231 |
| 0.2632 | false | 0.9231 |
| 0.4211 | false | 0.9231 |
| 0.4737 | false | 0.9231 |
| 0.5263 | false | 0.9231 |
| 0.5789 | false | 1 |
| 0.6316 | false | 1 |
| 0.6842 | false | 1 |
| 0.7368 | false | 1 |
| 0.7895 | false | 1 |
| 0.8421 | false | 1 |
| 0.8947 | false | 1 |
| 0.9474 | false | 1 |
| 1 | false | 1 |
View data
| manual | weight (1000 lbs) |
|---|---|
| true | 2.620 |
| true | 2.875 |
| true | 2.320 |
| false | 3.215 |
| false | 3.440 |
| false | 3.460 |
| false | 3.570 |
| false | 3.190 |
| false | 3.150 |
| false | 3.440 |
| false | 3.440 |
| false | 4.070 |
| false | 3.730 |
| false | 3.780 |
| false | 5.250 |
| false | 5.424 |
| false | 5.345 |
| true | 2.200 |
| true | 1.615 |
| true | 1.835 |
| false | 2.465 |
| false | 3.520 |
| false | 3.435 |
| false | 3.840 |
| false | 3.845 |
| true | 1.935 |
| true | 2.140 |
| true | 1.513 |
| true | 3.170 |
| true | 2.770 |
| true | 3.570 |
| true | 2.780 |
Assumptions
- Enough cases and non-cases — 13 with manual = true and 19 without.
- Data-driven cut-off — The cut-off was chosen on these data, so its sensitivity and specificity are optimistic; validate it on new data.
Minimum-cost cut-off
| Measure | Value |
|---|---|
| Cut-off (weight (1000 lbs) ≤) | 3.170 |
| Sensitivity | 0.9231 |
| Specificity | 0.8947 |
| Youden's J | 0.8178 |
| PPV (sample prevalence) | 0.8571 |
| NPV (sample prevalence) | 0.9444 |
- Condition present: manual = true; lower values of weight (1000 lbs) indicate the condition; a cut-off c classifies weight (1000 lbs) ≤ c as positive. Ties count one half in the AUC.
The exact R script · R R version 4.5.1 (2025-06-13)
# ROC curve and AUC (DeLong)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method diagnostic.roc 1.0.1 · spec 72577220521e69b6
# Dataset: mtcars (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_auc_delong, cs_roc_points, cs_optimal_cutoff (twins of codesplash.stats.roc)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/mtcars.parquet", col_select = c("weight (1000 lbs)", "manual")))
n_input <- nrow(df)
df[["manual"]] <- factor(df[["manual"]], levels = c("false", "true")) # stored level order
df <- df[stats::complete.cases(df[c("weight (1000 lbs)", "manual")]), , 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("weight (1000 lbs)", "manual")) # infinite values stop the run (registry/errors.yaml)
# %% Test
mk <- "weight (1000 lbs)"
r <- "manual"
ref_levels <- c("false", "true") # stored level order
pos_level <- ref_levels[length(ref_levels)] # default: the last level ("true")
direction <- "lower" # explicit; never flipped automatically
sgn <- if (direction == "higher") 1 else -1 # "lower": analyze -marker
is_pos <- as.character(df[[r]]) == pos_level
x <- as.numeric(df[[mk]])
pos <- sgn * x[is_pos]
neg <- sgn * x[!is_pos]
m <- length(pos)
n <- length(neg)
if (m == 0 || n == 0) cs_error("CS_E_TOO_FEW_GROUPS", column = r, min = 2, k = 1) # needs positives and negatives
conf <- 0.95
method <- "cost"
auc <- cs_auc_delong(pos, neg, conf) # AUC, DeLong SE, interval clipped to [0, 1], z test of 0.5
se_ok <- min(m, n) >= 2 # DeLong's SE needs two or more of each class; otherwise the SE, interval and test are left empty
pts <- cs_roc_points(pos, neg)
prev <- m / (m + n)
best <- cs_optimal_cutoff(pts, method = method, cost_ratio = 2, prevalence = prev)
cut <- sgn * pts$threshold[best] # back on the marker's scale
se_c <- pts$tpr[best]
sp_c <- 1 - pts$fpr[best]
tp_c <- se_c * m
fp_c <- (1 - sp_c) * n
ppv_c <- if (tp_c + fp_c > 0) tp_c / (tp_c + fp_c) else NaN
npv_c <- if (sp_c * n + (1 - se_c) * m > 0) sp_c * n / (sp_c * n + (1 - se_c) * m) else NaN
rule <- if (direction == "higher") "≥" else "≤"
labels <- c(youden = "Youden", "closest-topleft" = "closest-to-top-left", cost = "minimum-cost")
# %% Assumptions
assumptions <- list(
list(key = "sample_size", label = "Enough cases and non-cases", status = if (min(m, n) < 10) "warn" else "pass",
detail = sprintf("%d with %s = %s and %d without%s", m, r, pos_level, n, if (min(m, n) < 10) "; the DeLong interval is rough." else ".")),
list(key = "cutoff_optimism", label = "Data-driven cut-off", status = "info",
detail = "The cut-off was chosen on these data, so its sensitivity and specificity are optimistic; validate it on new data.")
)
if (auc$auc < 0.5) {
warnings <- c(warnings, sprintf("AUC is below 0.5: %s works in the opposite direction to the one chosen (%s values indicate %s).", mk, direction, pos_level))
}
# %% Result
k <- length(pts$tpr)
keep <- sort(unique(c(round(seq(1, k, length.out = min(k, 2000))), best))) # thin long curves
chart_rows <- unique(round(seq(1, length(x), length.out = min(length(x), 5000))))
pct <- sprintf("%.0f%%", conf * 100)
summary <- sprintf("AUC = %.3f, %s CI [%.3f, %.3f] (%s); %s cut-off %s %s %s: sensitivity %.1f%%, specificity %.1f%%.",
auc$auc, pct, auc$low, auc$high, cs_fmt_p(auc$p), labels[[method]], mk, rule, format(cut), 100 * se_c, 100 * sp_c)
cs_publish(list(
method = "diagnostic.roc",
methodVersion = "1.0.1",
title = "ROC analysis",
engine = cs_engine_info("stats", "nanoparquet"),
n = m + n,
summary = summary,
apa = sprintf("AUC = %s, %s CI [%s, %s], %s", cs_fmt_num(auc$auc, leading_zero = FALSE), pct, cs_fmt_num(auc$low, leading_zero = FALSE),
cs_fmt_num(auc$high, leading_zero = FALSE), cs_fmt_p(auc$p)),
statistics = list(
list(key = "auc", label = "AUC", value = auc$auc), list(key = "auc_se", label = "SE (DeLong)", value = auc$se),
list(key = "z", label = "z (AUC = 0.5)", value = auc$z), list(key = "p", label = "p", value = auc$p, format = "p")
),
tables = list(list(
key = "cutoff", title = paste0(toupper(substr(labels[[method]], 1, 1)), substring(labels[[method]], 2), " cut-off"),
columns = list(list(key = "measure", label = "Measure", type = "string"), list(key = "value", label = "Value", type = "number")),
rows = list(list(measure = sprintf("Cut-off (%s %s)", mk, rule), value = cut), list(measure = "Sensitivity", value = se_c),
list(measure = "Specificity", value = sp_c), list(measure = "Youden's J", value = se_c + sp_c - 1),
list(measure = "PPV (sample prevalence)", value = ppv_c), list(measure = "NPV (sample prevalence)", value = npv_c))
)),
effectSizes = list(list(key = "auc", label = "AUC", value = auc$auc, ciLow = auc$low, ciHigh = auc$high, ciLevel = conf,
method = "Mann–Whitney estimate, DeLong standard error")),
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Condition present: %s = %s; %s values of %s indicate the condition; a cut-off c classifies %s %s c as positive. Ties count one half in the AUC.",
r, pos_level, direction, mk, mk, rule)),
charts = list(
cs_chart("roc", "roc-curve", sprintf("ROC curve of %s", mk),
list(fpr = cs_col("1 − specificity", pts$fpr[keep]), tpr = cs_col("Sensitivity", pts$tpr[keep]), optimal = cs_col("optimal", keep == best))),
cs_chart("distribution", "raincloud", sprintf("%s by %s", mk, r),
list(y = cs_col(mk, x[chart_rows]), group = cs_col(r, as.character(df[[r]])[chart_rows], levels = ref_levels)))
),
values = list(
n_pos = m, n_neg = n, auc = auc$auc, auc_se = if (se_ok) auc$se else NA,
auc_ci_low = if (se_ok) auc$low else NA, auc_ci_high = if (se_ok) auc$high else NA,
z = if (se_ok) auc$z else NA, p = if (se_ok) auc$p else NA, cutoff = cut, cutoff_sensitivity = se_c, cutoff_specificity = sp_c, cutoff_youden = se_c + sp_c - 1,
cutoff_ppv = ppv_c, cutoff_npv = npv_c, n_thresholds = k - 1, positive_level = pos_level, cutoff_rule = rule,
cutoff_label = labels[[method]], cutoff_text = sprintf("%g", cut) # %g: same text in Python
)
))
AUC = .93, 95% CI [.84, 1.00], p < .001
- AUC
- 0.9332
- SE (DeLong)
- 0.0481
- z (AUC = 0.5)
- 9.004
- p
- < .001
Effect size
- AUC 0.9332 95% CI [0.8389, 1]
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Enough cases and non-cases — 13 with manual = true and 19 without.
- Data-driven cut-off — The cut-off was chosen on these data, so its sensitivity and specificity are optimistic; validate it on new data.
Minimum-cost cut-off
| Measure | Value |
|---|---|
| Cut-off (weight (1000 lbs) ≤) | 3.170 |
| Sensitivity | 0.9231 |
| Specificity | 0.8947 |
| Youden's J | 0.8178 |
| PPV (sample prevalence) | 0.8571 |
| NPV (sample prevalence) | 0.9444 |
- Condition present: manual = true; lower values of weight (1000 lbs) indicate the condition; a cut-off c classifies weight (1000 lbs) ≤ c as positive. Ties count one half in the AUC.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# ROC curve and AUC (DeLong)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method diagnostic.roc 1.0.1 · spec 72577220521e69b6
# Dataset: mtcars (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 roc as csr # DeLong AUC, ROC points, cut-offs (twins of codesplashr)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/mtcars.parquet", columns=["weight (1000 lbs)", "manual"])
n_input = len(df)
df["manual"] = pd.Categorical(df["manual"], categories=["false", "true"]) # stored level order
df = df.dropna(subset=["weight (1000 lbs)", "manual"]) # listwise deletion over the analysis columns
df["manual"] = df["manual"].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, ["weight (1000 lbs)", "manual"]) # infinite values stop the run (registry/errors.yaml)
# %% Test
mk, r = "weight (1000 lbs)", "manual"
ref_levels = ["false", "true"] # stored level order
pos_level = ref_levels[-1] # default: the last level ("true")
direction = "lower" # explicit; never flipped automatically
sign = 1.0 if direction == "higher" else -1.0 # "lower": analyze −marker
is_pos = (df[r].astype(str) == pos_level).to_numpy()
x = df[mk].to_numpy(dtype=float)
pos, neg = sign * x[is_pos], sign * x[~is_pos]
m, n = len(pos), len(neg)
if m == 0 or n == 0:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=r, min=2, k=1) # needs positives and negatives
conf = 0.95
method = "cost"
auc = csr.auc_delong(pos, neg, conf) # AUC, DeLong SE, interval clipped to [0, 1], z test of 0.5
se_ok = min(m, n) >= 2 # DeLong's SE needs two or more of each class; otherwise the SE, interval and test are left empty
pts = csr.roc_points(pos, neg)
prev = m / (m + n)
best = csr.optimal_cutoff(pts, method=method, cost_ratio=2, prevalence=prev)
cut = sign * float(pts["threshold"][best]) # back on the marker's scale
se_c, sp_c = float(pts["tpr"][best]), 1.0 - float(pts["fpr"][best])
tp_c, fp_c = se_c * m, (1 - sp_c) * n
ppv_c = tp_c / (tp_c + fp_c) if tp_c + fp_c > 0 else math.nan
npv_c = sp_c * n / (sp_c * n + (1 - se_c) * m) if sp_c * n + (1 - se_c) * m > 0 else math.nan
rule = "≥" if direction == "higher" else "≤"
labels = {"youden": "Youden", "closest-topleft": "closest-to-top-left", "cost": "minimum-cost"}
# %% Assumptions
assumptions = [
{"key": "sample_size", "label": "Enough cases and non-cases", "status": "warn" if min(m, n) < 10 else "pass",
"detail": f"{m} with {r} = {pos_level} and {n} without" + ("; the DeLong interval is rough." if min(m, n) < 10 else ".")},
{"key": "cutoff_optimism", "label": "Data-driven cut-off", "status": "info",
"detail": "The cut-off was chosen on these data, so its sensitivity and specificity are optimistic; validate it on new data."},
]
if auc["auc"] < 0.5:
warnings.append(f"AUC is below 0.5: {mk} works in the opposite direction to the one chosen ({direction} values indicate {pos_level}).")
# %% Result
k = len(pts["tpr"])
keep = np.unique(np.concatenate([np.round(np.linspace(0, k - 1, min(k, 2000))).astype(int), [best]])) # thin long curves
fpr, tpr = pts["fpr"][keep], pts["tpr"][keep]
chart_rows = np.unique(np.round(np.linspace(0, len(x) - 1, min(len(x), 5000))).astype(int))
summary = f"AUC = {auc['auc']:.3f}, {conf:.0%} CI [{auc['low']:.3f}, {auc['high']:.3f}] ({cs.fmt_p(auc['p'])}); {labels[method]} cut-off {mk} {rule} {cut:g}: sensitivity {se_c:.1%}, specificity {sp_c:.1%}."
cs.publish({
"method": "diagnostic.roc",
"methodVersion": "1.0.1",
"title": "ROC analysis",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": m + n,
"summary": summary,
"apa": f"AUC = {cs.fmt_num(auc['auc'], leading_zero=False)}, {conf:.0%} CI [{cs.fmt_num(auc['low'], leading_zero=False)}, {cs.fmt_num(auc['high'], leading_zero=False)}], {cs.fmt_p(auc['p'])}",
"statistics": [
{"key": "auc", "label": "AUC", "value": auc["auc"]}, {"key": "auc_se", "label": "SE (DeLong)", "value": auc["se"]},
{"key": "z", "label": "z (AUC = 0.5)", "value": auc["z"]}, {"key": "p", "label": "p", "value": auc["p"], "format": "p"},
],
"tables": [{
"key": "cutoff", "title": f"{labels[method].capitalize()} cut-off",
"columns": [{"key": "measure", "label": "Measure", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
"rows": [{"measure": f"Cut-off ({mk} {rule})", "value": cut}, {"measure": "Sensitivity", "value": se_c},
{"measure": "Specificity", "value": sp_c}, {"measure": "Youden's J", "value": se_c + sp_c - 1},
{"measure": "PPV (sample prevalence)", "value": ppv_c}, {"measure": "NPV (sample prevalence)", "value": npv_c}],
}],
"effectSizes": [{"key": "auc", "label": "AUC", "value": auc["auc"], "ciLow": auc["low"], "ciHigh": auc["high"], "ciLevel": conf,
"method": "Mann–Whitney estimate, DeLong standard error"}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Condition present: {r} = {pos_level}; {direction} values of {mk} indicate the condition; a cut-off c classifies {mk} {rule} c as positive. Ties count one half in the AUC."],
"charts": [
cs.chart("roc", "roc-curve", f"ROC curve of {mk}",
{"fpr": cs.col("1 − specificity", fpr), "tpr": cs.col("Sensitivity", tpr), "optimal": cs.col("optimal", (keep == best).tolist())}),
cs.chart("distribution", "raincloud", f"{mk} by {r}",
{"y": cs.col(mk, x[chart_rows]), "group": cs.col(r, df[r].astype(str).to_numpy()[chart_rows], levels=ref_levels)}),
],
"values": {
"n_pos": m, "n_neg": n, "auc": auc["auc"], "auc_se": auc["se"] if se_ok else None,
"auc_ci_low": auc["low"] if se_ok else None, "auc_ci_high": auc["high"] if se_ok else None,
"z": auc["z"] if se_ok else None, "p": auc["p"] if se_ok else None, "cutoff": cut, "cutoff_sensitivity": se_c, "cutoff_specificity": sp_c, "cutoff_youden": se_c + sp_c - 1,
"cutoff_ppv": ppv_c, "cutoff_npv": npv_c, "n_thresholds": k - 1, "positive_level": pos_level, "cutoff_rule": rule,
"cutoff_label": labels[method], "cutoff_text": f"{cut:g}", # %g: same text in R
},
})
Test the winner on new patients
PredictPredict first
You pick the Youden cut-off on these data and report its sensitivity and specificity. Then you try that cut-off on new patients. What should you expect?
Reveal
Somewhat worse. You chose the best-looking point on a noisy curve, so part of what you selected was noise. The card flags this under Data-driven cut-off. Validate on new data, or bootstrap the selection along with the estimate.
Do you need a cut-off at all?
ReadCutting a number into two throws information away: a glucose of 127 and one of 129 land on opposite sides, while 129 and 199 count as the same.
If one decision really does need one threshold, fine. Otherwise keep the number. Model the risk with logistic regression and report it across the range. A borrowed cut-off also needs checking: this one came from these patients, and prevalencePrevalenceHow common the condition is in the population tested; it drives predictive values. or the case mix may differ elsewhere.
Same rule, two dialects
ReadpROC reports thresholds as midpoints between observed values, so it can differ from the card's cut-off, which is an observed value. Both classify the same patients as positive.
import pandas as pd
from sklearn.metrics import roc_curve
df = pd.read_csv("pima.csv")
y = (df["type"] == "Yes").astype(int)
fpr, tpr, thresholds = roc_curve(y, df["glu"])
best = (tpr - fpr).argmax()
print(thresholds[best], tpr[best], 1 - fpr[best], tpr[best] - fpr[best])library(pROC)
df <- read.csv("pima.csv")
r <- roc(df$type, df$glu, levels = c("No", "Yes"), direction = "<")
coords(r, "best", best.method = "youden",
ret = c("threshold", "sensitivity", "specificity"))Check your understanding
CheckpointCheck yourself
At a cut-off, sensitivity is 2/3 and specificity is 0.80. What is Youden's J? Give three decimals.
Show the answer
Answer: 0.466666666666667
0.667 + 0.800 − 1 = 0.467.
Check yourself
Higher values of a marker indicate the condition. You move to a setting where the condition is much rarer, with the same costs. Where does the minimum-cost cut-off go?
Show the answer
Answer: a
In the expected cost, prevalence multiplies the misses and multiplies the false alarms. As falls, false alarms weigh more, so you flag fewer people.
Check yourself
A paper reports sensitivity 92% and specificity 88% at an "optimal" cut-off chosen on its own 80 patients. How should you read it?
Show the answer
Answer: b
Selecting and evaluating on the same data flatters the result, and small samples make that worse.
Recap
Recap- Youden's J and the closest corner ignore costs and prevalence. Expected cost uses both.
- Higher costs for misses move the cut-off toward flagging more people.
- A cut-off chosen on the data looks better than it is: validate it.
- If no single decision needs a threshold, keep the number.
Concepts in this lesson