Chapter 20 · Many variables, validation and pitfalls

Will your model work on new patients?

Bootstrap and jackknife, internal and external validation, calibration and sensitivity analysis.

Read first: Correlation and regression, Diagnostic tests

The problem first

You are a final-year General Surgery resident. From 200 patients who had emergency laparotomy, 37 of whom died within 30 days, you build a logistic regression score with 10 candidate predictors. In the same 200 patients its C-statistic is 0.81, and you write that the score predicts death well.

At the viva the external examiner turns to your results table and asks one question.

“You tested the score on the same patients you built it from. What will its C-statistic be in the next 200 patients?”

Start here

Why does a model look better in the patients it was built on?

A regression model chooses its coefficients to fit your patients as closely as possible. Some of what it fits is real, and some is chance variation that will not repeat in the next patients.

Patients the model was built onpredictorNew patientspredictoroutcomered zigzag: fits every point, including the noisedashed line: the simple model
Made-up points for teaching. A model with enough terms can pass through every development patient. It has learned the chance variation as well as the real trend, so it does worse than the simple model in new patients from the same population.

This is overfitting. The amount by which performance in the development patients exceeds performance in new patients is the optimism. Van Calster et al. (2019) describe what an overfitted model does in new data: lower discrimination, and predicted risks that are too extreme, with high-risk patients given risks that are too high and low-risk patients risks that are too low.

Optimism = performance in the development patients (apparent) − performance in new patients

Optimism is larger when:

  • there are few outcome events for the number of candidate predictors;
  • predictors are chosen by looking at the same data (for example, keeping those with p < 0.05);
  • continuous predictors are cut at the cut-points that happen to work best in these patients.

Interactive

Add useless predictors and watch the C-statistic rise in the development patients and fall in new patients

Every added predictor lets the model fit your 120 patients more closely, even when the predictor is a random number. New patients do not share that chance pattern.

Try this: move the number of useless predictors from 0 to 12. Watch the C-statistic in the development patients rise while the C-statistic in new patients falls, and the calibration slope drop below 1. Then press "Run 100 bootstrap resamples" to see how close the corrected estimate comes to the new-patient value.

Teaching example, simulated: a model for a yes/no outcome built on 120 patients (46 events) and tested on 2,000 new patients from the same population. Two predictors are real. The others are random numbers.

0

Total predictors = 2 real + 0 noise; 23.0 events per predictor

Data set 1
0.748C-statistic in the 120 development patients
0.746C-statistic in 2,000 new patients

Optimism: the model looks better by 0.002 in the patients it was built on. Calibration slope in new patients 1.04 (1 means the predicted risks are neither too extreme nor too timid).

0.50.60.70.80.91.0024681012useless predictors added to the 2 real onesC-statisticdevelopment patientsnew patients

Internal validation

How can you estimate performance in new patients using only your own data?

Internal validation uses the development data set to estimate how much of the apparent performance is optimism. There are three common designs.

Split samplebuild on half, test on halfhalf the patients never build the model10-fold cross-validationeach tenth left out in turn… 10 rounds; red block = test patients in that roundBootstrapbuild on a resample, test on all1134446791010121313151718181920patients 1, 4, 10, 13 and 18 drawn twice or more; 6 left outtest the resample's model in all 20 original patients
Schematic, 20 patients. In a bootstrap resample some patients are drawn more than once and others not at all, and the resample is the same size as the original data.
DesignHow it worksMain problem
Split sampleBuild on a random part (often half), test on the restThe model is built on fewer patients, and the estimate depends on which patients happened to fall in the test half
k-fold cross-validationCut the data into k parts (often 10). Build on k − 1 parts, test on the part left out, and repeat for each partEvery step of model building must be repeated in each round
BootstrapBuild the model in resamples drawn with replacement, test each in the original data, and subtract the average optimismEvery step of model building must be repeated in each resample; needs software

Steyerberg et al. (2001) compared these designs in samples drawn from a large trial data set. Split-sample analyses gave overly pessimistic estimates of performance with large variability. Bootstrapping gave stable estimates with low bias, and they recommended it for internal validation of logistic regression models. Collins et al. (2014) described a random split of one data set as a weak and inefficient design that does not constitute external validation.

new patients 0.753Apparent (same patients)0.814Bootstrap-corrected0.763Split sample, 200 randomsplits of 100 + 1000.5990.8610.60.70.80.9C-statistic
Simulated teaching data, the worked example below. The same 200 patients split at random 200 different ways gave C-statistics from 0.599 to 0.861, depending only on which patients fell in each half. The bootstrap-corrected estimate used all 200 patients and was close to the value in new patients.

The formula

Worked example: bootstrap optimism correction

Simulated teaching data: 200 patients, 37 deaths, 10 candidate predictors (3 real, 7 noise), 3.7 events per candidate predictor. Because the data were simulated, the model could also be tested in 100,000 new patients.

1. Fit the model in all 200 patientsC = 0.814 in those patients (apparent)2. Draw 200 patients with replacementand repeat every modelling step3. Optimism of this resample =C in the resample − C in the original 2004. Repeat steps 2 and 3 200 timesaverage optimism = 0.0515. Optimism-corrected C = 0.814 − 0.051 = 0.763In 100,000 new patients from the same population: C = 0.753
Harrell, Lee and Mark (1996) recommend that predictive accuracy be validated with bootstrapping or cross-validation before predictions are used in new patients. The corrected estimate comes from all 200 patients.

Corrected C = apparent C − average over resamples of (C of the resample model in its resample − C of the same model in the original data)

Apparent C
the model fitted and tested in the same 200 patients
Resample
200 patients drawn from the 200 with replacement
Optimism of one resample
how much better that resample model looks in its own resample than in the original patients
MeasureValueWhat it tells you
Apparent C-statistic0.814Too good: tested on the patients that built it
Average optimism (200 resamples)0.051Expected fall in new patients
Optimism-corrected C-statistic0.763The estimate to report
C-statistic in 100,000 new patients0.753Available only because the data were simulated
Average calibration slope of resample models in the original data0.74Predictions too extreme: the coefficients need shrinkage
Calibration slope in new patients0.76The bootstrap estimate was close

Calculated in Python (scikit-learn 1.7.2, statsmodels 0.14.5), unpenalised logistic regression, 200 resamples. The C-statistic of the true model in the new patients was 0.785: even a model with the right predictors loses some discrimination when its coefficients are estimated from 37 events.

Measuring performance

Does the model put patients in the right order, and are its risks right?

These are two different questions. Discrimination asks whether patients who have the event get higher predicted risks. Calibration asks whether a predicted risk of 20% means that about 20 in 100 such patients have the event.

Discrimination: the C-statistic

diedsurvived0.620.350.800.200.410.150.5500.51predicted risk2 discordant pairs
Made-up predicted risks for seven patients. Take every pair of one patient who died and one who survived. The C-statistic is the proportion of pairs in which the patient who died had the higher predicted risk: 10 of 12 = 0.83. 0.5 means no better than chance, 1 means perfect ranking.

For a yes/no outcome the C-statistic equals the area under the ROC curve (Housseine et al., 2022). TRIPOD+AI notes that it is called the c statistic or AUC for binary outcomes and the c index for time-to-event outcomes. For survival models, Harrell's C counts the comparable pairs in which the patient with the earlier event had the higher predicted risk. Somers' Dxy, reported by the R rms package, is 2 × (C − 0.5).

Calibration: intercept, slope and plot

Well calibratedpredicted riskintercept 0, slope 1Risks too high for everyonepredicted riskintercept below 0Risks too extremepredicted riskslope below 1observed
Schematic calibration curves, observed proportion against predicted risk. The dashed diagonal is perfect calibration.
  • Calibration-in-the-large (calibration intercept): compares the average predicted risk with the overall event rate. Target 0. Negative values mean the model overestimates risk, positive values that it underestimates (Van Calster et al., 2019).
  • Calibration slope: the spread of the predicted risks. Target 1. A slope below 1 means the risks are too extreme (Van Calster et al., 2019), the typical result of overfitting.
  • Calibration plot: observed proportion against predicted risk, by groups or with a smoothed curve. It shows where in the risk range the model goes wrong.
  • Hosmer-Lemeshow test: Van Calster et al. (2019) recommend against it: it groups patients arbitrarily, its P value does not show the type or size of miscalibration, and it has low power.

Steyerberg and Vergouwe (2014) proposed four measures for validation: calibration-in-the-large (A), calibration slope (B), discrimination with a concordance statistic (C), and clinical usefulness with decision-curve analysis (D).

External validation

Will the model work in another year or another hospital?

Internal validation estimates performance in new patients from the same population. External validation tests the finished model, unchanged, in patients who were not used to build it.

Hospital AHospital Banother regiondevelopmenttemporal validationgeographic validationinternal: bootstrap20152017201920212023made-up study plan
A made-up study plan. The model equation is fixed before the validation data are analysed.
  • Temporal validation: patients from the same centre in a different time period (Collins et al., 2014).
  • Geographic validation: patients from other hospitals, regions or countries.
  • Justice, Covinsky and Berlin (1999) separated reproducibility, accurate predictions in new patients from the same population, from transportability, accurate predictions in a different but plausibly related population. They noted that a prognostic system is often limited to a single historical period, geographic location, methodologic approach, disease spectrum or follow-up interval.

Why performance changes in a new setting

  • Different event rate: the average predicted risk no longer matches the observed rate, so calibration-in-the-large is wrong. Van Calster et al. (2019) note that calibration-in-the-large is irrelevant at internal validation but highly relevant at external validation.
  • Different strength of the predictors: measurement, treatment or case mix changes the effect of each predictor, and the calibration slope moves away from 1.
  • Narrower case mix: if patients are more alike, they are harder to rank, and the C-statistic falls even when the model is correct.

Updating a model starts with the simplest change. Van Calster et al. (2019) suggest that updating may start with changing the intercept to correct calibration-in-the-large. Nugawela et al. (2022) did the equivalent for a Cox model by recalibrating the baseline survival in each validation cohort.

Calibration is often left out. In a review of 78 external validation articles, 53 (68%) did not report evaluating calibration, and only 11 (14%) presented a calibration plot (Collins et al., 2014).

Interactive

Take a published model to a new hospital and watch the C-statistic, the calibration slope and the calibration intercept

You change the hospital's patients, not the model. See which change affects discrimination, which affects calibration, and what updating the intercept or slope repairs.

Try this: press "Sicker patients". The C-statistic hardly moves, but the model now predicts too few events and every dot sits above the diagonal. Then choose "Update the intercept" and watch calibration return while the C-statistic stays the same.

Teaching example, simulated: a published risk model, predicted log odds = −1.4 + 1.1 × risk score, applied to 1,000 patients in a new hospital. You change the new hospital, not the model.

0.0

Positive: more events than where the model was built

× 1.0

Below 1: the model's coefficients are too large for this hospital

× 1.0

A narrow case mix makes patients harder to tell apart

Update the model in this hospital
0.76C-statistic
1.01calibration slope (target 1)
-0.02calibration intercept (target 0)

The groups lie close to the diagonal: the predicted risks match what happened in this hospital. 235 events observed, 237.7 predicted (O/E 0.99).

0%0%25%25%50%50%75%75%100%100%predicted riskobserved proportion with the eventdashed diagonal:perfect calibrationdots: ten groupsof 100 patientsthin red line:logistic calibrationcurve

The bootstrap

How do you get a confidence interval when there is no formula?

The confidence interval for a mean comes from a formula. For a median, a ratio of two medians, or a C-statistic after model building, the formula is missing or unreliable. The bootstrap estimates the sampling variation directly from your data.

Original 15 stays23344566789111419306Resample 1233344566678911146Resample 2223444556789911145Resample 334667789111114141930309median… 2,000 resamples2.5th percentile of the 2,000 medians: 4 days97.5th percentile: 11 days95% percentile interval for the median: 4 to 11 days
Made-up teaching data: days in the ICU for 15 ventilated patients. Each resample draws 15 stays with replacement from the original 15. The median of each resample is recorded, and the spread of those medians shows how much the median would vary from sample to sample.
  1. Draw n patients from your n patients, with replacement.
  2. Calculate the statistic (median, ratio, C-statistic) in that resample.
  3. Repeat many times. IBM's SPSS documentation recommends at least 1,000 bootstrap samples for percentile and BCa intervals.
  4. Percentile interval: the 2.5th and 97.5th percentiles of the bootstrap statistics give the 95% interval.
  5. Bootstrap standard error: the standard deviation of the bootstrap statistics.

In the ICU data, 2,000 resamples gave a 95% percentile interval for the median of 4 to 11 days, with a bootstrap standard error of 1.60 days. For the mean (8.73 days) the percentile interval was 5.53 to 12.73 days, against 4.60 to 12.86 days from the t formula, which assumes the mean is normally distributed.

The bootstrap only resamples the patients you have. If the sample is small or unrepresentative, every resample shares that problem, and the interval can be too narrow. The bias-corrected and accelerated (BCa) interval is an adjusted version that SPSS describes as more accurate, at the cost of more computing time.

Interactive

Draw resamples one at a time, then thousands, and watch the percentile interval for the median form

Each resample is one version of your study that could have happened. The spread of their medians is the uncertainty in your median.

Try this: press "Draw 1 resample" a few times and see that some patients are picked twice and others not at all. Then press "Draw 1,000 more" twice and watch the histogram of medians fill in and the 95% interval settle.

Teaching data, made up: days in the ICU for 15 ventilated patients. Median 6 days, mean 8.7 days. No formula gives a simple confidence interval for this median.

Statistic
0resamples drawn
—95% percentile interval for the median, days

No resamples yet. The median of the original 15 patients is 6 days.

The 15 patients (days in ICU)051015202530red: picked in the last resampleopen circle: left outBootstrap medians25101520

The jackknife

What is the jackknife, and how is it different from the bootstrap?

The jackknife leaves out one patient at a time and recalculates the statistic, giving n estimates from n patients. Nothing is random: everyone who repeats it gets the same answer.

Jackknife SE = √[ (n − 1) ÷ n × Σ (θ₍ᵢ₎ − θ̄₍.₎)² ]

θ₍ᵢ₎
the statistic calculated with patient i left out
θ̄₍.₎
the average of the n leave-one-out values

For the mean ICU stay, the jackknife SE is 1.93 days, exactly the usual SD ÷ √n = 7.46 ÷ √15 = 1.93. For the median it behaves badly.

051015202530days in ICULeave out one of the 8 red stays: median 6.5 daysLeave out one of the 7 dark stays: median 6 daysjackknife SE of the median 0.93 · bootstrap SE 1.60
The same 15 stays. Because the median depends only on the middle values, leaving out one stay can give only two answers, so the jackknife sees almost no variation: jackknife SE 0.93 days, against a bootstrap SE of 1.60 days from 2,000 resamples.

The jackknife is also used to find influential patients: if leaving out one patient changes a coefficient a lot, that patient drives the result. SPSS saves this as DfBeta, the estimated change in a coefficient if a case is removed.

Sensitivity analysis

Would the conclusion change if an assumption were different?

Every analysis rests on assumptions about missing data, outliers, the analysis method and the outcome definition. A sensitivity analysis repeats the analysis under other plausible assumptions and asks whether the conclusion stays the same.

ICH E9(R1) (2019) defines sensitivity analysis as a series of analyses that explore whether inferences from the main estimator hold when its modelling assumptions are departed from and when the data have limitations. The analyses should focus on the same estimand and be pre-specified. The addendum gives tipping point analysis as an example: finding how far an assumption must move before the interpretation changes.

no differenceComplete cases only14/90 vs 30/92Missing = no event (both arms)14/100 vs 30/100Missing = event (both arms)24/100 vs 38/100Best case for the drug14/100 vs 38/100Worst case for the drug24/100 vs 30/100−40−30−20−10010risk difference, drug minus placebo (percentage points)
Made-up trial for teaching: 100 patients per arm, outcome missing for 10 on the drug and 8 on placebo. The result holds under every assumption except the most extreme one. A tipping point analysis (placebo missing counted as no event) shows the 95% CI first crosses zero when 5 of the 10 missing drug patients are counted as events: risk difference −11.0 points (−22.8 to 0.8).

Common sensitivity analyses

Thabane et al. (2013) list questions such as whether the results change with:

  • a different definition of the outcome, for example a different cut-off;
  • a different method of analysis;
  • a different way of handling missing data;
  • protocol deviations and degree of compliance;
  • ignoring correlation between repeated measurements in a patient;
  • a non-normal distribution or outliers.

Choosing a sensitivity analysis

Morris, Kahan and White (2014) proposed three questions:

  1. Does the proposed sensitivity analysis address the same question as the primary analysis?
  2. Is it possible for it to arrive at a different conclusion?
  3. If it does, is there a genuine degree of uncertainty as to which analysis will be believed?

CONSORT 2025 lists subgroup and sensitivity analyses as separate kinds of additional analysis. An analysis that ignores clustering in a cluster-randomised trial is not a useful sensitivity analysis, because there would be no uncertainty about which result to believe (Morris et al., 2014).

Limits of models

How far can you trust a model's conclusions?

A model that fits the data well is one plausible description of them, not proof that its structure is the true one. Its conclusions deserve trust in proportion to the checks it has passed.

  1. Assumptions checked: linearity of continuous predictors, proportional hazards for Cox models, independence of observations.
  2. No single patient decides the result: leave-one-out (jackknife) or DfBeta checks for influential observations.
  3. Optimism measured: bootstrap internal validation, with the corrected C-statistic and calibration slope.
  4. Conclusions unchanged under other plausible assumptions: pre-specified sensitivity analyses.
  5. Performance confirmed elsewhere: temporal and geographic validation, with calibration reported.
  6. Measurement comparable: Van Calster et al. (2019) point out that medical data contain measurement error, for example biomarker values that vary with assay kits, which can change calibration between settings.

A model is a prediction built from past patients. When treatment, case mix or measurement changes, its predictions need to be checked again.

Decide

Which approach does your study need?

Answer the questions in order.

What are you trying to do?

Which approach: all possible answers
  • Bootstrap internal validation: Build the model on all patients. Estimate optimism in 200 or more bootstrap resamples, repeating every modelling step, and report the corrected C-statistic and calibration slope. Do not split the data at random.
  • Bootstrap validation, then temporal or geographic validation: Develop and internally validate the model, then test it unchanged in the later period or the other hospital: C-statistic, calibration plot, slope and intercept.
  • External validation: Apply the published equation exactly. Report the C-statistic, a calibration plot, calibration intercept and slope, and update the intercept if the average risk is wrong.
  • Bootstrap percentile interval: Resample patients with replacement at least 1,000 times, calculate the statistic each time, and take the 2.5th and 97.5th percentiles.
  • Sensitivity analysis: Plan analyses that answer the same question under different assumptions (missing data, outliers, analysis method), and report whether the conclusion changes.

Comparison

Pairs that residents confuse

Internal or external validation?

FeatureInternal validationExternal validation
DataThe development data, reused (bootstrap, cross-validation)New patients: a later period, another hospital or region
EstimatesOptimism: performance in new patients from the same populationPerformance in a different time or place
Calibration-in-the-largeNot informative (average predicted risk matches the event rate)Highly informative
WhenAlways, when a model is developedBefore the model is used elsewhere
TRIPOD+AIItem 12c: method for internal validationItems 12e, 12f, 23a and 24: measures, updating, performance

Discrimination or calibration?

FeatureDiscriminationCalibration
QuestionDo patients with the event get higher predicted risks?Do predicted risks match observed proportions?
MeasuresC-statistic (AUC), Harrell's C for survivalCalibration intercept, calibration slope, calibration plot, O/E ratio
Changed by a new event rateLittleYes: calibration-in-the-large moves
Repaired by updating the interceptNoYes, for calibration-in-the-large
Matters most forRanking and triageTelling a patient their risk, and deciding by a risk threshold

Bootstrap or jackknife?

FeatureBootstrapJackknife
Resamplesn patients drawn with replacement, repeated 1,000 times or moren data sets, each leaving out one patient
RandomYes (set a seed to repeat it)No
GivesStandard error, percentile and BCa intervals, optimismStandard error, bias estimate, influence of each patient
Median in the ICU dataSE 1.60 daysSE 0.93 days: only two leave-one-out values
IntroducedEfron, 1979Quenouille, 1949

In a real paper

Internal and external validation in published studies

Open-access paper · CC BY-NC-ND 4.0

Housseine N, Rijken MJ, Weller K, Nassor NH, Gbenga K, Dodd C, et al. Development of a clinical prediction model for perinatal deaths in low resource settings. EClinicalMedicine. 2022;44:101288.

The study: A prospective cohort of women admitted in labour at the tertiary hospital in Zanzibar. The authors first tested an existing stillbirth model from Nigeria in these women, then developed a new model for perinatal death and validated it internally with bootstrapping.

What the authors wrote
“The new model included 15 clinical predictors and showed promising discriminative and calibration performance after internal validation (optimism adjusted c-statistic of 0·78, optimism adjusted calibration slope =0·94).”
In plain words

Internal validation: the model was refitted in 200 bootstrap samples and each refitted model was tested in the original data. Optimism adjusted c-statistic 0·78: the apparent value of 0·80 minus the estimated optimism. Calibration slope 0·94: slightly below 1, so predictions were a little too extreme; the authors applied a shrinkage factor of 0·95 to the coefficients.

ReportedValueWhat it means
Mother-baby pairs analysed5747The development data set
c-statistic before and after internal validation0·80 and 0·78Apparent and optimism-adjusted discrimination
Optimism adjusted calibration slope0·94Close to 1: little overfitting
Bootstrap shrinkage factor0·95Applied to the coefficients of the final model
Existing Nigerian model in Zanzibarc-statistic 0·57External validation failed: it had shown 0·80 after internal validation in Nigeria
Check these when you read it
  • Whether a reporting guideline was followed: “The reporting of the study adheres to the TRIPOD guidelines”.
  • Events per candidate predictor: the authors aimed for “at least 10 events per candidate predictor”.
  • Whether the model has been validated elsewhere: “Before routine implementation, external validation and usefulness should be determined in future studies.”
Open-access paper · CC BY 4.0

Nugawela MD, Gurudas S, Prevost AT, Mathur R, Robson J, Sathish T, et al. Development and validation of predictive risk models for sight threatening diabetic retinopathy in patients with type 2 diabetes to be applied as triage tools in resource limited settings. EClinicalMedicine. 2022;51:101578.

The study: Cox models for sight-threatening diabetic retinopathy were developed in 40,334 adults with type 2 diabetes in London general practices, then validated geographically in 102,672 people in Wales and 17,509 people at a diabetes centre in Chennai, India.

What the authors wrote
“Observed over expected (O/E) ratios show that all models applied in the Indian datasets, were on average over-predicting risks at 3 years and risks being slightly under-predicted in Wales at 3-years.”
In plain words

Observed over expected: events seen ÷ events the model predicted. Over-predicting in India: fewer patients developed sight-threatening retinopathy than the UK equations predicted, so the O/E ratio was below 1. In Wales it was slightly above 1. Discrimination remained good (Model 1 C statistic 0.775 in Wales and 0.823 in India), so the main problem was the average risk, which recalibration of the baseline survival corrected.

ReportedValueWhat it means
Model 1 C statistic, development0·832 (0·822 to 0·842)Discrimination in London
Model 1 C statistic, India0.823 (0.810 to 0.836)Ranking of patients almost as good in Chennai
Model 1 calibration slope, India1.015 (0.939 to 1.091)Spread of predicted risks about right
Model 1 O/E ratio, India0.429Observed events were less than half of those predicted
Re-calibrated O/E ratio, India1.026After updating the baseline survival
Check these when you read it
  • How the validation populations differed: “Eligibility criteria for MDRF was different to that of the UK cohorts”, and the highest proportion with background retinopathy, 5,418 (31%), was among the Indian patients.
  • Whether calibration, not only the C statistic, is reported in each validation cohort (here: slope, O/E ratio and a calibration plot).
  • Whether an updated model is presented for local use: “Models were updated in each external validation cohort, if required, by re-calibrating the baseline survival function at 3-years.”

How to run it

Validation and bootstrap in SPSS, R and jamovi

Checked against the IBM SPSS Statistics 24 manuals, IBM's online documentation, the CRAN reference manuals and the jamovi documentation.

SPSS

  1. Analyze > Regression > Binary Logistic... Select the outcome and the covariates.
  2. Save: tick Probabilities to save each patient's predicted risk as a new variable.
  3. Analyze > ROC Curve... Put the saved probability in Test Variable and the outcome in State Variable, and give the positive value. The output gives the area under the curve with its confidence interval. Recent versions also have a newer ROC Analysis procedure.
  4. Bootstrap confidence intervals: in a procedure that supports bootstrapping (Frequencies, Explore, Binary Logistic Regression, Cox Regression and others), click Bootstrap, select Perform bootstrapping, set the Number of samples (at least 1,000 for percentile and BCa intervals), set a seed, and choose Percentile or Bias corrected accelerated (BCa).

R (rms, boot and pROC packages)

library(rms)
fit <- lrm(died ~ age + lactate + asa + shock, data = d, x = TRUE, y = TRUE)
v <- validate(fit, method = "boot", B = 200)   # default B is 40
v                  # index.orig, training, test, optimism, index.corrected
                   # rows include Dxy, R2, Intercept, Slope
0.5 + v["Dxy", "index.corrected"] / 2          # optimism-corrected C (Dxy = 2(C - 0.5))
plot(calibrate(fit, method = "boot", B = 200))  # bias-corrected calibration curve

library(pROC)
r <- roc(d$died, predict(fit, type = "fitted"))
ci.auc(r)                                       # DeLong method by default
ci.auc(r, method = "bootstrap", boot.n = 2000)

library(boot)
med <- function(x, i) median(x[i])             # statistic(data, indices)
b <- boot(icu_days, med, R = 2000)
boot.ci(b, type = c("perc", "bca"))
  • validate() and calibrate() need x = TRUE, y = TRUE in the fit. For Cox models use cph() with the same arguments.
  • If you selected predictors (for example by backward elimination), the selection must be repeated inside every resample; validate() does this with bw = TRUE.
  • In boot() the statistic function receives the data and a vector of indices that define the resample.

jamovi

Analyses → Regression → 2 Outcomes (Binomial) fits logistic regression. The Prediction drop-down gives a classification table. For bootstrap internal validation, use the R code above.

How to report it

What to write in your thesis or paper

Follow TRIPOD+AI (2024), which supersedes TRIPOD 2015. For validation, the relevant items include:

  • 10: how the study size was arrived at, and why it was sufficient.
  • 12c: the type of model, all model-building steps, and the method for internal validation.
  • 12e: all measures and plots used to evaluate performance (discrimination, calibration, clinical utility).
  • 12f and 24: any model updating, such as recalibration, and its results.
  • 23a: performance estimates with confidence intervals.
  • 26: limitations, including sample size and overfitting.

Worked sentence, with the teaching numbers:

“The model was developed in 200 patients, of whom 37 died within 30 days (3.7 events per candidate predictor). The apparent C-statistic was 0.81. Internal validation with 200 bootstrap resamples, repeating all modelling steps, estimated an optimism of 0.05, giving an optimism-corrected C-statistic of 0.76. The optimism-corrected calibration slope was 0.74, indicating predictions that were too extreme, so the coefficients were shrunk before presentation. The model has not been externally validated.”

For a sensitivity analysis in a trial, state the assumption varied, whether the analysis was pre-specified, and the result of each analysis alongside the primary one (CONSORT 2025, item 21d).

By specialty

Validation and bootstrap problems by specialty

A resident builds a score for death within 30 days of emergency laparotomy from 10 candidate predictors in 200 patients, 37 of whom died.

With 3.7 events per candidate predictor the model is overfitted. Report the bootstrap-corrected C-statistic and calibration slope, and use fewer predictors or shrinkage.

Common myths

Common mistaken beliefs

  • Myth: A high C-statistic in my own data shows that the score works.

    That is the apparent performance, and it is optimistic. In the worked example it fell from 0.814 to 0.763 after bootstrap correction.

  • Myth: Splitting the data into a training half and a test half is the best validation.

    A random split builds the model on fewer patients and gives unstable, pessimistic estimates (Steyerberg et al., 2001). In the teaching data, 200 splits gave C-statistics from 0.599 to 0.861.

  • Myth: A good C-statistic means the predicted risks are right.

    Discrimination and calibration are separate. A model can rank patients well while every predicted risk is twice too high.

  • Myth: A non-significant Hosmer-Lemeshow test proves good calibration.

    The test has low power and does not show the type or size of miscalibration. Van Calster et al. (2019) recommend a calibration plot with intercept and slope instead.

  • Myth: The bootstrap creates new data, so it can rescue a small study.

    It resamples the same patients. It measures the uncertainty in your sample; it cannot add information that the sample does not contain.

  • Myth: Any extra analysis counts as a sensitivity analysis.

    Morris et al. (2014) require a sensitivity analysis to address the same question as the primary analysis. CONSORT 2025 lists subgroup and sensitivity analyses separately.

Why this matters to you

Five consequences of skipping validation

  1. Protocol or paper sent back

    TRIPOD+AI item 12c asks for the method of internal validation. "The model was tested on the study patients" does not meet it.

  2. An inflated result in your thesis

    An apparent C-statistic and a model with 3.7 events per candidate predictor overstate how well the score will work.

  3. Questions you cannot answer at the viva

    "What is the calibration slope?" and "Was it validated in other patients?" need numbers, not a P value from the Hosmer-Lemeshow test.

  4. Misreading papers

    A model reported without calibration or external validation is not ready for your patients: 68% of external validation articles in one review did not report calibration.

  5. Harm to patients

    A score that over-predicts risk in your population, as the UK retinopathy equations did before recalibration in India, sends low-risk patients for unnecessary tests, and one that under-predicts delays care.

History

History of resampling and model validation

  1. 1949

    Maurice Quenouille

    Proposed the method later called the jackknife, in "Approximate tests of correlation in time-series", and expanded it in "Notes on bias in estimation" (1956).

  2. 1974

    M. Stone

    Published "Cross-validatory choice and assessment of statistical predictions", applying cross-validation to choosing and assessing predictions.

  3. 1979

    Bradley Efron

    Introduced the bootstrap in "Bootstrap methods: another look at the jackknife".

  4. 1982

    Frank Harrell and colleagues

    Published "Evaluating the yield of medical tests" in JAMA. Later authors cite it as the origin of the C-index for survival data.

  5. 1996

    Frank Harrell, Kerry Lee and Daniel Mark

    Described overfitted models and recommended that predictive accuracy be validated with bootstrapping or cross-validation before predictions are used in new patients.

  6. 1999

    Amy Justice, Kenneth Covinsky and Jesse Berlin

    Separated reproducibility from transportability, and proposed a hierarchy of generalisability across periods, places, methods, disease spectrum and follow-up.

  7. 2001

    Ewout Steyerberg and colleagues

    Showed that split-sample validation is inefficient and recommended bootstrapping for internal validation of logistic regression models.

  8. 2014

    Gary Collins and colleagues

    Reviewed 78 external validation articles: 68% did not report calibration.

  9. 2015

    TRIPOD group

    Published the TRIPOD statement, a 22-item checklist for reporting prediction model development and validation.

  10. 2019

    Ben Van Calster and colleagues

    Published "Calibration: the Achilles heel of predictive analytics", defining calibration intercept and slope and recommending against the Hosmer-Lemeshow test.

  11. 2024

    TRIPOD+AI group

    Published TRIPOD+AI, a 27-item checklist for models built with regression or machine learning, which supersedes TRIPOD 2015.

Guidelines

Validation and sensitivity analysis in guidelines

TRIPOD 2015, items 10b and 16

“Specify type of model, all model-building procedures (including any predictor selection), and method for internal validation.” “Report performance measures (with CIs) for the prediction model.”

TRIPOD+AI 2024, items 12c, 12e and 23a

“Specify the type of model, rationale, all model building steps, including any hyperparameter tuning, and method for internal validation”. “Specify all measures and plots used (and their rationale) to evaluate model performance (eg, discrimination, calibration, clinical utility)”. “Report model performance estimates with confidence intervals”.

SAMPL guidelines (Lang and Altman)

For regression analyses: “Specify whether and how the model was validated.” For supplementary analyses: “Describe methods used for any ancillary analyses, such as sensitivity analyses, imputation of missing values, or testing of assumptions underlying methods of analysis.”

CONSORT 2025, item 21d

“Methods for any additional analyses (eg, subgroup and sensitivity analyses), distinguishing prespecified from post hoc”.

ICH E9(R1) (2019), section A.5.2.1

One or more analyses focused on the same estimand should be pre-specified to investigate the assumptions of the main estimator, for example by a tipping point analysis.

Reading a paper

Five checks on any prediction model paper

  • Are the number of events and the number of candidate predictors both reported?
  • Is the C-statistic apparent, optimism-corrected, or from external data?
  • Is calibration reported with a plot, intercept and slope, and not only a Hosmer-Lemeshow P value?
  • Was the model validated in patients from another time or place, and was it updated there?
  • Were all modelling steps, including predictor selection, repeated inside the bootstrap or cross-validation?

Why is it called that?

Word surgery

“Validation”

In everyday speech

Official approval that something is correct or genuine.

In research

Measuring how well a model performs in patients, preferably ones not used to build it. A validated model can still perform badly.

“Optimism”

In everyday speech

A cheerful expectation that things will turn out well.

In research

The amount by which a model's performance in its own development patients exceeds its performance in new patients.

“Calibration”

In everyday speech

Adjusting an instrument so that its readings are correct.

In research

How closely predicted risks agree with the observed proportion of patients who have the event.

Memory trick

Apparent minus optimism gives corrected. C for order, slope and intercept for risk. Resample the same patients for a CI, test in new patients for validation.

Bootstrap

a tab or loop at the back of a boot, used to pull the boot on (1870); "pull oneself up by one's bootstraps" by 1871

The bootstrap estimates uncertainty using only the sample itself, with no outside information.

Jackknife

jack-knife: "pocket knife larger than a pen-knife", 1711

A resampling method that leaves out one observation at a time.

Valid

Latin validus: "strong, effective, powerful, active"

A valid model gives predictions that hold in the patients it is used for.

Calibrate

"determine the caliber of", 1839, from caliber: the inside diameter of a gun barrel

In prediction, to check or adjust predicted risks against observed outcomes.

Optimism

Latin optimus: "the best"

Performance measured in the development data is the best case.

Sensitivity

from sensitive: Medieval Latin sensitivus "capable of sensation", from Latin sentire "feel, perceive"

A sensitivity analysis shows how much a result responds to a change in an assumption.

Exam answers

Model answer outlines

Sensitivity analysis

MD Community Medicine 2022
  1. Definition: analyses that repeat the main analysis under different plausible assumptions to see whether the conclusion changes (ICH E9(R1), 2019).
  2. Why: every analysis rests on assumptions (missing data, outliers, distribution, analysis method, outcome definition) that the data cannot fully test.
  3. Common types: missing data (complete case, best and worst case, multiple imputation), per-protocol against intention-to-treat, with and without outliers, alternative outcome definitions or cut-offs, allowing for clustering, different statistical models (Thabane et al., 2013).
  4. Choosing one (Morris et al., 2014): it must address the same question as the primary analysis, be able to give a different conclusion, and leave genuine uncertainty about which analysis to believe.
  5. Tipping point analysis: how far an assumption must move before the conclusion changes. Teaching trial: 5 of 10 missing drug patients counted as events make the CI cross zero.
  6. Planning and reporting: pre-specify in the protocol, and report methods and results with the primary analysis (CONSORT 2025 item 21d; SAMPL).
  7. Interpretation: if the conclusions stay the same, confidence increases. If they change, report both and discuss which assumption is more plausible.

Randomised clinical trials: external validity, allocation concealment, stratification, sensitivity analysis and Fragility Index

DM Critical Care Medicine 2022
  1. External validity: whether the results can be reasonably applied to a definable group of patients in a particular clinical setting in routine practice (Rothwell, 2005). Depends on setting, eligibility, the intervention as delivered, and outcomes. CONSORT 2025 item 30 includes generalisability under trial limitations.
  2. Allocation concealment: keeps clinicians and participants unaware of upcoming assignments until the patient is enrolled (Schulz and Grimes, 2002). Methods: central computer or telephone randomisation, sequentially numbered opaque sealed containers (CONSORT 2025 item 18). It is possible in every trial, unlike blinding.
  3. Stratification: separate randomisation lists, usually in blocks, within categories of a strong prognostic factor (centre, disease severity) so that the arms are balanced for it. Reported under type of randomisation (CONSORT 2025 item 17b). ICH E9: more than two or three stratification factors are rarely necessary.
  4. Sensitivity analysis: repeating the analysis under different assumptions, such as the handling of missing outcomes, to see whether the conclusion changes; pre-specified and reported separately from subgroup analyses (CONSORT 2025 item 21d).
  5. Fragility Index (Walsh et al., 2014): for a statistically significant dichotomous or time-to-event result, the number of patients in the group with the smallest number of events whose status must change from non-event to event before P exceeds 0.05. In 399 trials the median was 8, and 25% had a Fragility Index of 3 or less. Compare it with the number lost to follow-up: in 53% of trials the index was smaller.

More detail on randomisation and concealment is in the clinical trials chapter.

Bootstrap and jackknife resampling

  1. Purpose: to estimate the uncertainty (standard error, confidence interval) or bias of a statistic from the data themselves, when no reliable formula exists.
  2. Bootstrap (Efron, 1979): draw n observations with replacement from the n, compute the statistic, repeat 1,000 or more times. SE = SD of the bootstrap statistics. Percentile 95% CI = 2.5th and 97.5th percentiles. The BCa interval is an adjusted interval, more accurate but slower to compute.
  3. Example: median ICU stay of 15 patients 6 days, bootstrap 95% CI 4 to 11 days (2,000 resamples).
  4. Jackknife (Quenouille, 1949): leave out one observation at a time to give n estimates. SE = √[(n − 1)/n × Σ(θ₍ᵢ₎ − θ̄)²]. Deterministic. Also shows influential observations.
  5. Limitation of the jackknife: poor for non-smooth statistics such as the median. Example: SE 0.93 days against a bootstrap SE of 1.60, because the leave-one-out medians take only two values.
  6. Uses in medicine: CIs for medians, ratios and C-statistics; internal validation of prediction models (optimism correction); checking the stability of regression coefficients.
  7. Limitations of both: they cannot correct a biased or unrepresentative sample, and the bootstrap needs enough observations to represent the population.
  8. Software: R boot (boot, boot.ci type "perc"), SPSS Bootstrap option.

Validation of a clinical prediction model

  1. Why: apparent performance in the development data is optimistic because of overfitting.
  2. Performance measures: discrimination (C-statistic), calibration (intercept, slope, plot), clinical usefulness (decision curves) (Steyerberg and Vergouwe, 2014).
  3. Internal validation: bootstrap optimism correction preferred; split sample inefficient (Steyerberg et al., 2001). Example: apparent C 0.814, optimism 0.051, corrected 0.763.
  4. External validation: temporal (same centre, later period), geographic (other centres or countries). Reproducibility versus transportability (Justice et al., 1999).
  5. Updating: recalibrate the intercept first, then slope, then refit if needed (Van Calster et al., 2019).
  6. Real examples: Housseine et al. (2022), a Nigerian stillbirth model had C 0.57 in Zanzibar. Nugawela et al. (2022), retinopathy models over-predicted in India (O/E 0.429) until recalibrated.
  7. Reporting: TRIPOD+AI (2024), 27 items, which supersedes TRIPOD 2015.

The one thing to remember

A model always looks best in the patients it was built on, so report the bootstrap-corrected C-statistic and the calibration slope, and test it in patients from another time or place before anyone relies on its risks.

Worked examples and interactive elements use made-up or simulated data for teaching. Numbers were calculated in Python (NumPy 2.2.6, scikit-learn 1.7.2, statsmodels 0.14.5, SciPy 1.15.3) and checked against the interactive elements' own code. Risk differences use Wald confidence intervals.

Sources: Quenouille MH. J R Stat Soc Ser B 1949;11(1):68–84 (doi:10.1111/j.2517-6161.1949.tb00023.x). Quenouille MH. Biometrika 1956;43(3/4):353 (doi:10.2307/2332914). Stone M. J R Stat Soc Ser B 1974;36(2):111–33 (doi:10.1111/j.2517-6161.1974.tb00994.x). Efron B. Ann Stat 1979;7(1) (doi:10.1214/aos/1176344552). Harrell FE et al. JAMA 1982;247(18):2543–6 (PMID 7069920). Harrell FE, Lee KL, Mark DB. Stat Med 1996;15(4):361–87 (PMID 8668867). ICH E9 Statistical Principles for Clinical Trials, 1998. Justice AC, Covinsky KE, Berlin JA. Ann Intern Med 1999;130(6):515–24 (doi:10.7326/0003-4819-130-6-199903160-00016). Steyerberg EW et al. J Clin Epidemiol 2001;54(8):774–81 (doi:10.1016/s0895-4356(01)00341-9). Schulz KF, Grimes DA. Lancet 2002;359:614–8 (PMID 11867132). Rothwell PM. Lancet 2005;365:82–93 (PMID 15639683). Thabane L et al. BMC Med Res Methodol 2013;13:92 (doi:10.1186/1471-2288-13-92). Collins GS et al. BMC Med Res Methodol 2014;14:40 (doi:10.1186/1471-2288-14-40). Morris TP, Kahan BC, White IR. BMC Med Res Methodol 2014;14:11 (doi:10.1186/1471-2288-14-11). Steyerberg EW, Vergouwe Y. Eur Heart J 2014;35(29):1925–31 (doi:10.1093/eurheartj/ehu207). Walsh M et al. J Clin Epidemiol 2014;67(6):622–8 (PMID 24508144). Collins GS et al. TRIPOD statement. BMJ 2015;350:g7594 (PMID 25569120); checklist from BMC Med 2015;13:1 (PMC4284921). Lang TA, Altman DG. SAMPL guidelines. Int J Nurs Stud 2015;52(1):5–9 (doi:10.1016/j.ijnurstu.2014.09.006). Van Calster B et al. BMC Med 2019;17:230 (doi:10.1186/s12916-019-1466-7). ICH E9(R1) addendum on estimands and sensitivity analysis, adopted 20 November 2019. Housseine N et al. EClinicalMedicine 2022;44:101288 (doi:10.1016/j.eclinm.2022.101288). Nugawela MD et al. EClinicalMedicine 2022;51:101578 (doi:10.1016/j.eclinm.2022.101578). Collins GS et al. TRIPOD+AI statement. BMJ 2024;385:e078378 (doi:10.1136/bmj-2023-078378). Hopewell S et al. CONSORT 2025 statement. BMJ 2025;389:e081123. IBM SPSS Statistics 24 manuals (Bootstrapping, Regression, Statistics Base, Advanced Statistics). R packages rms 8.1-1, Hmisc 5.3-0, boot 1.3-32 and pROC 1.19.1, CRAN reference manuals. jamovi documentation.

Further reading: Indrayan A. Medical Biostatistics, sections on validation of models, sensitivity analysis and resampling. Jawlik A. Statistics from A to Z: Confusing Concepts Clarified. Wiley; 2016 (Sampling Distribution).

Past papers

TNMGRMU questions on bootstrap and model validation

Questions from MD, MS, DM, MCh and Ph.D. papers that this chapter helps you answer. Tap a sitting to open the university's own question paper.

  1. ×1Sensitivity AnalysisMD Community Medicine · May 2022
  2. ×1Regarding randomised clinical trials, explain the following terms: a. External validity. b. Allocation concealment. c. Stratification. d. Sensitivity analysis. e. Fragility IndexDM Critical Care Medicine · Aug 2022