FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Generalization and Leakage

Design evaluation splits and training pipelines that estimate performance on unseen users, patients, devices, or future time without leaking evidence.

Freshness: current•12 min read•Machine Learning Foundations
Full Technical Reference Document

Mental model

Generalization is performance on fresh examples drawn from the deployment distribution, not a property that a high training score can certify. A test estimate is useful only when its split reflects the unit and time direction of future use, and when every learned preprocessing or selection step is confined to training data. Leakage makes held-out evidence look better than it is.

Theory

Let PP be the joint distribution of future inputs and labels, ff a fitted model, and ℓ\ell the task loss. The deployment risk is an expectation under PP; a finite test set estimates it with a sample average:

RP(f)=E(X,Y)∼P ⁣[ℓ(f(X),Y)],R^S(f)=1n∑i=1nℓ(f(xi),yi).R_P(f)=\mathbb{E}_{(X,Y)\sim P}\!\left[\ell(f(X),Y)\right], \qquad \widehat{R}_S(f)=\frac{1}{n}\sum_{i=1}^{n}\ell(f(x_i),y_i).

Here S={(xi,yi)}i=1nS=\{(x_i,y_i)\}_{i=1}^{n} is the evaluation sample and nn its example count. Both risks are in the units of ℓ\ell: 0–1 loss is a fraction of errors, while squared error has squared-target units. The difference between empirical and deployment risk is the generalization gap. A held-out score estimates that gap only when the sample construction is appropriate; a random split does not make correlated records independent.

The split unit should match the unit expected to be new in production. If future requests come from unseen patients, keep all scans from one patient in one partition. If the model predicts next month’s demand for existing stores, hold out later time and use only information available at each prediction date. The split must happen before fitting scalers, imputers, feature selectors, encoders, or thresholds. Putting those transformations in a pipeline makes their fit scope explicit: each training fold learns its parameters, then applies them unchanged to its held-out fold.

Model selection is part of training. Trying many architectures, prompts, feature sets, or thresholds and retaining the one with the best validation score adapts the model to that validation sample. A final test set should remain untouched until the selection procedure is fixed. When data is scarce, nested cross-validation separates inner-loop selection from outer-loop evaluation; its uncertainty still depends on how representative and independent the folds are. Confidence intervals around a score cannot fix a split that samples the wrong population.

Worked leakage calculation

Suppose a medical imaging set contains 500 patients with four scans each, or 2,000 images. If each image is independently assigned 80 percent to training and 20 percent to test, a patient appears in both partitions unless all four scans land on one side. The probability of that overlap is 1−0.84−0.24=0.58881-0.8^4-0.2^4=0.5888, so about 500×0.5888≈294500\times0.5888\approx294 patients are expected to leak across the split. The model can recognize patient-specific scanner texture or anatomy in the test set. A patient-group split removes that identity overlap and usually gives a harder but more relevant estimate for unseen patients.

Define the future population and independent unit
Partition groups or future time before fitting transforms
Fit models and select settings inside training folds
Evaluate once on an untouched target-like holdout
Monitor drift and refresh evidence with a new cohort
Conceptual teaching model synthesized from:vapnik-stat-learning-1995,hastie-esl-2009

Trade-offs

A group split may place fewer independent units in each fold than a row split, which widens uncertainty even when the raw row count is large. Repeated cross-validation can reduce dependence on one lucky partition, but it costs compute and overlapping folds do not create independent datasets. A time-based split preserves chronology, yet a single cutoff may mix seasonal events with long-term drift; rolling-origin evaluation shows whether performance changes as the cutoff moves. Choose the simplest evaluation that reproduces the deployment sampling process, then report the number of independent groups or time windows as well as records.

Exploratory validation can be useful while a team narrows hypotheses. The trade-off is that every decision informed by the same scores adds selection pressure. Keep a versioned experiment log, predeclare the primary metric and slices, and reserve a final cohort for the decision that controls release. If that cohort influences threshold selection or product tuning, it has become validation data and needs a new independent test for an honest final estimate.

Failure modes and misconceptions

Group leakage occurs when sibling records cross partitions. Time leakage occurs when training features include information computed after the prediction timestamp, such as a future rolling average or a label-derived count. Preprocessing leakage occurs when the test distribution influences learned means, vocabulary, imputation values, or selected features. Selection leakage occurs when a team repeatedly inspects the final test and chooses the best model or threshold. Each case makes the evaluation procedure depend on information that would not be available at the corresponding deployment decision.

Distribution shift is different from leakage. A perfectly isolated test set can still be stale: a sensor revision, pricing policy, new geography, or change in user mix can move PP. Treat a score as evidence for a stated population and time period, not a lifetime guarantee. Monitor input and label slices after launch, and collect new evaluation labels using the same target definition. A model that fails a new region should not be rescued by repartitioning until the old test score rises.

Decision scenario

A churn model scores 0.91 AUROC on a random split of weekly customer records, but account managers report missed churn among newly acquired customers. Many customers have several weeks in both partitions, and a feature uses a rolling count whose window extends past the prediction date. Rebuild the evaluation around customer groups and forward time, compute every rolling feature as of the prediction timestamp, and fit preprocessing only inside each training fold. Keep the final future cohort sealed until thresholds are chosen, then report AUROC and recall by customer tenure.

Learning outcomes

  • Distinguish deployment risk from a finite-sample test score and state the population a score represents.
  • Choose group, temporal, or nested validation based on the unit and direction of future prediction.
  • Identify leakage in data splitting, preprocessing, feature construction, and repeated model selection.

Implementation: split by subject before fitting transforms

This example keeps four observations from each synthetic patient together. The pipeline fits its scaler only on the training patients, so test statistics do not flow back into preprocessing.

python
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GroupShuffleSplit
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
​
rng = np.random.default_rng(17)
patients = np.repeat(np.arange(500), 4)
patient_signal = np.repeat(rng.normal(size=500), 4)
features = np.column_stack([
patient_signal + rng.normal(scale=0.35, size=patients.size),
rng.normal(size=patients.size),
])
labels = (patient_signal + rng.normal(scale=0.8, size=patients.size) > 0).astype(int)
splitter = GroupShuffleSplit(n_splits=1, test_size=0.2, random_state=23)
train, test = next(splitter.split(features, labels, groups=patients))
assert set(patients[train]).isdisjoint(set(patients[test]))
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(features[train], labels[train])
test_accuracy = model.score(features[test], labels[test])
assert 0.0 <= test_accuracy <= 1.0
print(f"held-out patient accuracy: {test_accuracy:.3f}")
Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.