TExcelTAD

External Validation

Every strategy so far splits one data set: one hospital's scans, one shop's customers, one year of sensor logs. Cross-validation then measures how well the model generalises to new rows from the same source. Deployment usually means a different source: another hospital with another scanner, another country, next year's customers. External validation tests the finished model, unchanged, on data collected independently, at a different place or time, ideally by different people. It is the strongest evidence a model will work elsewhere, and in medicine it is expected before a model is used on patients.

Internal, temporal and external

Kind Test data Answers
internal (holdout, k-fold) new rows from the same source does the model generalise beyond its training rows?
temporal the same source, a later period does it survive time? (Backtesting)
geographic / site another hospital, region, factory, device does it transfer to a new setting?
fully independent another team collects and evaluates is the result reproducible?

The model and every choice around it (features, preprocessing, threshold) are frozen before the external data is opened. If you tune on the external set, it becomes a validation set, and you need yet another one.

A model that does not travel

Two simulated hospitals. At hospital A, where the model is built, 30 % of patients have the condition. Hospital B has older patients, a scanner whose measurement of the first marker reads 0.8 units higher, and 15 % prevalence. The biology linking markers to the condition is the same at both.

python · try it yourself
import numpy as np
from sklearn.model_selection import cross_val_score, StratifiedKFold, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, accuracy_score, recall_score

rng = np.random.default_rng(0)
W = np.array([1.2, -0.8, 0.6, 0.0, 0.5])                 # true effect of five markers (same at both sites)

def site(n, age_mean, intercept, scanner_offset):
    age = rng.normal(age_mean, 8, n)
    X = rng.normal(0, 1, (n, 5))
    X[:, 4] = (age - 60) / 10                            # marker 4: age in decades from 60
    p = 1 / (1 + np.exp(-(intercept + X @ W)))
    y = (rng.random(n) < p).astype(int)
    X[:, 0] += scanner_offset                            # how the scanner reports marker 0
    return X, y

X_a, y_a = site(1500, age_mean=55, intercept=-0.7, scanner_offset=0.0)
X_b, y_b = site(1500, age_mean=68, intercept=-2.6, scanner_offset=0.8)
print(f"prevalence A {y_a.mean():.3f}   B {y_b.mean():.3f}")

model = make_pipeline(StandardScaler(), LogisticRegression())
cv_auc = cross_val_score(model, X_a, y_a, cv=StratifiedKFold(5, shuffle=True, random_state=0), scoring="roc_auc")
X_tr, X_te, y_tr, y_te = train_test_split(X_a, y_a, test_size=0.3, stratify=y_a, random_state=0)
model.fit(X_tr, y_tr)

for name, X, y in [("A internal test", X_te, y_te), ("B external", X_b, y_b)]:
    p = model.predict_proba(X)[:, 1]
    print(f"{name:16s} AUC {roc_auc_score(y, p):.3f}  accuracy {accuracy_score(y, p >= 0.5):.3f}"
          f"  recall {recall_score(y, p >= 0.5):.3f}  mean predicted risk {p.mean():.3f} vs observed {y.mean():.3f}")
print(f"5-fold CV AUC at A: {cv_auc.mean():.3f} +/- {cv_auc.std():.3f}")
prevalence A 0.348   B 0.173
A internal test  AUC 0.813  accuracy 0.753  recall 0.624  mean predicted risk 0.361 vs observed 0.349
B external       AUC 0.825  accuracy 0.525  recall 0.938  mean predicted risk 0.591 vs observed 0.173
5-fold CV AUC at A: 0.836 +/- 0.005

Internally everything looks fine: cross-validated AUC 0.836 with a tiny spread, and on A's own held-out patients the mean predicted risk (0.361) matches the observed rate (0.349). At hospital B the ranking still works (AUC 0.825, about the same), but the probabilities are badly wrong: the model predicts an average risk of 0.591 where 0.173 is observed, flags most patients (recall 0.938) and gets only 0.525 accuracy at the 0.5 threshold, worse than calling everyone healthy (0.827). Internal validation could not have revealed this, because hospital A's data contains neither the older patients, nor the scanner offset, nor the lower baseline risk.

Why it failed: compare the sites

Before blaming the model, look at how the data differs. Two quick checks: the standardised mean difference of each feature between sites, and a domain classifier (also called adversarial validation): train a model to tell site A from site B. If it can, with an AUC well above 0.5, the inputs differ, and its feature importances say where.

python · try it yourself
import numpy as np
from sklearn.model_selection import cross_val_score, StratifiedKFold
from sklearn.linear_model import LogisticRegression

rng = np.random.default_rng(0)
W = np.array([1.2, -0.8, 0.6, 0.0, 0.5])
def site(n, age_mean, intercept, scanner_offset):
    age = rng.normal(age_mean, 8, n)
    X = rng.normal(0, 1, (n, 5)); X[:, 4] = (age - 60) / 10
    y = (rng.random(n) < 1 / (1 + np.exp(-(intercept + X @ W)))).astype(int)
    X[:, 0] += scanner_offset
    return X, y
X_a, y_a = site(1500, 55, -0.7, 0.0)
X_b, y_b = site(1500, 68, -2.6, 0.8)

smd = (X_b.mean(axis=0) - X_a.mean(axis=0)) / np.sqrt((X_a.var(axis=0) + X_b.var(axis=0)) / 2)
print("standardised mean difference B - A per marker:", smd.round(2).tolist())

X_both = np.vstack([X_a, X_b]); is_b = np.r_[np.zeros(len(X_a)), np.ones(len(X_b))]
dom = LogisticRegression()
auc = cross_val_score(dom, X_both, is_b, cv=StratifiedKFold(5, shuffle=True, random_state=0), scoring="roc_auc")
print(f"domain classifier AUC {auc.mean():.3f}; coefficients", dom.fit(X_both, is_b).coef_[0].round(2).tolist())
standardised mean difference B - A per marker: [0.77, 0.0, -0.0, -0.02, 1.67]
domain classifier AUC 0.906; coefficients [0.82, 0.07, -0.02, -0.04, 2.15]

Marker 0 differs by 0.77 standard deviations (the scanner offset) and marker 4, age, by 1.67; the other markers match. The domain classifier separates the hospitals with AUC 0.906, and its two large coefficients point at the same two markers. The lower baseline risk at B does not show up here at all, because it is a change in P(y∣x)P(y \mid \mathbf{x}), not in P(x)P(\mathbf{x}); only labelled external data reveals it. Distribution Shift names these kinds of shift and how to detect them in production.

Many sites: leave one site out

When data comes from several sites, you can build external validation into development: train on all sites but one, test on the one left out, repeat. This is internal-external cross-validation, LeaveOneGroupOut with the site as the group (Stratified and Group CV). The spread across sites is the honest answer to "how well will it work in a new hospital?".

python · try it yourself
import numpy as np
from sklearn.model_selection import LeaveOneGroupOut, cross_val_predict
from sklearn.metrics import roc_auc_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

rng = np.random.default_rng(1)
W = np.array([1.2, -0.8, 0.6, 0.0, 0.5])
X_all, y_all, g_all = [], [], []
sites = {"north": (55, -0.7, 0.0), "south": (60, -1.2, 0.3), "east": (68, -2.6, 0.8), "west": (58, -1.0, -0.5)}
for gi, (name, (age_mean, b0, offset)) in enumerate(sites.items()):
    age = rng.normal(age_mean, 8, 600)
    X = rng.normal(0, 1, (600, 5)); X[:, 4] = (age - 60) / 10
    y = (rng.random(600) < 1 / (1 + np.exp(-(b0 + X @ W)))).astype(int)
    X[:, 0] += offset
    X_all.append(X); y_all.append(y); g_all += [gi] * 600
X, y, g = np.vstack(X_all), np.concatenate(y_all), np.array(g_all)

model = make_pipeline(StandardScaler(), LogisticRegression())
p = cross_val_predict(model, X, y, cv=LeaveOneGroupOut(), groups=g, method="predict_proba")[:, 1]
for gi, name in enumerate(sites):
    m = g == gi
    print(f"left-out site {name:5s} AUC {roc_auc_score(y[m], p[m]):.3f}   mean predicted risk {p[m].mean():.3f}"
          f"   observed {y[m].mean():.3f}")
left-out site north AUC 0.802   mean predicted risk 0.242   observed 0.307
left-out site south AUC 0.796   mean predicted risk 0.288   observed 0.275
left-out site east  AUC 0.776   mean predicted risk 0.537   observed 0.192
left-out site west  AUC 0.802   mean predicted risk 0.161   observed 0.325

Each site is predicted by a model trained on the other three. The AUC is stable (0.776 to 0.802), so the ranking transfers. Calibration does not: for the east site the model predicts 0.537 against 0.192 observed, for the west 0.161 against 0.325. A single random cross-validation over all 2400 patients would have averaged these errors away. The fix for this kind of failure is usually local recalibration (refitting the intercept, or Platt scaling, on some labelled data from the new site), followed by a fresh validation there.

What to report

An external validation report states where and when the external data was collected and how it differs (population, devices, prevalence, label definition); the frozen model and threshold; discrimination (AUC) and calibration on the external data (Calibration); results for important subgroups; and what was changed afterwards, if anything (for example recalibrating the intercept for the new prevalence, which then needs its own validation). Reporting guidelines such as TRIPOD for clinical prediction models list these items.

Pitfalls

  • Calling a random holdout "external". Rows from the same source are internal validation, however they were split.
  • Small external sets. 80 patients with 6 events cannot pin down an AUC; report confidence intervals (for example by bootstrapping the external set).
  • Tuning on the external data, then reporting it as external. Fix everything first.
  • Only checking discrimination. A shifted site often keeps a decent AUC but gets miscalibrated probabilities and wrong thresholds, which is what users act on.

Practice

  1. A sepsis model has AUC 0.86 in internal cross-validation and 0.72 at a second hospital. Name three things that could explain the drop.
Answer

Any three of: a different patient population (age, severity, case mix); different measurement (lab equipment, units, how often vitals are recorded); a different label definition or coding practice for sepsis; different treatment protocols that change the outcome; leakage in the internal evaluation (patients split across folds) that inflated 0.86; changes over time if the external data is from a later period.

  1. Why can a model's AUC stay the same at a new site while its accuracy at threshold 0.5 changes a lot?
Answer

AUC depends only on the ranking of patients. If the new site's prevalence or measurement offset shifts all risks up or down, the ranking can be preserved while the fixed threshold now falls in a different place of the score distribution, so the confusion matrix, accuracy and recall change.

Test yourself

What makes a validation 'external'?

  1. The test rows were never used for training
  2. The test data comes from an independent source, such as another site or a later period, and the model is frozen beforehand
  3. It uses k-fold cross-validation
  4. The test set is larger than the training set

A domain classifier separates site A from site B with AUC 0.95. What does that tell you?

  1. The model will work well at B
  2. The input distributions of the two sites differ strongly
  3. The labels are wrong at B
  4. Nothing

What does leave-one-site-out cross-validation estimate?

  1. Performance on new rows from the training sites
  2. Performance at a new site, with its spread across sites
  3. The best hyperparameters
  4. The training error