Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Concept · 25 min · revision 2

Validation Schemes That Mirror Production

Choose between k-fold, stratified, grouped and time-based cross-validation by asking what the model will meet in production, measure how a random split flatters a model that memorises users, see why the best of many cross-validation scores is optimistic, and keep the test set honest with nested cross-validation and a split manifest.

Contentsand lesson path

What you will learn

  • Design a validation scheme (stratified, grouped or time-based cross-validation plus an untouched test set) that mirrors deployment, and tune hyperparameters inside it without contaminating the test set.

Prerequisites: Machine Learning Fundamentals

01. Why it matters

A validation score is a forecast: "this is how well the model will do on the data it meets next". The forecast is only as good as the rehearsal behind it. If the validation rows are easier, or more familiar, than the rows the model will see in production, the score is too high, and you only find out after launch.

The rule of this lesson is simple to state: split the data the way production splits it. If the model will serve new customers, validation must use customers it has never seen. If it will predict next month, validation must come after the training data in time. You will see how much a wrong split can flatter a model, and how to tune hyperparameters without spoiling the final estimate.

Recall the vocabulary from the baselines lab: the training set fits the model, the validation set compares choices, and the test set is scored once at the end. Cross-validation (CV) repeats the train/validate step on several splits, called folds, and averages the scores. In k-fold CV the rows are cut into k parts and each part is the validation fold once. Leave-one-out is the extreme case k = n: one row per fold, which costs n model fits and is only practical for small datasets. The code needs scikit-learn 1.9 and NumPy.

02. When rows share an entity: grouped cross-validation

Many datasets have several rows per entity: sessions per user, scans per patient, transactions per card, photos per product. Rows of one entity look alike and often share their label. If a random split puts some of a user's rows in training and others in validation, the model can score well by recognising the user rather than by learning anything that transfers to a new user.

The simulation below makes this concrete. Each of 200 users has a visible habit profile and an invisible personal taste. Both drive how often the user buys. A model can learn the habit part for anyone, but it can only exploit the taste part for users it has already seen. GroupKFold keeps every row of a user in the same fold, so validation users are always new. A second dataset of 200 brand-new users shows which estimate tells the truth.

Python · users.py
import numpy as np

WEIGHT = np.array([1.0, -0.8, 0.6, 0.0, 0.0, 0.0])  # how habits drive purchases


def load(n_users, rows_per_user=20, seed=0):
    """App sessions: label = the session ends in a purchase.

    Each user has a stable habit profile (visible in the features) and a personal
    taste (invisible), and both shape how often that user buys.
    """
    rng = np.random.default_rng(seed)
    habit = rng.normal(size=(n_users, 6))
    taste = rng.normal(scale=1.5, size=n_users)
    user_logit = habit @ WEIGHT + taste
    groups = np.repeat(np.arange(n_users), rows_per_user)
    X = habit[groups] + rng.normal(scale=0.2, size=(groups.size, 6))
    p = 1 / (1 + np.exp(-user_logit[groups]))
    y = (rng.random(groups.size) < p).astype(int)
    return X, y, groups
Python · grouped.py
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import GroupKFold, KFold, cross_val_score

from users import load

X, y, groups = load(n_users=200, seed=0)     # users in today's data
X_new, y_new, _ = load(n_users=200, seed=1)  # users who sign up next month
model = RandomForestClassifier(n_estimators=200, min_samples_leaf=5, random_state=0)

for name, cv in [("KFold, rows shuffled", KFold(5, shuffle=True, random_state=0)),
                 ("GroupKFold by user", GroupKFold(5))]:
    scores = cross_val_score(model, X, y, groups=groups if "Group" in name else None,
                             cv=cv, scoring="roc_auc")
    print(f"{name:<21} ROC-AUC {scores.mean():.3f} ± {scores.std():.3f}")

auc_new = roc_auc_score(y_new, model.fit(X, y).predict_proba(X_new)[:, 1])
print(f"{'truly new users':<21} ROC-AUC {auc_new:.3f}")
Terminal
python grouped.py
Expected output
KFold, rows shuffled  ROC-AUC 0.819 ± 0.004
GroupKFold by user    ROC-AUC 0.676 ± 0.023
truly new users       ROC-AUC 0.689

The shuffled k-fold estimate, 0.819, is far above what the model achieves on new users, 0.689. The grouped estimate, 0.676, is close to it. The random split did nothing wrong in a narrow sense: every validation row really was unseen. But the users were not unseen, and in production they will be. Also notice the spread: grouped folds disagree more (± 0.023), because each fold holds a different set of people. That spread is honest information about how much the score depends on who your users happen to be.

Use the entity that production treats as new. For a model that scores existing customers next month, the customer is not the boundary, time is. When you need both grouping and a stable class balance, StratifiedGroupKFold combines them.

03. Rare classes and time order

Stratified k-fold keeps the share of each class roughly equal in every fold. It does not balance the classes; it keeps whatever balance the data has. That matters when positives are rare, because each fold's score is computed from only a handful of them.

Python · stratified.py
import numpy as np
from sklearn.model_selection import KFold, StratifiedKFold

y = np.zeros(3000, dtype=int)
y[:60] = 1                                  # 2% positives, e.g. chargebacks
X = np.zeros((3000, 1))
for name, cv in [("KFold", KFold(5, shuffle=True, random_state=3)),
                 ("StratifiedKFold", StratifiedKFold(5, shuffle=True, random_state=3))]:
    counts = [int(y[val].sum()) for _, val in cv.split(X, y)]
    print(f"{name:<16} positives per validation fold: {counts}")
Terminal
python stratified.py
Expected output
KFold            positives per validation fold: [13, 14, 9, 14, 10]
StratifiedKFold  positives per validation fold: [12, 12, 12, 12, 12]

With plain k-fold, the validation folds hold between 9 and 14 of the 60 positives, so a recall computed on the fold with 9 can move by more than 10 points when a single case flips. Stratification gives every fold 12, which makes the fold scores comparable and their spread meaningful.

When the model predicts the future from the past, the folds must respect time. TimeSeriesSplit trains on an expanding window of older rows and validates on the block that follows. Its gap argument leaves out rows between the two. Use a gap when the label takes time to become known. Suppose the label is "cancels within the next month". On the day you train, the rows of the most recent month do not have labels yet, so a model in production never trains on them. A gap of one month reproduces that delay. The rows must be sorted by time before splitting.

Python · time_split.py
import numpy as np
from sklearn.model_selection import TimeSeriesSplit

months = np.repeat(np.arange(1, 13), 100)  # 12 months of rows, oldest first
cv = TimeSeriesSplit(n_splits=4, test_size=100, gap=100)  # gap = one month of rows
for fold, (train, val) in enumerate(cv.split(months), start=1):
    print(f"fold {fold}: train months {months[train].min()}-{months[train].max()}, "
          f"validate month {months[val].min()}")
Terminal
python time_split.py
Expected output
fold 1: train months 1-7, validate month 9
fold 2: train months 1-8, validate month 10
fold 3: train months 1-9, validate month 11
fold 4: train months 1-10, validate month 12

04. Tuning without fooling yourself

Hyperparameters are settings you choose rather than learn, such as k in k-NN or the regularisation strength C. A hyperparameter search (for example GridSearchCV or RandomizedSearchCV) scores many candidate settings with CV and keeps the best. Each score is an honest estimate for its own candidate. The maximum of many scores is not: some candidates score high because their folds happened to suit them, and taking the maximum picks exactly those. The more candidates you try and the noisier each score, the bigger this selection bias.

The script makes the bias visible on data with no signal at all. Labels are coin flips, so the true accuracy of every candidate is 0.5. Each candidate is logistic regression on three random columns. A nested CV loop then estimates the whole procedure: in each outer fold, the complete search runs on the outer training rows only, and the winner is scored on the outer validation rows it never saw.

Python · selection.py
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import KFold, cross_val_score

rng = np.random.default_rng(0)
X, y = rng.normal(size=(200, 50)), rng.integers(0, 2, 200)        # pure noise
X_fresh, y_fresh = rng.normal(size=(5000, 50)), rng.integers(0, 2, 5000)
candidates = [rng.choice(50, size=3, replace=False) for _ in range(100)]


def search(X, y):
    """Try every candidate (3 columns each) with 5-fold CV; return the best one."""
    cv = KFold(5, shuffle=True, random_state=0)
    scores = [cross_val_score(LogisticRegression(), X[:, c], y, cv=cv).mean()
              for c in candidates]
    best = int(np.argmax(scores))
    return candidates[best], scores[best], float(np.median(scores))


cols, best_cv, median_cv = search(X, y)
model = LogisticRegression().fit(X[:, cols], y)
print(f"median CV accuracy of 100 candidates: {median_cv:.3f}")
print(f"best CV accuracy:                     {best_cv:.3f}")
fresh = model.score(X_fresh[:, cols], y_fresh)
print(f"the best candidate on fresh data:     {fresh:.3f}")

outer_scores = []  # nested CV: the whole search runs inside each outer training fold
for train, test in KFold(5, shuffle=True, random_state=1).split(X):
    cols_k, _, _ = search(X[train], y[train])
    fitted = LogisticRegression().fit(X[train][:, cols_k], y[train])
    outer_scores.append(fitted.score(X[test][:, cols_k], y[test]))
print(f"nested CV accuracy of the procedure:  {np.mean(outer_scores):.3f}")
Terminal
python selection.py
Expected output
median CV accuracy of 100 candidates: 0.488
best CV accuracy:                     0.615
the best candidate on fresh data:     0.507
nested CV accuracy of the procedure:  0.560

The typical candidate scores 0.488, as expected for coin flips. The winner scores 0.615, which looks like a real signal, and drops to 0.507 on fresh data. The nested estimate, 0.560, is much closer to the truth, though with only 40 rows per outer fold it is noisy too. Nested CV answers the question "how good is my procedure, search included?" It is not a way to pick the final settings; for that you run the search once on all the training rows.

In scikit-learn, nested CV is one line: pass the search object to cross_val_score. On a real, easy dataset with a small grid the two estimates often agree, as here; the gap grows with the number of candidates and shrinks with the amount of data.

Python · nested.py
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV, StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC

X, y = load_breast_cancer(return_X_y=True)
grid = {"svc__C": [0.1, 1, 10, 100], "svc__gamma": [1e-4, 1e-3, 1e-2, 1e-1]}
search = GridSearchCV(make_pipeline(StandardScaler(), SVC()), grid,
                      cv=StratifiedKFold(5, shuffle=True, random_state=0))
outer = StratifiedKFold(5, shuffle=True, random_state=1)
nested = cross_val_score(search, X, y, cv=outer)  # a fresh search in every outer fold
print(f"nested CV accuracy: {nested.mean():.3f} ± {nested.std():.3f}")
search.fit(X, y)                                  # then refit the search on all rows
print(f"best non-nested score: {search.best_score_:.3f}")
print(f"settings to deploy: {search.best_params_}")
Terminal
python nested.py
Expected output
nested CV accuracy: 0.981 ± 0.007
best non-nested score: 0.981
settings to deploy: {'svc__C': 100, 'svc__gamma': 0.001}

05. Check your understanding

Practice check · 3 questions

Pick the scheme

Use the scripts and outputs of this lesson.

Q1. In `time_split.py`, fold 1 trains on months 1 to 7 and validates on month 9. The label is "cancels within the next month". Why is month 8 left out?
Q2. A chargeback model has 60 positives in 3,000 rows. Why does `stratified.py` recommend `StratifiedKFold` over `KFold` here?
Q3. In `nested.py`, what does the nested CV accuracy of 0.981 estimate?
Practice only: not graded, not saved, not evidence.

06. Apply it

For the practice project, write the validation plan before running any model.

  1. In one sentence, describe what production will look like: new entities, a later time period, or both.
  2. Choose the matching splitter (GroupKFold, StratifiedGroupKFold, TimeSeriesSplit with a gap, or a time cut-off with grouped folds before it) and split off the test set first with the same rule.
  3. Save a split manifest (entity IDs per part, time boundaries, seed, data version) and run your hyperparameter search only inside the training part. Report a nested or held-out estimate, not the best search score.

07. Review prompt

Without looking back, explain why a shuffled k-fold split overestimated the model on new users and how GroupKFold fixes it; say what stratification does and does not do; describe when TimeSeriesSplit needs a gap; explain why the best score of a large search is optimistic and what nested CV estimates instead; and list four things a split manifest should record.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check