← All posts

Machine learning algorithms › Training and evaluation

What is cross-validation? A plain guide to k-fold

What cross-validation is, why one train/test split can mislead you, how the k-fold variants differ, and how a pipeline keeps data leakage out of your scores.

If you’ve read a machine learning tutorial or a post comparing models, you’ve probably come across a line like “5-fold cross-validation accuracy 0.95.” scikit-learn’s Getting Started guide shows a 5-fold example in its section on model evaluation. Training a model now takes only a few lines of code, but the question of how far to trust its score hasn’t gone anywhere, and perhaps that’s why you hear the term so often. The textbook The Elements of Statistical Learning (ESL) calls cross-validation probably the simplest and most widely used method for estimating prediction error (book site).

Cross-validation splits your data into k pieces, called folds, and lets each fold take a turn as validation data while the model trains on the rest. So you measure performance k times and look at both the average and the spread. Its roots go back a while. ESL names Stone (1974 and 1977) and Allen (1974) as the key references, and Stone’s 1974 paper, Cross-Validatory Choice and Assessment of Statistical Predictions, applied a cross-validation criterion both to choosing a prediction method and to assessing it.

Splitting the data into folds and taking turns

Data usually plays three roles. The model learns from the training set, you compare settings and pick one using the validation set, and the test set stays hidden until the end, when you look at it once. Cross-validation takes over the validation set’s job. That’s why scikit-learn’s user guide says that with cross-validation you no longer need a separate validation set, though you should still hold out a test set.

With 100 samples, 5-fold cross-validation cuts the data into five folds of 20. Then it trains five models, one per fold, so that when fold 1 is scored the model has learned from folds 2 to 5, and so on. Every sample ends up in validation once and in training four times, and ESL notes that k is typically 5 or 10. Why go to the trouble? Because a single split is just one draw. If a few hard samples happen to land in the test set the score drops, and when data is scarce, setting aside a large validation set leaves the model even less to learn from. Cross-validation eases both by giving every sample its turn, and the spread of the scores shows how much luck went into the result.

How much one split can move a score

Let’s measure that luck. scikit-learn’s wine dataset holds chemical analyses of 178 wines grown in the same region of Italy by three cultivators, with 13 features each, and the label is the cultivator. The code below trains a decision tree, a model that answers through a chain of yes/no questions, ten times with a different 25% held out as the test set each time. Then it runs 5-fold cross-validation on the same data.

from sklearn.datasets import load_wine
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.tree import DecisionTreeClassifier

X, y = load_wine(return_X_y=True)  # 178 wines, 13 features, 3 classes
model = DecisionTreeClassifier(random_state=0)

# Ten different 25% test sets; only the shuffle seed changes
scores = []
for seed in range(10):
    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.25, random_state=seed)
    model.fit(X_train, y_train)
    scores.append(model.score(X_test, y_test))
print("10 splits:", " ".join(f"{s:.3f}" for s in scores))
print(f"lowest {min(scores):.3f}, highest {max(scores):.3f}")

# 5-fold cross-validation on the same data
cv_scores = cross_val_score(model, X, y, cv=5)
print("5 folds:", " ".join(f"{s:.3f}" for s in cv_scores))
print(f"mean {cv_scores.mean():.3f}, std {cv_scores.std():.3f}")
10 splits: 0.933 0.956 0.956 0.867 0.911 0.911 0.933 0.933 0.933 0.956
lowest 0.867, highest 0.956
5 folds: 0.944 0.833 0.889 0.914 0.857
mean 0.888, std 0.040

The only thing that changed was how the data was shuffled, and yet test accuracy went from 0.867 to 0.956. With 45 wines in the test set, that’s the gap between 39 and 43 correct, so the number you’d report depends on which seed you happened to use. Cross-validation, on the other hand, gives you a mean of 0.888 along with a standard deviation (how far the scores typically sit from the mean) of 0.040. So you can say “about 0.89, give or take 0.04.” In scikit-learn 1.9.1, calling cross_val_score with cv=5 on a classifier uses StratifiedKFold without shuffling. In practice you’d set a test set aside first and cross-validate only on the rest, but I skipped that step to keep the example short.

Stratified, leave-one-out, group, and time series splits

Plain k-fold assumes that samples are independent and that their order doesn’t matter, so when your data breaks those assumptions, the way you split has to change too. These are the splitters you’ll use most often in scikit-learn.

Splitter How it splits When it fits
KFold k folds of nearly equal size Independent samples, regression
StratifiedKFold Similar class proportions in every fold Classification, especially with rare classes
LeaveOneOut Each sample is its own fold Very small datasets
GroupKFold A group never lands on both sides Several rows per patient
TimeSeriesSplit Trains on the past, validates on what follows Data ordered in time

Stratification keeps class proportions roughly equal across folds, so a rare class is less likely to vanish from one. That said, scikit-learn’s guide also warns that stratification can make the spread across folds look smaller than it really is. Leave-one-out cross-validation (LOOCV) is k-fold with k equal to the number of samples, which on the wine data means training 178 models. ESL explains that LOOCV is nearly unbiased but can have high variance because its training sets are so alike, and it recommends five- or tenfold as a good compromise.

Groups and time call for more care. If samples from one patient end up on both sides of a split, the model can score points just by recognizing that patient, so GroupKFold always keeps a group on one side. And TimeSeriesSplit always trains on earlier samples and validates on later ones, and each round’s training set includes everything the previous round trained on.

Data leakage, the most common mistake

Cross-validation only does its job if each validation fold is truly unseen. That breaks when you scale the features or choose which ones to keep using the whole dataset before cross-validation starts. scikit-learn’s common pitfalls page calls this data leakage, explaining that information you won’t have at prediction time gets used to build the model, so the scores come out too optimistic.

Section 7.10.2 of ESL, “The Wrong and Right Way to Do Cross-validation,” shows how large the effect can be. There are 50 samples, 25 in each of two classes, and 5,000 features of noise unrelated to the labels, so no model can beat 50%. The authors used all 50 samples to pick the 100 features most correlated with the labels, then cross-validated a 1-nearest-neighbor classifier (a model that copies the label of the closest training sample). Over 50 simulations, the error rate averaged 3%, and they add that they’ve seen this blunder many times in papers in top journals. Below is the same setup in scikit-learn. SelectKBest keeps the k features with the highest scores, and with two classes the 100 features picked by its default score, f_classif, were the same 100 picked by correlation.

import numpy as np
from sklearn.feature_selection import SelectKBest
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline

rng = np.random.default_rng(0)
X = rng.normal(size=(50, 5000))           # 50 samples, 5,000 noise features
y = rng.permutation([0] * 25 + [1] * 25)  # labels unrelated to X

# Wrong: pick 100 features using all 50 samples, then CV
X_top = SelectKBest(k=100).fit_transform(X, y)
wrong = cross_val_score(KNeighborsClassifier(n_neighbors=1), X_top, y, cv=5)

# Right: the pipeline redoes the selection in each training fold
pipe = make_pipeline(SelectKBest(k=100), KNeighborsClassifier(n_neighbors=1))
right = cross_val_score(pipe, X, y, cv=5)

for name, s in [("selection before CV", wrong), ("selection inside CV", right)]:
    print(f"{name}:", " ".join(f"{v:.2f}" for v in s), f"| mean {s.mean():.3f}")
selection before CV: 1.00 1.00 1.00 1.00 1.00 | mean 1.000
selection inside CV: 0.70 0.50 0.50 0.40 0.70 | mean 0.560

Picking features first earned a perfect 1.00 on every fold, on labels that are no better than coin flips. The 100 features were chosen after seeing the labels of the samples later used for validation, so those folds were never really unseen. With the selection inside the pipeline, the score was 0.560, close to the 0.5 we should expect. When I changed the seed from 0 to 49, the wrong way averaged 0.985 and the right way 0.488, and with only 50 samples, single runs of the right way still swung between 0.300 and 0.620.

A Pipeline bundles the steps so that in every round of cross-validation, each step is fit on the training folds alone and only applied to the validation fold. The same goes for StandardScaler, filling in missing values, and PCA, which the pitfalls page also lists. Of course, ESL says a step that never looks at the labels, such as keeping the features with the largest variance, can be done beforehand, but putting every step in the pipeline is the safer choice.

Choosing hyperparameters with GridSearchCV

Hyperparameters are settings you fix before training, like the number of features to keep in the example above. GridSearchCV runs cross-validation for every combination you list, picks the one with the best mean score, stores that score in best_score_, and by default (refit=True) retrains on all the data you gave it.

But if you report best_score_ as your final performance, the number tends to be optimistic. You picked the best of many scores, so some luck is mixed in. I let GridSearchCV choose k for SelectKBest from 20 values between 5 and 100 on the noise data above, and over seeds 0 to 19, best_score_ averaged 0.595 even though the true accuracy is 0.5. Nested cross-validation, which wraps the whole search in an outer cross-validation loop, written as cross_val_score(grid, X, y, cv=5), averaged 0.503 on the same seeds. scikit-learn’s nested cross-validation example gives the same warning, and another common approach is to score the chosen model once at the end on a test set you set aside at the start.

When it fits and when it doesn’t

Cross-validation fits best when data is limited and a single split swings a lot, as in the wine example. And since every candidate is scored on the same folds, it’s also a good way to compare models or settings fairly.

The cost is time. k-fold trains k models, and a grid search multiplies that by the number of candidates. When I ran the search above with verbose=1, it printed “Fitting 5 folds for each of 20 candidates, totalling 100 fits.” On top of that it refits once on all the data, and nesting repeats all of it five times. That’s why, with very large data, a single validation set is often enough. When I split a 200,000-row dataset made with make_classification ten different ways and trained a logistic regression, test accuracy only moved between 0.9584 and 0.9600.

If you shuffle time-ordered data into plain k-fold, the model learns from the future and is validated on the past. So the score tends to look better than it will in real use, where you only have the past to go on. scikit-learn’s guide warns that KFold and ShuffleSplit assume independent samples and give poor estimates of generalization error on time series.

Where to start

If you’re new to this, I’d suggest following the install guide to run pip install -U scikit-learn and then trying the two examples above. After that, put cv=10 into the wine example or move SelectKBest in and out of the pipeline, and you’ll see right away how the scores change. I ran these examples on November 2, 2026, with Python 3.13.12, scikit-learn 1.9.1, and NumPy 2.5.4.

AI tools helped with the research for this post.