Skip to content

HDiagnostic accuracy · diagnostic.reclassification

Reclassification (NRI, IDI) and AUC change

Does a new model (or added marker) move people into more appropriate risk categories than the old one?

Compares two sets of predicted risks for the same people: the categorical net reclassification improvement over stated risk cut-offs with its event and non-event components, the category-free NRI(>0), the integrated discrimination improvement, the change in AUC (paired DeLong), and the reclassification tables — with asymptotic tests and stratified bootstrap intervals.

Verified in Python and R Python and R agree to 10 decimals Seeded

A real result

Example “Pima default missing”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Reclassification (NRI, IDI)Recorded · Python and R agreeRecorded 2026-11-17 · 34 values compared
R

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

ROC curvesHow well does a score separate positives from negatives at every cutoff?
View data
Model1 − specificitySensitivity
p_base00
p_base00.0057
p_base00.0114
p_base00.0171
p_base00.0229
p_base00.0286
p_base00.0343
p_base0.00290.0343
p_base0.00290.0400
p_base0.00290.0457
p_base0.00290.0514
p_base0.00570.0514
p_base0.00570.0571
p_base0.00570.0629
p_base0.00570.0686
p_base0.00570.0743
p_base0.00570.0800
p_base0.00860.0800
p_base0.01140.0800
p_base0.01140.0857
p_base0.01430.0857
p_base0.01710.0857
p_base0.01710.0914
p_base0.01710.0971
p_base0.01710.1029
p_base0.01710.1086
p_base0.01710.1143
p_base0.01710.1200
p_base0.01710.1257
p_base0.01710.1314
p_base0.01710.1371
p_base0.01710.1429
p_base0.02000.1429
p_base0.02290.1429
p_base0.02290.1486
p_base0.02290.1543
p_base0.02290.1600
p_base0.02290.1657
p_base0.02290.1714
p_base0.02570.1714
p_base0.02570.1771
p_base0.02570.1829
p_base0.02570.1886
p_base0.02570.1943
p_base0.02860.1943
p_base0.02860.2000
p_base0.02860.2057
p_base0.02860.2114
p_base0.02860.2171
p_base0.03140.2171
p_base0.03140.2229
p_base0.03140.2286
p_base0.03140.2343
p_base0.03430.2343
p_base0.03430.2400
p_base0.03430.2457
p_base0.03710.2457
p_base0.03710.2514
p_base0.03710.2571
p_base0.03710.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

MeasureEventsNon-eventsTotal95% CI low95% CI highp
NRI (categorical)0.01710.15710.17430.09990.2444< .001
NRI(>0) (category-free)0.18860.32570.51430.33710.6917< .001
IDI0.04000.01910.05910.03980.0806< .001
ΔAUC (new − old, DeLong)——0.03230.01200.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.10.1–0.2≥ 0.2
< 0.1151
0.1–0.2276
≥ 0.207146

Reclassification of non-events (n = 350)

p_base ↓ / risk score →< 0.10.1–0.2≥ 0.2
< 0.172122
0.1–0.2515211
≥ 0.2326121
  • 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.
Python

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

MeasureEventsNon-eventsTotal95% CI low95% CI highp
NRI (categorical)0.01710.15710.17430.09990.2444< .001
NRI(>0) (category-free)0.18860.32570.51430.33710.6917< .001
IDI0.04000.01910.05910.03980.0806< .001
ΔAUC (new − old, DeLong)——0.03230.01200.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.10.1–0.2≥ 0.2
< 0.1151
0.1–0.2276
≥ 0.207146

Reclassification of non-events (n = 350)

p_base ↓ / risk score →< 0.10.1–0.2≥ 0.2
< 0.172122
0.1–0.2515211
≥ 0.2326121
  • 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.

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Pima default missings5_risk · baseline: p_base · new: risk score · outcome: diabetic
  • Three cutoffs categoricals5_risk · baseline: p_base · new: p_overfit · outcome: type
  • No bootstraps5_risk · baseline: p_base · new: risk score · outcome: diabetic
  • Tiess5_ties · baseline: p_group · new: p_edge · outcome: event
  • Degenerate n2s5_risk · baseline: p_base · new: risk score · outcome: diabetic
  • Degenerate tiess5_risk · baseline: p_base · new: risk score · outcome: diabetic

In the guides

Where it sits in the decision guides

  • Multiple predictors: logistic / ML · Statistics Guide · H — Diagnostic accuracy
  • PR curves, calibration, decision curves · Statistics Guide · H — Diagnostic accuracy
  • Probabilistic forecasting (Bayesian, deep ensembles) · DS & ML Decision Guide · Predict — forecast or classify outcomes

What you need

Observed outcomecategorical / boolean · 1 column · 2–2 levels
What happened (two levels).
Old model's risknumeric · 1 column
Predicted risks from the reference model.
New model's risknumeric · 1 column
Predicted risks from the new or extended model.

Choices you make

hypothesis

Event leveldefault —

The outcome level the risks predict (default the last stored level — true for true/false columns).

Scale of the predictionsdefault probability

The units of your prediction column: probabilities, percentages or log-odds. All are converted to probabilities.

  • Probability (0–1)(default) — Your column holds probabilities from 0 to 1, so nothing is converted.
  • Percent (0–100) — Your column holds percentages from 0 to 100, which are divided by 100.
  • Log-odds (linear predictor) — Your column holds log-odds, such as a model's linear predictor, which are converted to probabilities.
Risk category cut-offsdefault 0.1,0.2

Risks below the first cut-off form the lowest category; a cut-off c starts the category c ≤ risk < next. Use clinically meaningful thresholds stated in advance.

Confidence leveldefault 0.95

How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.

statistics

Bootstrap resamplesdefault 1000

Stratified by the outcome (the shared random stream gives the same resamples in Python and R); 0 = asymptotic intervals only.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Both models are calibrated

    NRI and IDI can reward miscalibration (Pepe et al. 2015; Kerr et al. 2014): check calibration of both models before reading them.

  • Cut-offs stated in advance

    Categorical NRI depends on the cut-offs; choosing them after seeing the data inflates it.

What it reports

  • Tests: Net reclassification improvement differs from 0
  • Tests: Integrated discrimination improvement differs from 0
n
How many independent units the analysis used; it sets precision and power.
n_events
How many independent units the analysis used; it sets precision and power.
positive_level
Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
n_categories
How many independent units the analysis used; it sets precision and power.
nri
Net upward moves in risk among events, plus net downward moves among non-events. It's a sum of two proportions.
nri_events
Net upward moves in risk among events, plus net downward moves among non-events. It's a sum of two proportions.
nri_nonevents
Net upward moves in risk among events, plus net downward moves among non-events. It's a sum of two proportions.
nri_se
The typical size of the error in an estimate, the standard deviation of its sampling distribution.
nri_z
An estimate in standard-error units, compared with the standard normal distribution.
nri_p
How surprising your data would be if the null hypothesis were true, as a probability.
nri_low
A range of effect values compatible with your data at the chosen confidence level.
nri_high
A range of effect values compatible with your data at the chosen confidence level.
cnri
Net upward moves in risk among events, plus net downward moves among non-events. It's a sum of two proportions.
cnri_events
Net upward moves in risk among events, plus net downward moves among non-events. It's a sum of two proportions.
cnri_nonevents
Net upward moves in risk among events, plus net downward moves among non-events. It's a sum of two proportions.
cnri_se
The typical size of the error in an estimate, the standard deviation of its sampling distribution.
cnri_p
How surprising your data would be if the null hypothesis were true, as a probability.
cnri_low
A range of effect values compatible with your data at the chosen confidence level.
cnri_high
A range of effect values compatible with your data at the chosen confidence level.
idi
The mean rise in predicted risk among events, plus the mean fall among non-events, with a new model.
idi_events
The mean rise in predicted risk among events, plus the mean fall among non-events, with a new model.
idi_nonevents
The mean rise in predicted risk among events, plus the mean fall among non-events, with a new model.
idi_se
The typical size of the error in an estimate, the standard deviation of its sampling distribution.
idi_p
How surprising your data would be if the null hypothesis were true, as a probability.
idi_low
A range of effect values compatible with your data at the chosen confidence level.
idi_high
A range of effect values compatible with your data at the chosen confidence level.
auc_old
The chance a random positive scores higher than a random negative; 0.5 is guessing, 1 is perfect ranking.
auc_new
The chance a random positive scores higher than a random negative; 0.5 is guessing, 1 is perfect ranking.
delta_auc
The chance a random positive scores higher than a random negative; 0.5 is guessing, 1 is perfect ranking.
delta_auc_se
The typical size of the error in an estimate, the standard deviation of its sampling distribution.
delta_auc_low
A range of effect values compatible with your data at the chosen confidence level.
delta_auc_high
A range of effect values compatible with your data at the chosen confidence level.
delta_auc_p
How surprising your data would be if the null hypothesis were true, as a probability.
boot
Estimates uncertainty by recomputing a statistic on many samples drawn with replacement from your data.

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • NRI, IDI and their standard errors are the codesplash twins in both engines (Pencina et al. 2008, 2011; same as PredictABEL/nricens point estimates); bootstrap resamples come from the shared Wichmann–Hill stream, so intervals agree exactly.
Python

The exact script CodeSplash ran for example “Pima default missing” · 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,
})
R

The exact script CodeSplash ran for example “Pima default missing” · 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
))

Sources

  • Pencina, M. J., D'Agostino, R. B., Sr., D'Agostino, R. B., Jr., & Vasan, R. S. (2008). Evaluating the added predictive ability of a new marker: from area under the ROC curve to reclassification and beyond. Statistics in Medicine, 27, 157–172.
  • Pencina, M. J., D'Agostino, R. B., Sr., & Steyerberg, E. W. (2011). Extensions of net reclassification improvement calculations to measure usefulness of new biomarkers. Statistics in Medicine, 30, 11–21.
  • Kerr, K. F., Wang, Z., Janes, H., McClelland, R. L., Psaty, B. M., & Pepe, M. S. (2014). Net reclassification indices for evaluating risk prediction instruments: a critical review. Epidemiology, 25, 114–121.
  • Pepe, M. S., Fan, J., Feng, Z., Gerds, T., & Hilden, J. (2015). The net reclassification index (NRI): a misleading measure of prediction improvement even with independent test data sets. Statistics in Biosciences, 7, 282–295.

From the CodeSplash method registry · diagnostic.reclassification v1.0.1.