Skip to content

ROC and precision–recall curves

Sweep every threshold at once. See what AUC really measures, why it ignores prevalence, and when the precision–recall curve tells you what ROC hides.

Applied ~12 min9 steps

What runs in CodeSplash

You will be able to

  • Read a ROC curve and interpret AUC as a probability
  • Explain why ROC doesn't move with prevalence, and precision does
  • Choose between ROC AUC and PR AUC

Read first

01

Every threshold at once

Read

Threshold metrics describe one cut. A ROC curveROC curveSensitivity against 1 − specificity across every threshold of a score. draws all of them: each point is a threshold's true-positive rate against its false-positive rate.

The area beneath it is the AUCArea under the ROC curveThe chance a random positive scores higher than a random negative; 0.5 is guessing, 1 is perfect ranking., and it has a plain meaning: the chance that a random positive scores above a random negative.

A score that ignores the features gets 0.500. Glucose alone on Pima gets 0.794. A random forest on all seven measurements gets 0.835.

02

Slide the threshold

Explore

Move Threshold and watch the point travel along the curve. Then change Separation of the classes (d′) and see the curve bow out. Use the check to find the best Youden's J.

HExplorable · The ROC curve and its threshold

What does moving a threshold trade away, and what does the AUC really measure?

How often does a random positive score above a random negative?

0.75
How sure?
1.50
2.50
0.100
150
threshold

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

03

Rare positives

Predict

Predict first

The score and the classes' shapes don't change, but the positive class falls from 50% to 1% of rows. What happens to the ROC AUC, and to precision at a fixed threshold?

Both stay the sameAUC stays, and precision fallsBoth fall
Reveal

AUC stays, and precision falls. ROC's axes are each computed within one class, so prevalence doesn't enter. Precision mixes the classes, so with 1% positives the false alarms swamp the real cases. Set Prevalence low in the explorable above and read PPV.

04

The precision–recall view

Read

Plot precision against recall, and you see the trade you'd really face. A no-skill model isn't on a diagonal here: it sits flat at the prevalence, which the chart shows as a baseline.

Precision–recall curveHow much precision does the model keep as it finds more of the positives?
View data
recallprecisionmodel
01XGBoost
0.09681XGBoost
0.19351XGBoost
0.25810.8889XGBoost
0.32260.8333XGBoost
0.40320.8333XGBoost
0.45160.7778XGBoost
0.46770.6905XGBoost
0.50000.6458XGBoost
0.53230.6111XGBoost
0.56450.5833XGBoost
0.58060.5455XGBoost
0.61290.5278XGBoost
0.62900.5000XGBoost
0.62900.4643XGBoost
0.64520.4444XGBoost
0.70970.4583XGBoost
0.72580.4412XGBoost
0.72580.4167XGBoost
0.74190.4035XGBoost
0.75810.3917XGBoost
0.77420.3810XGBoost
0.80650.3788XGBoost
0.82260.3696XGBoost
0.82260.3542XGBoost
0.83870.3467XGBoost
0.85480.3397XGBoost
0.85480.3272XGBoost
0.88710.3274XGBoost
0.88710.3161XGBoost
0.88710.3056XGBoost
0.90320.3011XGBoost
0.90320.2917XGBoost
0.90320.2828XGBoost
0.90320.2745XGBoost
0.90320.2667XGBoost
0.90320.2593XGBoost
0.90320.2523XGBoost
0.91940.2500XGBoost
0.95160.2521XGBoost
0.95160.2458XGBoost
0.95160.2398XGBoost
0.95160.2341XGBoost
0.95160.2287XGBoost
0.96770.2273XGBoost
0.96770.2222XGBoost
0.96770.2174XGBoost
0.96770.2128XGBoost
0.96770.2083XGBoost
0.96770.2041XGBoost
0.96770.2000XGBoost
0.96770.1961XGBoost
0.96770.1923XGBoost
0.96770.1887XGBoost
0.96770.1852XGBoost
0.96770.1818XGBoost
0.96770.1786XGBoost
0.98390.1784XGBoost
0.98390.1753XGBoost
0.98390.1723XGBoost

First 60 of 202 rows.

So read PR AUCPrecision–recall AUCArea under the precision–recall curve; more informative than ROC AUC when positives are rare. against the prevalence, not against zero. On Pima, about a third of rows are positive, so a useful PR AUC must beat that figure by a good margin. With a 1% rate, a PR AUC of 0.20.2 is already twenty times the no-skill value.

05

Which to report?

Reflect
  • ROC AUC: ranking quality that's comparable across different prevalences. The default Primary metric for two classes.
  • PR AUC: when positives are rare, and when you act on the top of the list.
  • Neither: when you've settled on a threshold and costs, as both summarize thresholds you'd never use.

Two models can have similar ROC AUCs and rather different precision where it matters. For more than two classes, the app reports one-vs-rest macro AUC.

Which part of the curve would you operate in, for a model you know?

06

A worked cut

Read

Reading the curve becomes a decision when you choose a point. For glucose, Youden's J picks a cutoff of 128: sensitivity 0.667 and specificity 0.800.

Youden's J weighs both errors the same. That's rarely what a real decision wants, and the next lessons give you better tools.

ROC analysisRecorded · Python and R agreeRecorded 2026-11-25 · 19 values compared
R

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

ROC curve of gluHow well does a score separate positives from negatives at every cutoff?
View data
1 − specificityoptimalSensitivity
0false0
0false0.0056
0false0.0113
0.0028false0.0226
0.0028false0.0339
0.0028false0.0395
0.0028false0.0452
0.0056false0.0508
0.0085false0.0508
0.0113false0.0678
0.0113false0.0734
0.0113false0.0960
0.0113false0.1017
0.0113false0.1186
0.0113false0.1469
0.0141false0.1638
0.0169false0.1808
0.0169false0.1864
0.0169false0.1977
0.0169false0.2034
0.0169false0.2147
0.0197false0.2373
0.0197false0.2429
0.0197false0.2542
0.0197false0.2655
0.0197false0.2712
0.0197false0.2825
0.0197false0.2938
0.0197false0.2994
0.0282false0.2994
0.0310false0.3051
0.0310false0.3164
0.0310false0.3333
0.0310false0.3390
0.0310false0.3446
0.0338false0.3616
0.0394false0.3616
0.0394false0.3672
0.0423false0.3898
0.0563false0.3955
0.0620false0.3955
0.0648false0.4124
0.0704false0.4294
0.0732false0.4350
0.0732false0.4407
0.0761false0.4576
0.0817false0.4633
0.0873false0.4689
0.0901false0.4859
0.0986false0.5085
0.1070false0.5141
0.1155false0.5198
0.1211false0.5198
0.1268false0.5311
0.1380false0.5367
0.1380false0.5480
0.1493false0.5537
0.1549false0.5706
0.1577false0.5763
0.1634false0.5876

First 60 of 127 rows.

glu by typeHow do groups compare in shape, summary and individual observations at once?
View data
typeglu
No86
Yes195
No77
No165
No107
Yes97
No83
No193
No142
Yes128
Yes137
No154
Yes189
Yes92
No86
No99
No109
Yes143
Yes149
No139
No99
No100
No83
No101
No87
Yes164
No99
Yes140
No108
No110
No79
No148
Yes121
No158
Yes105
No145
No79
No71
No102
No119
Yes176
No97
No129
No97
No86
No125
No123
No92
Yes171
Yes199
No116
No83
Yes154
No114
No106
No127
No124
No109
No123
Yes167

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

MeasureValue
Cut-off (glu ≥)128
Sensitivity0.6667
Specificity0.8000
Youden's J0.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
  )
))
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

MeasureValue
Cut-off (glu ≥)128
Sensitivity0.6667
Specificity0.8000
Youden's J0.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
    },
})
07

Check your understanding

Checkpoint

Check yourself

A model has an AUC of 0.8. Which statement is correct?

Show the answer

Answer: b

AUC measures ranking. It doesn't depend on any threshold or on the class shares, and it can't say how accurate any one decision is.

Check yourself

Positives make up 2% of rows. Where does a no-skill model's precision sit? Answer as a proportion.

Show the answer

Answer: 0.02

Flagging at random keeps precision at the base rate, so a PR baseline is the prevalence.

Check yourself

You're finding fraud, about 1 in 1,000 transactions, and investigators can review 100 a day. Which view helps most?

Show the answer

Answer: b

Only the top of the list gets reviewed, and false alarms cost time. A high ROC AUC can coexist with poor precision at that point.

08

On a run

In the app

Open a binary run and go to Evaluation. You'll find the ROC and precision–recall curves together. Switch on Curves per fold to see how much they vary. Compare two runs on the same plan by ticking them on the Leaderboard.

Python
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import average_precision_score, roc_auc_score
from sklearn.model_selection import StratifiedKFold, cross_val_predict

df = pd.read_csv("pima.csv")
X, y = df.drop(columns="diabetic"), df["diabetic"]
cv = StratifiedKFold(5, shuffle=True, random_state=1)
p = cross_val_predict(RandomForestClassifier(300, random_state=1), X, y, cv=cv, method="predict_proba")[:, 1]
print("roc auc", round(roc_auc_score(y, p), 3), "pr auc", round(average_precision_score(y, p), 3), "prevalence", round(y.mean(), 3))
R
library(ranger)
df <- rbind(MASS::Pima.tr, MASS::Pima.te)
set.seed(1)
fold <- sample(rep(1:5, length.out = nrow(df)))
p <- numeric(nrow(df))
for (k in 1:5) {
  fit <- ranger(type ~ ., df[fold != k, ], num.trees = 300, probability = TRUE, seed = 1)
  p[fold == k] <- predict(fit, df[fold == k, ])$predictions[, "Yes"]
}
y <- df$type == "Yes"
ord <- order(-p); tp <- cumsum(y[ord]); prec <- tp / seq_along(tp)
c(roc_auc = as.numeric(pROC::auc(y, p, quiet = TRUE)), pr_auc = sum(prec[y[ord]]) / sum(y), prevalence = mean(y))
09

Recap

Recap
  • A ROC curve shows all thresholds, and AUC is a ranking probability.
  • ROC ignores prevalence, and precision doesn't, so rare classes need the PR view.
  • Read PR AUC against the base rate, and look at the part of the curve you'd really use.

Concepts in this lesson