To find out whether a model works, you test it on data it hasn’t seen. But which rows you happen to hold back for the test can swing the score far more than most people expect. Cross-validation tests on every row once, in turn, and averages the results, so one lucky or unlucky split can’t fool you. Here you’ll watch a score jump around between splits, see cross-validation steady it, and learn the special ways to split rare classes and data over time.
Why one split isn’t enough#
Say you have 60 rows of data, each one of two kinds, and a simple model that labels a row by looking at the 5 most similar rows it has seen. The standard move is to shuffle the rows, hold back 20% of them (12 rows) as a test set, train on the other 48 (the training set), and score the model on the 12 it never saw.
With only 12 test rows, every single one is worth 8.3 points of accuracy. Swap one easy row for one hard row and the score moves by 8 points, though nothing about the model has changed.
Predict first
You shuffle, split 80/20, train, and score 83% on the 12 test rows. A colleague does exactly the same with a different shuffle. What might they get?
The 60 rows
Press shuffle: the rows are shuffled, the model is trained, and it’s scored on rows it didn’t see.
● one split: no tries yet
● 5-fold CV: no tries yet
Dashed line: the model’s real accuracy, 82.7%, measured on 5,000 fresh rows from the same source. You never get those in real life.
In 500 shuffles we ran, a single split scored anywhere from 50% to 100%, with the middle 90% of them between 67% and 100%. Same data, same model. A score from one split tells you roughly how good the model is, plus a large helping of luck.
k-fold cross-validation takes the luck out. Shuffle the rows once and cut them into k equal parts, called folds; with k = 5, that’s 5 folds of 12 rows. Train on 4 folds and test on the fifth, then do it again with a different fold held out, until every fold has been the test set once. Average the 5 scores. Every row gets tested exactly once, by a model that didn’t train on it.
Switch the figure to 5-fold cross-validation and do it 100 times. In 500 shuffles, the average stayed between 80% and 91.7%, with a spread of about ±2 points instead of ±9. Cross-validation doesn’t make the model better; it makes your measurement of it trustworthy.
Now look at the dashed line. Because these rows are made up, we can generate 5,000 fresh ones and measure the model’s real accuracy: 82.7%. Both methods centre on about 86%, a little above it, because these particular 60 rows happen to be a little easier than average. No way of splitting can fix that. Cross-validation removes the luck of the split, not the luck of the data you collected. Only more data does.
Choosing settings without fooling yourself#
Cross-validation’s everyday job is comparing options: which model, how many neighbours, how deep a tree. Score each option with cross-validation on your training data and pick the best. Two habits keep it honest:
- Keep a final test set locked away. If you try 50 settings and keep the best, its score is a bit flattering, because you picked the luckiest of 50. Set some data aside before you start, never use it for choosing, and score the winner on it once at the very end.
- Do all preparation inside the folds. If you scale your data, fill in missing values or pick features using all the rows first, information from each test fold has leaked into its training. Fit those steps on the training folds only; in scikit-learn, putting them in a
Pipelinedoes it for you.
Splitting the awkward cases#
Shuffling and cutting works when every row is independent and the classes are reasonably balanced. Real data often isn’t either.
Predict first
60 card transactions, 6 of them fraud. Shuffle them and cut them into 5 folds of 12. Will every fold get at least one fraud?
traintestfraud (6 of 60)
2 of 5 test folds have no fraud at all: their score says nothing about catching fraud.
KFold, StratifiedKFold and TimeSeriesSplit. Each line is one round: the model trains on the green rows and is tested on the yellow ones.Stratified k-fold deals each class out separately, so every fold keeps the same mix: here, 1 or 2 fraud rows in each. Use it for classification, especially when one class is rare. Push the folds up to 10, though, and even stratified splitting leaves 4 folds without fraud, since there are only 6 to go round. scikit-learn warns you when a class has fewer rows than you have folds.
Now picture the rows as days of sales, oldest first, and you want to predict tomorrow. Plain k-fold would happily train on next month to predict last week: the model peeks at the future, and the score looks far better than anything you’ll see once it’s live. Switch to Time series: every round trains only on the past and tests on the block that comes right after it. When your rows are in time order, never shuffle them before splitting.
One more case: when several rows come from the same person, patient or customer, keep all of their rows in the same fold (scikit-learn’s GroupKFold). Otherwise the model can recognise the person rather than learn the pattern.
In code#
On scikit-learn’s real breast cancer dataset (569 rows), a single split and stratified 5-fold cross-validation, with scaling inside a pipeline so nothing leaks:
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
model = make_pipeline(StandardScaler(), KNeighborsClassifier()) # scaling happens inside each fold
for seed in range(5): # one split, five different shuffles
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, random_state=seed)
print(round(model.fit(X_tr, y_tr).score(X_te, y_te), 3)) # 0.956 0.956 0.974 0.947 0.965
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
scores = cross_val_score(model, X, y, cv=cv)
print(scores.round(3), round(scores.mean(), 3), "+/-", round(scores.std(), 3))
# [0.93 0.991 0.956 0.965 0.982] 0.965 +/- 0.021With 114 test rows instead of 12, single splits wobble less, between 94.7% and 97.4% here, but the folds still range from 93% to 99%. Report 96.5% ± 2.1, not whichever split you happened to run first. For data in time order, swap in TimeSeriesSplit(n_splits=5), without shuffling.
What to remember
- A score from one train/test split mixes how good the model is with how lucky the split was.
- k-fold cross-validation tests every row once across k rounds and averages them; report the average and the spread.
- Split to match your data: stratify rare classes, keep time in order, keep each group’s rows together, and keep a final test set untouched.