What will the next prediction look like?
Imagine evaluating a subscription renewal model with twelve weeks of activity per customer. Your product team might care about two different predictions. One is next week’s renewal for someone with an established account. The other is renewal for someone who signed up yesterday. Both use the same outcome column, yet each calls for a different test set. The first evaluation needs a cutoff in time. The second needs customers whose records were absent during training. Decide which question a score should answer before choosing a splitter.
Read the diagram one column at a time. A column represents an observation at a particular time step. Its first two cells give the binary outcome and entity number. Follow the column downward to see when that observation enters training or validation. Moving across a single fold instead shows everything one fitted model gets to learn from. Change only the splitter on your first pass so the rows, labels and entity histories stay the same.
Why a single train/test split gives a noisy score
Suppose a test set contains ten renewals and your model catches seven. That gives a recall of 70 percent. Just one additional correct prediction moves recall by ten percentage points. A lucky draw of straightforward cases can make that change happen even when the training procedure stays identical. Training composition matters too. With a small dataset, moving a handful of unusual accounts into the test set can remove nearly every example of their behavior from training.
KFold divides the rows into disjoint test blocks. Each block takes its turn in validation while the remaining blocks supply training examples. Across the complete run every row receives one out-of-fold prediction. Inspecting the spread of scores reveals how much results vary with the particular cases held out. The training sets overlap, so five fold scores do not constitute five independent experiments. Keep an untouched final evaluation set if you repeatedly consult cross-validation to choose features or tune a model.
KFold and StratifiedKFold on rare outcomes
Set the ordering to grouped, turn shuffle off and lower the positive rate. Examine the class strip above each dark test block. Entities here have different tendencies to produce positive outcomes, so adjacent rows can contain long runs of one label. KFold respects the supplied row order by default. A validation block may capture a pocket of renewals while another contains mostly cancellations. The maximum fold class drift measures the largest gap between a block’s positive fraction and the fraction in the entire dataset.
Switch to StratifiedKFold with the same controls. Class labels guide the allocation so that each test fold receives roughly its share of each outcome. Whole observations impose a rounding limit. Seven positives distributed across five folds cannot give every fold the same positive count. Balancing labels helps when comparing models on rare outcomes, particularly for recall, which needs positive examples in the denominator. Check the entity strip as well. Similar test percentages alone tell you little about whether the validation customers were previously seen.
Hold out the unit that must generalize
A patient’s measurements across visits often resemble one another. A classifier may recognize a stable baseline, a device calibration or a clinic-specific measurement pattern even after a patient identifier is removed from the features. When visits from one patient appear on both sides of a split, recognizing that patient can improve validation performance. The apparent gain may disappear on the first visit from a new patient. The same reasoning applies to clicks from one user or overlapping recording windows from one session.
Use interleaved ordering to bring this effect into view. In a KFold row, find any underlined test cell and read its entity number. Follow the strip sideways to find an underlined training cell for that same entity. The table counts the entity once in that fold even if it contributed many visits. If it crosses the boundary again in the next fold, that contributes another fold/group pair. The underline shows an opportunity for leakage. Measuring the size of the score inflation requires fitting and evaluating a model.
GroupKFold keeps all observations from an entity together and distributes the groups across validation folds. StratifiedGroupKFold additionally considers class counts when assigning groups. Try six groups and six folds. Each test set must hold an entire group, so the splitter has little freedom to correct a group with an unusually high positive rate. Additional independent groups give it more choices. GroupShuffleSplit answers a related question by drawing held-out groups repeatedly. A difficult patient can appear in several draws, and another patient may never enter a test set.
Walk forward for a forecast
For a forecast, reconstruct what could have been known at the moment of prediction. Turning off shuffle in KFold leaves observations in sequence, but look at its first fold. The test block comes first and the training rows lie later on the timeline. The audit counts each training row later than the earliest test time once per fold. That quantity matters if the task requires learning exclusively from prior events. For an exchangeable collection of independently sampled items, column order may have no such interpretation.
TimeSeriesSplit starts with an initial training window and tests on the following block. Move down one strip and the training window expands into observations that have now become historical. Future blocks stay unused until their turn. Here the displayed column position defines synthetic time for either ordering. With production data, sort by the actual event time before splitting. Also check when the target becomes available. A seven-day outcome for an event immediately before the cutoff may still be unknown at training time. Leave an appropriate gap for that delay.
Fit preprocessing inside each fold
Once the indices look sensible, apply them to the entire learning procedure. Consider filling missing purchase amounts with a median. Computing that median on the full table allows held-out purchases to influence a training decision. Put the imputer, scaler and estimator into a Pipeline and fit a fresh pipeline on the training indices of each fold. During validation, use the median and scale learned from those training rows. Apply the same discipline to supervised feature selection, where consulting validation labels can have an even larger effect.
Save the fold indices alongside a stable dataset version when comparing two pipelines. Both candidates then face the same held-out cases, and a difference in recall can be traced to specific positive observations. Before reporting an average, inspect each fold’s test size, class fraction and distinct entities. A large fold with common outcomes and a small fold with rare outcomes may contribute very different evidence. Document the prediction population and time horizon with the score so the next reader knows where that evidence applies.