Cross-validation (k-fold, stratified, group, time series)
Estimate how a model will do on new data by training and scoring it several times on different splits, and choose the split that matches how the model will be used.
Lesson 40 of 6615 minIntermediate
You will learn to
- Explain why one train-validation split gives a noisy estimate and how k-fold cross-validation reduces it
- Choose between k-fold, stratified, group and time-ordered folds for a given dataset
- Spot leakage caused by the wrong fold strategy
Before this lesson
Intuition
To know how a model will do on new data, you score it on data it did not train on. The simplest way is to hold out one validation set. The trouble is that the score then depends on which rows happened to land in that set: a lucky split flatters the model, an unlucky one buries it. With a few thousand rows, two random splits can easily differ by several points of accuracy.
Cross-validation repeats the experiment. Split the training rows into k parts called folds. Train on k - 1 folds and score on the remaining one; do that k times so every fold is the validation set once; average the k scores. Every row is used for validation exactly once and for training k - 1 times. The average is far more stable than any single split, and the spread between folds tells you how much to trust it.
The rule that decides how to make the folds is simple to state: each validation fold must look like the data the model will face in production, relative to what it trained on. If production means new customers, a fold must contain customers the model never saw. If production means next month, a fold must come after the training data in time. Getting this wrong does not cause an error message; it silently produces a score that is too good.
Picture it
Plain k-fold: rows are shuffled and cut into five equal folds; each round validates on a different one.
Stratified k-fold does the same, but deals rows so that each fold has the same share of every class (the dots mark a minority class).
Group k-fold keeps every row of a group (a patient, a store, a user) in the same fold, so the model is always validated on groups it has never seen. Folds can have different sizes because groups do.
Time-ordered folds never look back. With an expanding window, each round trains on all history up to a cutoff and validates on the period right after it; the future beyond stays unused.
The math
Let be the score of a model on data . Split the training data into folds , and let be the model trained on every fold except . The cross-validated estimate is the mean of the fold scores:
and its spread is the standard deviation across folds:
Two consequences follow:
- The estimate is slightly pessimistic. Each trains on a fraction of the data, a little less than the final model will. With that is 90%, and the bias is usually small.
- The fold scores are not independent, because the training sets overlap. So understates the real uncertainty. Treat two models whose averages differ by less than about one fold standard deviation as tied.
Larger k means more training data per round and a less pessimistic estimate, but k times the compute. Values between 5 and 10 are the usual compromise.
Worked example
Suppose you are predicting whether a hospital visit leads to readmission. The data has 6,000 visits from 900 patients; frequent patients appear many times, and the model will be used for patients who are new to the hospital. (The scores below are illustrative; the size of the gap varies from dataset to dataset, but its direction is typical.)
- First attempt: stratified 10-fold. Readmission is rare (around 12% of visits), so stratification is sensible. The cross-validated AUC is 0.86.
- Question the folds. With random folds, most patients have visits on both sides of every split. A flexible model can learn patient-specific quirks (an unusual combination of medications, say) and recognise the same patient in the validation fold. That is not a skill it will have for new patients.
- Second attempt: stratified group 10-fold, grouped by patient id. Every patient's visits now stay in one fold, and the class balance is still kept. The cross-validated AUC drops to 0.79.
The model did not get worse; the estimate got honest. The 0.07 gap is the part of the first score that came from recognising patients rather than predicting readmission. Had you shipped on the strength of 0.86, the first months in production would have looked like a mysterious drop.
The same reasoning applies to time: a model validated on shuffled folds of daily sales has seen days from the "future" of each validation fold, and will look better in testing than it ever will in production. Use time-ordered folds for anything that forecasts.
How mlflow does it
- Hold-out and folds. mlflow first keeps part of the data aside as a hold-out test set (by default 70% of the rows train, 30% are held out), then cross-validates every algorithm on the training part. The leaderboard shows the cross-validated averages.
- Fold strategies. In Pipeline Studio, the Cross-validation card in the Models part of the pipeline editor (headed "Which models to try") has CV folds (2 to 20, default 10) and Fold strategy. Classification offers Stratified k-fold (the default), K-fold, Group k-fold and Stratified group k-fold; regression offers K-fold (the default) and Group k-fold.
- Group column. Picking a Group column keeps every group whole, in one fold and on one side of the train/test split; the column is not used as a feature, cannot be the target and cannot be used by a step. With a group column, the hold-out share counts groups instead of rows, and you need at least as many groups as folds.
- Time series. Forecasting pipelines show Forecast settings instead: a Date column, a Forecast horizon and CV folds, with an Expanding or Sliding fold strategy. Every fold trains on the past and is scored on the next horizon of periods; a group column is not available for time series.
- Preprocessing stays inside. The steps of a pipeline are part of the model, so they are fitted on training rows only and never learn from the rows they are scored on.
- Clustering and anomaly detection have no target to score against, so there is no cross-validation setting for them.
Common mistakes
- Preprocessing before splitting. Scaling, imputing or selecting features on the full dataset lets information from validation rows into training. Fit every transformation inside the folds; in mlflow, put it in the pipeline rather than in the uploaded file.
- Random folds on related rows. Repeated measurements of the same person, store, machine or document must share a fold. Use a group strategy whenever the model will meet new groups.
- Shuffling time. Any random split of a time series validates on the past using the future. Use time-ordered folds.
- Reading the mean and ignoring the spread. If the fold scores range from 0.70 to 0.88, a 0.01 difference between two models means nothing.
- Tuning on the folds and reporting the same folds. Once the folds have been used to choose hyperparameters, their score is optimistic. Confirm the final choice on the hold-out set.
- Too few rows per fold. With very small datasets or rare classes, a large k leaves folds with only a handful of positives. Lower k, or use stratification.
Try it in mlflow
Change the fold strategy and see the score move
- Open Pipelines and pick a classification pipeline.
- Open the Models part and find the Cross-validation card.
- Train once with Stratified k-fold; then pick a Group column, switch to Group k-fold and train again.
- Compare the two runs: if the group score is lower, the first estimate was flattered by related rows.