Does a new marker add value? NRI, IDI and reporting
A small rise in AUC prompted reclassification measures, and these can reward a worse model. Learn to read them, what to report instead, and how to write up an accuracy study.
What runs in CodeSplash
- Reclassification (NRI, IDI) and AUC change Verified in Python and R
You will be able to
- Compute the NRI from reclassification counts and say what it isn't
- Show that the NRI depends on cut-offs and can reward miscalibration
- Assess an added marker with calibration, a nested test and net benefit
A small change in AUC
ReadYour old model predicts diabetes from glucose and age. The new one adds BMI and a family-history score. On the same 525 women, the AUC goes from 0.821 to 0.853.
Is that worth collecting two more variables? AUC changes tend to be small when the old model is already good. So researchers asked a different question: does the new model move people into better risk categories?
Two reclassification measures
ReadThe net reclassification improvementNet reclassification improvementNet upward moves in risk among events, plus net downward moves among non-events. It's a sum of two proportions. counts moves across risk categories. Moves up are good for events, and moves down are good for non-events:
NRI(>0) counts any change of risk, with no categories. The integrated discrimination improvementIntegrated discrimination improvementThe mean rise in predicted risk among events, plus the mean fall among non-events, with a new model. uses the mean change of risk instead of counts:
Compute one
CheckpointCheck yourself
Among 100 events, a new model moves 20 up and 5 down. Among 200 non-events, it moves 30 down and 10 up. What is the NRI?
Show the answer
Answer: 0.25
Events: (20 − 5)/100 = 0.15. Non-events: (30 − 10)/200 = 0.10. The sum is 0.25.
Check yourself
So the NRI is 0.25. What can you say?
Show the answer
Answer: b
The two parts have different denominators, so their sum isn't a share of anyone. Report them separately.
Move the cut-offs
PredictPredict first
With cut-offs at 10% and 20%, the NRI is 0.174. You keep the same two models and the same women, and switch to one cut-off at 25%. What happens?
Reveal
Much smaller: 0.020, with p = .476. The statistic reflects the lines you drew. So set Risk category cut-offs from a real decision, before you look at the data. The card lists this as Cut-offs stated in advance.
Reward a worse model
PredictPredict first
Now take the new model and stretch its risks until they're too extreme. The order barely changes, and the AUC gain stays near 0.032. What happens to NRI(>0) and the IDI?
Reveal
They rise. NRI(>0) goes from 0.51 to 0.97, and the IDI from 0.059 to 0.142. The AUC gain is 0.032. A worse-calibrated model scored better, which is the core criticism from Kerr and colleagues (2014) and Pepe and colleagues (2015).
Read the card
In the appImprovement of the new model splits each measure by events and non-events. Two tables below it show who moved. Bootstrap resamples sets the intervals.
Categorical NRI 0.174 (events 0.017, non-events 0.157; p < .001); NRI(>0) 0.514; IDI 0.059 (p < .001); ΔAUC 0.032 (p = .002).
- NRI (categorical)
- 0.1743
- p
- < .001
- NRI(>0)
- 0.5143
- IDI
- 0.0591
- p (IDI)
- < .001
- ΔAUC
- 0.0323
Effect size
- ΔAUC 0.0323 95% CI [0.0120, 0.0525]
Plots
View data
| Model | 1 − specificity | Sensitivity |
|---|---|---|
| p_base | 0 | 0 |
| p_base | 0 | 0.0057 |
| p_base | 0 | 0.0114 |
| p_base | 0 | 0.0171 |
| p_base | 0 | 0.0229 |
| p_base | 0 | 0.0286 |
| p_base | 0 | 0.0343 |
| p_base | 0.0029 | 0.0343 |
| p_base | 0.0029 | 0.0400 |
| p_base | 0.0029 | 0.0457 |
| p_base | 0.0029 | 0.0514 |
| p_base | 0.0057 | 0.0514 |
| p_base | 0.0057 | 0.0571 |
| p_base | 0.0057 | 0.0629 |
| p_base | 0.0057 | 0.0686 |
| p_base | 0.0057 | 0.0743 |
| p_base | 0.0057 | 0.0800 |
| p_base | 0.0086 | 0.0800 |
| p_base | 0.0114 | 0.0800 |
| p_base | 0.0114 | 0.0857 |
| p_base | 0.0143 | 0.0857 |
| p_base | 0.0171 | 0.0857 |
| p_base | 0.0171 | 0.0914 |
| p_base | 0.0171 | 0.0971 |
| p_base | 0.0171 | 0.1029 |
| p_base | 0.0171 | 0.1086 |
| p_base | 0.0171 | 0.1143 |
| p_base | 0.0171 | 0.1200 |
| p_base | 0.0171 | 0.1257 |
| p_base | 0.0171 | 0.1314 |
| p_base | 0.0171 | 0.1371 |
| p_base | 0.0171 | 0.1429 |
| p_base | 0.0200 | 0.1429 |
| p_base | 0.0229 | 0.1429 |
| p_base | 0.0229 | 0.1486 |
| p_base | 0.0229 | 0.1543 |
| p_base | 0.0229 | 0.1600 |
| p_base | 0.0229 | 0.1657 |
| p_base | 0.0229 | 0.1714 |
| p_base | 0.0257 | 0.1714 |
| p_base | 0.0257 | 0.1771 |
| p_base | 0.0257 | 0.1829 |
| p_base | 0.0257 | 0.1886 |
| p_base | 0.0257 | 0.1943 |
| p_base | 0.0286 | 0.1943 |
| p_base | 0.0286 | 0.2000 |
| p_base | 0.0286 | 0.2057 |
| p_base | 0.0286 | 0.2114 |
| p_base | 0.0286 | 0.2171 |
| p_base | 0.0314 | 0.2171 |
| p_base | 0.0314 | 0.2229 |
| p_base | 0.0314 | 0.2286 |
| p_base | 0.0314 | 0.2343 |
| p_base | 0.0343 | 0.2343 |
| p_base | 0.0343 | 0.2400 |
| p_base | 0.0343 | 0.2457 |
| p_base | 0.0371 | 0.2457 |
| p_base | 0.0371 | 0.2514 |
| p_base | 0.0371 | 0.2571 |
| p_base | 0.0371 | 0.2629 |
First 60 of 986 rows.
Assumptions
- Both models are calibrated — NRI and IDI can reward a miscalibrated new model; check calibration of both (Diagnostic → Calibration).
- Cut-offs stated in advance — Categories from cut-offs 0.1, 0.2; choosing them after seeing the data inflates the categorical NRI.
Improvement of the new model
| Measure | Events | Non-events | Total | 95% CI low | 95% CI high | p |
|---|---|---|---|---|---|---|
| NRI (categorical) | 0.0171 | 0.1571 | 0.1743 | 0.0999 | 0.2444 | < .001 |
| NRI(>0) (category-free) | 0.1886 | 0.3257 | 0.5143 | 0.3371 | 0.6917 | < .001 |
| IDI | 0.0400 | 0.0191 | 0.0591 | 0.0398 | 0.0806 | < .001 |
| ΔAUC (new − old, DeLong) | — | — | 0.0323 | 0.0120 | 0.0525 | .002 |
NRI/IDI intervals: stratified bootstrap percentile (300 resamples, seed 42); p-values asymptotic (Pencina et al.). IDI components: mean rise of risk in events, mean fall in non-events.
Reclassification of events (diabetic = true, n = 175)
| p_base ↓ / risk score → | < 0.1 | 0.1–0.2 | ≥ 0.2 |
|---|---|---|---|
| < 0.1 | 1 | 5 | 1 |
| 0.1–0.2 | 2 | 7 | 6 |
| ≥ 0.2 | 0 | 7 | 146 |
Reclassification of non-events (n = 350)
| p_base ↓ / risk score → | < 0.1 | 0.1–0.2 | ≥ 0.2 |
|---|---|---|---|
| < 0.1 | 72 | 12 | 2 |
| 0.1–0.2 | 51 | 52 | 11 |
| ≥ 0.2 | 3 | 26 | 121 |
- 7 of 532 rows were left out because a value was missing.
- Event: diabetic = true. Up = moved to a higher risk category (categorical NRI) or any higher risk (NRI(>0)); the event component counts up − down among events, the non-event component down − up among non-events.
- NRI is not a proportion of people reclassified correctly and can be positive for a worse model; report it with calibration and the AUC.
The exact R script · R R version 4.5.1 (2025-06-13)
# Reclassification (NRI, IDI) and AUC change
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method diagnostic.reclassification 1.0.1 · spec 8e6b8f93eaa266e8
# 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_nri_*, cs_cal_idi, cs_delong_paired, cs_boot_indices_strata (shared random stream)
# %% 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"
bc <- "p_base"
nc <- "risk score"
if (bc == nc) stop("Choose two different columns of predicted risks.")
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"
risk <- function(col) {
raw <- as.numeric(df[[col]])
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 = col, requirement = "a risk between 0 and 1 on the chosen scale (percent or log-odds otherwise)", count = n_outside)
p
}
p_old <- risk(bc)
p_new <- risk(nc)
n <- length(y)
n_events <- sum(y)
# The bootstrap and the event/non-event NRI need at least two events and two non-events.
if (n_events == 0 || n_events == n) cs_error("CS_E_TOO_FEW_GROUPS", column = yc, min = 2, k = 1)
if (n_events < 2) cs_error("CS_E_SMALL_GROUP", min = 2, group = sprintf("%s = %s", yc, event), n = n_events)
if (n - n_events < 2) cs_error("CS_E_SMALL_GROUP", min = 2, group = sprintf("%s ≠ %s", yc, event), n = n - n_events)
cuts <- sort(unique(as.numeric(c(0.1, 0.2))))
if (length(cuts) == 0 || any(cuts <= 0 | cuts >= 1)) stop("Risk cut-offs must lie strictly between 0 and 1.")
conf <- 0.95
zc <- stats::qnorm(1 - (1 - conf) / 2)
B <- as.integer(300)
seed <- 42 # portable Wichmann–Hill stream: Python draws the same resamples for this seed
# %% Reclassification
c_old <- cs_cal_categories(p_old, cuts)
c_new <- cs_cal_categories(p_new, cuts)
nri <- cs_cal_nri_categorical(y, c_old, c_new)
cnri <- cs_cal_nri_continuous(y, p_old, p_new)
idi <- cs_cal_idi(y, p_old, p_new)
dl <- cs_delong_paired(p_new[y], p_new[!y], p_old[y], p_old[!y], conf) # new - old
boot_ci <- function(stat) {
idx <- cs_boot_indices_strata(as.integer(y), B, seed)
vals <- vapply(seq_len(B), function(i) stat(idx[i, ]), numeric(1))
vals <- vals[is.finite(vals)]
a <- (1 - conf) / 2
stats::quantile(vals, c(a, 1 - a), names = FALSE, type = 7) # percentile interval
}
if (B > 0) {
nri_ci <- boot_ci(function(r) cs_cal_nri_categorical(y[r], c_old[r], c_new[r])$nri)
cnri_ci <- boot_ci(function(r) cs_cal_nri_continuous(y[r], p_old[r], p_new[r])$nri)
idi_ci <- boot_ci(function(r) cs_cal_idi(y[r], p_old[r], p_new[r])$idi)
ci_kind <- sprintf("stratified bootstrap percentile (%s resamples, seed %d)", format(B, big.mark = ","), seed)
} else {
nri_ci <- nri$nri + c(-1, 1) * zc * nri$se
cnri_ci <- cnri$nri + c(-1, 1) * zc * cnri$se
idi_ci <- idi$idi + c(-1, 1) * zc * idi$se
ci_kind <- "asymptotic (Wald)"
}
# %% Assumptions
assumptions <- list(
list(key = "calibration", label = "Both models are calibrated", status = "info",
detail = "NRI and IDI can reward a miscalibrated new model; check calibration of both (Diagnostic → Calibration)."),
list(key = "prespecified", label = "Cut-offs stated in advance", status = "info",
detail = sprintf("Categories from cut-offs %s; choosing them after seeing the data inflates the categorical NRI.", paste(sprintf("%g", cuts), collapse = ", ")))
)
if (min(n_events, n - n_events) < 30) warnings <- c(warnings, "Fewer than 30 events or non-events: the NRI components and their intervals are very imprecise.")
# %% Result
labels <- c(sprintf("< %g", cuts[1]), if (length(cuts) > 1) sprintf("%g–%g", cuts[-length(cuts)], cuts[-1]), sprintf("≥ %g", cuts[length(cuts)]))
k <- length(labels)
rtable <- function(mask) {
lapply(seq_len(k), function(i) {
row <- list(old = labels[i])
for (j in seq_len(k)) row[[sprintf("new_%d", j - 1)]] <- sum(mask & c_old == i - 1 & c_new == j - 1)
row
})
}
cols <- c(list(list(key = "old", label = sprintf("%s ↓ / %s →", bc, nc), type = "string")),
lapply(seq_len(k), function(j) list(key = sprintf("new_%d", j - 1), label = labels[j], type = "integer")))
values <- list(
n = n, n_events = n_events, positive_level = event, n_categories = k,
nri = nri$nri, nri_events = nri$events, nri_nonevents = nri$nonevents, nri_se = nri$se, nri_z = nri$z, nri_p = nri$p,
nri_low = nri_ci[1], nri_high = nri_ci[2],
cnri = cnri$nri, cnri_events = cnri$events, cnri_nonevents = cnri$nonevents, cnri_se = cnri$se, cnri_p = cnri$p,
cnri_low = cnri_ci[1], cnri_high = cnri_ci[2],
idi = idi$idi, idi_events = idi$events, idi_nonevents = idi$nonevents, idi_se = idi$se, idi_p = idi$p,
idi_low = idi_ci[1], idi_high = idi_ci[2],
auc_old = dl$auc_2, auc_new = dl$auc_1, delta_auc = dl$diff, delta_auc_se = dl$se,
delta_auc_low = dl$low, delta_auc_high = dl$high, delta_auc_p = dl$p, boot = B
)
pct <- sprintf("%.0f%%", conf * 100)
ro <- cs_roc_points(p_old[y], p_old[!y])
rn <- cs_roc_points(p_new[y], p_new[!y])
summary <- sprintf("Categorical NRI %.3f (events %.3f, non-events %.3f; %s); NRI(>0) %.3f; IDI %.3f (%s); ΔAUC %.3f (%s).",
nri$nri, nri$events, nri$nonevents, cs_fmt_p(nri$p), cnri$nri, idi$idi, cs_fmt_p(idi$p), dl$diff, cs_fmt_p(dl$p))
cs_publish(list(
method = "diagnostic.reclassification",
methodVersion = "1.0.1",
title = "Reclassification (NRI, IDI)",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
statistics = list(
list(key = "nri", label = "NRI (categorical)", value = nri$nri), list(key = "nri_p", label = "p", value = nri$p, format = "p"),
list(key = "cnri", label = "NRI(>0)", value = cnri$nri), list(key = "idi", label = "IDI", value = idi$idi),
list(key = "idi_p", label = "p (IDI)", value = idi$p, format = "p"), list(key = "delta_auc", label = "ΔAUC", value = dl$diff)
),
tables = list(
list(key = "measures", title = "Improvement of the new model",
columns = list(list(key = "measure", label = "Measure", type = "string"), list(key = "events", label = "Events", type = "number"),
list(key = "nonevents", label = "Non-events", type = "number"), list(key = "value", label = "Total", type = "number"),
list(key = "low", label = sprintf("%s CI low", pct), type = "number"), list(key = "high", label = sprintf("%s CI high", pct), type = "number"),
list(key = "p", label = "p", type = "pvalue")),
rows = list(
list(measure = "NRI (categorical)", events = nri$events, nonevents = nri$nonevents, value = nri$nri, low = nri_ci[1], high = nri_ci[2], p = nri$p),
list(measure = "NRI(>0) (category-free)", events = cnri$events, nonevents = cnri$nonevents, value = cnri$nri, low = cnri_ci[1], high = cnri_ci[2], p = cnri$p),
list(measure = "IDI", events = idi$events, nonevents = idi$nonevents, value = idi$idi, low = idi_ci[1], high = idi_ci[2], p = idi$p),
list(measure = "ΔAUC (new − old, DeLong)", events = NA, nonevents = NA, value = dl$diff, low = dl$low, high = dl$high, p = dl$p)),
note = sprintf("NRI/IDI intervals: %s; p-values asymptotic (Pencina et al.). IDI components: mean rise of risk in events, mean fall in non-events.", ci_kind)),
list(key = "events", title = sprintf("Reclassification of events (%s = %s, n = %d)", yc, event, n_events), columns = cols, rows = rtable(y)),
list(key = "nonevents", title = sprintf("Reclassification of non-events (n = %d)", n - n_events), columns = cols, rows = rtable(!y))
),
effectSizes = list(list(key = "delta_auc", label = "ΔAUC", value = dl$diff, ciLow = dl$low, ciHigh = dl$high, ciLevel = conf, method = "Paired DeLong")),
assumptions = assumptions,
warnings = warnings,
notes = list(
sprintf("Event: %s = %s. Up = moved to a higher risk category (categorical NRI) or any higher risk (NRI(>0)); the event component counts up − down among events, the non-event component down − up among non-events.", yc, event),
"NRI is not a proportion of people reclassified correctly and can be positive for a worse model; report it with calibration and the AUC."
),
charts = list(cs_chart("roc", "roc-curve", "ROC curves",
list(fpr = cs_col("1 − specificity", c(ro$fpr, rn$fpr)), tpr = cs_col("Sensitivity", c(ro$tpr, rn$tpr)),
curve = cs_col("Model", c(rep(bc, length(ro$tpr)), rep(nc, length(rn$tpr))), kind = "categorical")))),
values = values
))
Categorical NRI 0.174 (events 0.017, non-events 0.157; p < .001); NRI(>0) 0.514; IDI 0.059 (p < .001); ΔAUC 0.032 (p = .002).
- NRI (categorical)
- 0.1743
- p
- < .001
- NRI(>0)
- 0.5143
- IDI
- 0.0591
- p (IDI)
- < .001
- ΔAUC
- 0.0323
Effect size
- ΔAUC 0.0323 95% CI [0.0120, 0.0525]
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Both models are calibrated — NRI and IDI can reward a miscalibrated new model; check calibration of both (Diagnostic → Calibration).
- Cut-offs stated in advance — Categories from cut-offs 0.1, 0.2; choosing them after seeing the data inflates the categorical NRI.
Improvement of the new model
| Measure | Events | Non-events | Total | 95% CI low | 95% CI high | p |
|---|---|---|---|---|---|---|
| NRI (categorical) | 0.0171 | 0.1571 | 0.1743 | 0.0999 | 0.2444 | < .001 |
| NRI(>0) (category-free) | 0.1886 | 0.3257 | 0.5143 | 0.3371 | 0.6917 | < .001 |
| IDI | 0.0400 | 0.0191 | 0.0591 | 0.0398 | 0.0806 | < .001 |
| ΔAUC (new − old, DeLong) | — | — | 0.0323 | 0.0120 | 0.0525 | .002 |
NRI/IDI intervals: stratified bootstrap percentile (300 resamples, seed 42); p-values asymptotic (Pencina et al.). IDI components: mean rise of risk in events, mean fall in non-events.
Reclassification of events (diabetic = true, n = 175)
| p_base ↓ / risk score → | < 0.1 | 0.1–0.2 | ≥ 0.2 |
|---|---|---|---|
| < 0.1 | 1 | 5 | 1 |
| 0.1–0.2 | 2 | 7 | 6 |
| ≥ 0.2 | 0 | 7 | 146 |
Reclassification of non-events (n = 350)
| p_base ↓ / risk score → | < 0.1 | 0.1–0.2 | ≥ 0.2 |
|---|---|---|---|
| < 0.1 | 72 | 12 | 2 |
| 0.1–0.2 | 51 | 52 | 11 |
| ≥ 0.2 | 3 | 26 | 121 |
- 7 of 532 rows were left out because a value was missing.
- Event: diabetic = true. Up = moved to a higher risk category (categorical NRI) or any higher risk (NRI(>0)); the event component counts up − down among events, the non-event component down − up among non-events.
- NRI is not a proportion of people reclassified correctly and can be positive for a worse model; report it with calibration and the AUC.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Reclassification (NRI, IDI) and AUC change
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method diagnostic.reclassification 1.0.1 · spec 8e6b8f93eaa266e8
# 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
from scipy import stats
import codesplash as cs
from codesplash.stats import calibration as cal # NRI, IDI, risk categories (twins of codesplashr cs_cal_*)
from codesplash.stats import roc as csr # paired DeLong comparison of AUCs
from codesplash.stats.rng import boot_indices_strata # shared stream: R draws the same resamples
# %% 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, bc, nc = "diabetic", "p_base", "risk score"
if bc == nc:
raise ValueError("Choose two different columns of predicted risks.")
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"
def risk(col: str) -> np.ndarray:
raw = df[col].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=col, requirement="a risk between 0 and 1 on the chosen scale (percent or log-odds otherwise)", count=n_outside)
return p
p_old, p_new = risk(bc), risk(nc)
n, n_events = len(y), int(y.sum())
# The bootstrap and the event/non-event NRI need at least two events and two non-events.
if n_events == 0 or n_events == n:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=yc, min=2, k=1)
if n_events < 2:
cs.cs_error("CS_E_SMALL_GROUP", min=2, group=f"{yc} = {event}", n=n_events)
if n - n_events < 2:
cs.cs_error("CS_E_SMALL_GROUP", min=2, group=f"{yc} ≠ {event}", n=n - n_events)
cuts = sorted(set(float(c) for c in [0.1, 0.2]))
if not cuts or any(c <= 0 or c >= 1 for c in cuts):
raise ValueError("Risk cut-offs must lie strictly between 0 and 1.")
conf = 0.95
zc = float(stats.norm.ppf(1 - (1 - conf) / 2))
B = int(300)
seed = 42 # portable Wichmann–Hill stream: R draws the same resamples for this seed
# %% Reclassification
c_old, c_new = cal.categories(p_old, cuts), cal.categories(p_new, cuts)
nri = cal.nri_categorical(y, c_old, c_new)
cnri = cal.nri_continuous(y, p_old, p_new)
idi = cal.idi(y, p_old, p_new)
dl = csr.delong_paired(p_new[y], p_new[~y], p_old[y], p_old[~y], conf) # new − old
def boot_ci(stat):
if B <= 0:
return (None, None)
idx = boot_indices_strata(y.astype(int), B, seed)
vals = np.array([stat(r) for r in idx])
vals = vals[np.isfinite(vals)]
a = (1 - conf) / 2
return (float(np.quantile(vals, a)), float(np.quantile(vals, 1 - a))) # percentile interval (type 7)
nri_ci = boot_ci(lambda r: cal.nri_categorical(y[r], c_old[r], c_new[r])["nri"]) if B > 0 else (nri["nri"] - zc * nri["se"], nri["nri"] + zc * nri["se"])
cnri_ci = boot_ci(lambda r: cal.nri_continuous(y[r], p_old[r], p_new[r])["nri"]) if B > 0 else (cnri["nri"] - zc * cnri["se"], cnri["nri"] + zc * cnri["se"])
idi_ci = boot_ci(lambda r: cal.idi(y[r], p_old[r], p_new[r])["idi"]) if B > 0 else (idi["idi"] - zc * idi["se"], idi["idi"] + zc * idi["se"])
ci_kind = f"stratified bootstrap percentile ({B:,} resamples, seed {seed})" if B > 0 else "asymptotic (Wald)"
# %% Assumptions
assumptions = [
{"key": "calibration", "label": "Both models are calibrated", "status": "info",
"detail": "NRI and IDI can reward a miscalibrated new model; check calibration of both (Diagnostic → Calibration)."},
{"key": "prespecified", "label": "Cut-offs stated in advance", "status": "info",
"detail": f"Categories from cut-offs {', '.join(f'{c:g}' for c in cuts)}; choosing them after seeing the data inflates the categorical NRI."},
]
if min(n_events, n - n_events) < 30:
warnings.append("Fewer than 30 events or non-events: the NRI components and their intervals are very imprecise.")
# %% Result
labels = [f"< {cuts[0]:g}"] + [f"{a:g}–{b:g}" for a, b in zip(cuts[:-1], cuts[1:])] + [f"≥ {cuts[-1]:g}"]
k = len(labels)
def table(mask: np.ndarray) -> list[dict]:
rows = []
for i in range(k):
row = {"old": labels[i]}
for j in range(k):
row[f"new_{j}"] = int(np.sum(mask & (c_old == i) & (c_new == j)))
rows.append(row)
return rows
cols = [{"key": "old", "label": f"{bc} ↓ / {nc} →", "type": "string"}] + [{"key": f"new_{j}", "label": labels[j], "type": "integer"} for j in range(k)]
values = {
"n": n, "n_events": n_events, "positive_level": event, "n_categories": k,
"nri": nri["nri"], "nri_events": nri["events"], "nri_nonevents": nri["nonevents"], "nri_se": nri["se"], "nri_z": nri["z"], "nri_p": nri["p"],
"nri_low": nri_ci[0], "nri_high": nri_ci[1],
"cnri": cnri["nri"], "cnri_events": cnri["events"], "cnri_nonevents": cnri["nonevents"], "cnri_se": cnri["se"], "cnri_p": cnri["p"],
"cnri_low": cnri_ci[0], "cnri_high": cnri_ci[1],
"idi": idi["idi"], "idi_events": idi["events"], "idi_nonevents": idi["nonevents"], "idi_se": idi["se"], "idi_p": idi["p"],
"idi_low": idi_ci[0], "idi_high": idi_ci[1],
"auc_old": dl["auc_2"], "auc_new": dl["auc_1"], "delta_auc": dl["diff"], "delta_auc_se": dl["se"],
"delta_auc_low": dl["low"], "delta_auc_high": dl["high"], "delta_auc_p": dl["p"], "boot": B,
}
pct = f"{conf:.0%}"
summary = (f"Categorical NRI {nri['nri']:.3f} (events {nri['events']:.3f}, non-events {nri['nonevents']:.3f}; {cs.fmt_p(nri['p'])}); "
f"NRI(>0) {cnri['nri']:.3f}; IDI {idi['idi']:.3f} ({cs.fmt_p(idi['p'])}); ΔAUC {dl['diff']:.3f} ({cs.fmt_p(dl['p'])}).")
cs.publish({
"method": "diagnostic.reclassification",
"methodVersion": "1.0.1",
"title": "Reclassification (NRI, IDI)",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"statistics": [
{"key": "nri", "label": "NRI (categorical)", "value": nri["nri"]}, {"key": "nri_p", "label": "p", "value": nri["p"], "format": "p"},
{"key": "cnri", "label": "NRI(>0)", "value": cnri["nri"]}, {"key": "idi", "label": "IDI", "value": idi["idi"]},
{"key": "idi_p", "label": "p (IDI)", "value": idi["p"], "format": "p"}, {"key": "delta_auc", "label": "ΔAUC", "value": dl["diff"]},
],
"tables": [
{"key": "measures", "title": "Improvement of the new model", "columns": [
{"key": "measure", "label": "Measure", "type": "string"}, {"key": "events", "label": "Events", "type": "number"},
{"key": "nonevents", "label": "Non-events", "type": "number"}, {"key": "value", "label": "Total", "type": "number"},
{"key": "low", "label": f"{pct} CI low", "type": "number"}, {"key": "high", "label": f"{pct} CI high", "type": "number"},
{"key": "p", "label": "p", "type": "pvalue"}],
"rows": [
{"measure": "NRI (categorical)", "events": nri["events"], "nonevents": nri["nonevents"], "value": nri["nri"], "low": nri_ci[0], "high": nri_ci[1], "p": nri["p"]},
{"measure": "NRI(>0) (category-free)", "events": cnri["events"], "nonevents": cnri["nonevents"], "value": cnri["nri"], "low": cnri_ci[0], "high": cnri_ci[1], "p": cnri["p"]},
{"measure": "IDI", "events": idi["events"], "nonevents": idi["nonevents"], "value": idi["idi"], "low": idi_ci[0], "high": idi_ci[1], "p": idi["p"]},
{"measure": "ΔAUC (new − old, DeLong)", "events": None, "nonevents": None, "value": dl["diff"], "low": dl["low"], "high": dl["high"], "p": dl["p"]}],
"note": f"NRI/IDI intervals: {ci_kind}; p-values asymptotic (Pencina et al.). IDI components: mean rise of risk in events, mean fall in non-events."},
{"key": "events", "title": f"Reclassification of events ({yc} = {event}, n = {n_events})", "columns": cols, "rows": table(y)},
{"key": "nonevents", "title": f"Reclassification of non-events (n = {n - n_events})", "columns": cols, "rows": table(~y)},
],
"effectSizes": [{"key": "delta_auc", "label": "ΔAUC", "value": dl["diff"], "ciLow": dl["low"], "ciHigh": dl["high"], "ciLevel": conf,
"method": "Paired DeLong"}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Event: {yc} = {event}. Up = moved to a higher risk category (categorical NRI) or any higher risk (NRI(>0)); "
"the event component counts up − down among events, the non-event component down − up among non-events.",
"NRI is not a proportion of people reclassified correctly and can be positive for a worse model; report it with calibration and the AUC."],
"charts": [cs.chart("roc", "roc-curve", "ROC curves", {
"fpr": cs.col("1 − specificity", np.concatenate([csr.roc_points(p_old[y], p_old[~y])["fpr"], csr.roc_points(p_new[y], p_new[~y])["fpr"]])),
"tpr": cs.col("Sensitivity", np.concatenate([csr.roc_points(p_old[y], p_old[~y])["tpr"], csr.roc_points(p_new[y], p_new[~y])["tpr"]])),
"curve": cs.col("Model", [bc] * len(csr.roc_points(p_old[y], p_old[~y])["tpr"]) + [nc] * len(csr.roc_points(p_new[y], p_new[~y])["tpr"]), kind="categorical")})],
"values": values,
})
The events part is 0.017 and the non-events part 0.157. Nearly all the improvement comes from non-events, which is worth knowing before you claim the model finds more cases.
What to report instead
ReadTo judge an added marker, in this order:
- Calibration of both models, on data they didn't see.
- A nested test, such as a likelihood-ratio test from the same regression. DeLong's p-value isn't reliable for nested models fitted on the same data (Demler and colleagues, 2012).
- Net benefit at the thresholds in real use.
- ΔAUC with its interval, as a description.
To combine several markers in the first place, fit a logistic model, or a learner in Predict.
Write it up
ReflectSTARD covers accuracy studies, and TRIPOD covers prediction models. Between them, they ask for:
- who was enrolled, and how
- the test, the reference and who was blinded
- a flow of who was excluded or unverified
- cut-offs, and whether they were chosen in advance
- estimates with intervals, and the setting's prevalence
Pick a test or model you know. Which of these could you report today, and which would you need to find out?
Same measures, two dialects
Readimport numpy as np
import pandas as pd
df = pd.read_csv("s5_risk.csv").dropna(subset=["risk score"])
y = df["diabetic"].to_numpy()
old, new = df["p_base"].to_numpy(), df["risk score"].to_numpy()
cuts = [0.1, 0.2]
up = np.digitize(new, cuts, right=False) > np.digitize(old, cuts, right=False)
down = np.digitize(new, cuts, right=False) < np.digitize(old, cuts, right=False)
nri = (up[y].sum() - down[y].sum()) / y.sum() + (down[~y].sum() - up[~y].sum()) / (~y).sum()
d = new - old
print(nri, d[y].mean() - d[~y].mean())df <- read.csv("s5_risk.csv", check.names = FALSE)
df <- df[!is.na(df[["risk score"]]), ]
y <- df$diabetic == "true"
old <- df$p_base; new <- df[["risk score"]]
cuts <- c(0.1, 0.2)
up <- findInterval(new, cuts) > findInterval(old, cuts)
down <- findInterval(new, cuts) < findInterval(old, cuts)
nri <- (sum(up[y]) - sum(down[y])) / sum(y) + (sum(down[!y]) - sum(up[!y])) / sum(!y)
d <- new - old
c(nri = nri, idi = mean(d[y]) - mean(d[!y]))Check your understanding
CheckpointCheck yourself
A paper reports NRI = 0.40 for a new biomarker, with p < .001. Which question matters most?
Show the answer
Answer: b
The NRI can rise with miscalibration and depends on the cut-offs. Without those two checks, a small p-value says little.
Check yourself
The new model is the old one plus a marker, both fitted on the same data. How should you test whether the marker adds anything?
Show the answer
Answer: b
The likelihood-ratio test is built for nested models. DeLong's normal approximation isn't reliable in this case, and the NRI's test has its own problems.
Check yourself
Which report of an added marker is best?
Show the answer
Answer: c
The best report gives calibration, a valid test, a decision-based measure and an interval, and it names the threshold.
Recap
Recap- The NRI isn't a share of people, and it depends on the cut-offs.
- NRI and IDI can reward a miscalibrated model, so never read them alone.
- For an added marker: calibration, a nested test, net benefit, then ΔAUC.
- Report the design with STARD or TRIPOD, since the data can't show it.