Sub topic 3
How k-fold cross-validation works
This chapter assumes you know how to train a supervised model in scikit-learn with fit and predict, and that you understand overfitting and accuracy. It also assumes you have seen the holdout split from the previous chapter. Here you will learn the k-fold procedure, how scikit-learn builds the folds, and what the resulting scores mean.
The problem k-fold solves
A single holdout split gives one score from one arbitrary choice of test rows. Move a few hard examples from the test set to the training set and the score changes. The holdout split also wastes data. The test rows never help train the model, and the training rows never help evaluate it.
K-fold cross-validation fixes both problems. It repeats the train-and-test cycle several times, so every row is used for testing exactly once and for training in the remaining rounds. You then summarize the scores from all rounds.
The procedure
For a chosen integer k (the number of folds):
- Shuffle the row indices, unless you are deliberately keeping their order.
- Divide the indices into k folds. A fold is a group of rows of roughly equal size.
- For each fold i from 1 to k, hold out fold i as the test set and train a fresh model on the other k-1 folds. Then score the model on fold i.
- Combine the k scores, usually as their mean and standard deviation.
The next diagram shows the loop.
For k = 5, the roles rotate like this:
| Round | Test fold | Training folds |
|---|---|---|
| 1 | 1 | 2, 3, 4, 5 |
| 2 | 2 | 1, 3, 4, 5 |
| 3 | 3 | 1, 2, 4, 5 |
| 4 | 4 | 1, 2, 3, 5 |
| 5 | 5 | 1, 2, 3, 4 |
Each round trains on 80% of the data and tests on 20%. Across the five rounds, every row is tested exactly once, so the combined predictions cover the whole dataset.
Inspecting the splits
KFold does not train anything. Its split method yields pairs of index arrays, one for training and one for testing. Printing the sizes on a tiny dataset makes the mechanics visible.
import numpy as np
from sklearn.model_selection import KFold
X = np.arange(20).reshape(10, 2)
kf = KFold(n_splits=5, shuffle=True, random_state=0)
for fold, (train_idx, test_idx) in enumerate(kf.split(X)):
print(fold, len(train_idx), len(test_idx))The output is five lines, one per fold, each with 8 training indices and 2 test indices:
0 8 2
1 8 2
2 8 2
3 8 2
4 8 2Three details matter here.
splitreturns indices, not data. You select rows withX[train_idx]andy[train_idx]. This keepsXandyaligned, and it works for any array-like input.shuffle=Trueshuffles the rows once before cutting them into folds. The rows within a fold are not reshuffled in each round. Without shuffling,KFoldcuts the data into consecutive blocks.- Fold sizes differ by at most one row when n is not divisible by k. With 569 rows and k = 5, the first four folds hold 114 rows and the last holds 113.
Set random_state whenever shuffle=True. Otherwise the folds change on every run, and so do your scores. That makes results hard to compare between experiments.
Writing the loop by hand
You rarely need to write the loop yourself, but doing it once shows what the helper functions do. The following code scores a shallow decision tree on the breast cancer dataset.
import numpy as np
from sklearn.base import clone
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import KFold
from sklearn.tree import DecisionTreeClassifier
X, y = load_breast_cancer(return_X_y=True)
template = DecisionTreeClassifier(max_depth=3, random_state=0)
kf = KFold(n_splits=5, shuffle=True, random_state=0)
scores = []
for train_idx, test_idx in kf.split(X):
model = clone(template)
model.fit(X[train_idx], y[train_idx])
scores.append(model.score(X[test_idx], y[test_idx]))
scores = np.array(scores)
print(scores.round(3))
print(f"mean={scores.mean():.3f} std={scores.std():.3f}")The key line is clone(template). It returns an unfitted copy with the same hyperparameters. If you reused one model object and called fit again, scikit-learn estimators would refit from scratch anyway, but a clone makes the independence of the rounds explicit. It also protects you with estimators that support warm starting, where a second fit can continue from the previous state.
model.score returns accuracy for classifiers. You get five numbers, one per fold, and then summarize them.
In practice, cross_val_score(model, X, y, cv=kf) runs this loop for you. The next chapter covers it, along with metrics and reporting.
What the numbers mean
Each fold score is an estimate of how a model trained on (k-1)/k of your data performs on unseen rows. The mean of the scores estimates the expected performance of that training procedure. The standard deviation shows how much the score moves from one fold to another.
Cross-validation does not evaluate one specific fitted model. It evaluates the procedure: the algorithm, its hyperparameters, and any preprocessing. You trained k different models, and none of them is the model you will ship. Once you are satisfied with the procedure, you normally train a final model on all the data and use the cross-validated mean as your expectation of its performance.
Costs and what changes with k
K-fold trains k models, so it costs about k times as much as one holdout fit. For a model that trains in two seconds, 5-fold cross-validation takes about ten seconds. For a deep network that trains for hours, it may be unaffordable. The folds are independent of each other, so they can run in parallel. Scikit-learn's cross-validation functions accept n_jobs for this.
The choice of k also changes the estimate. A larger k gives each model more training data, so the estimate is less pessimistic, but it costs more and the folds overlap more. A later chapter treats this bias and variance trade-off in detail. For now, remember that k = 5 and k = 10 are common defaults.
Common errors
- Using
KFoldon sorted data without shuffling. If rows are ordered by class or by date, the unshuffled folds are blocks with different distributions. One fold may contain only one class. Shuffle, or choose a splitter that matches the data structure. - Treating the fold standard deviation as a full confidence interval. Training sets overlap between folds, so the fold scores are not independent. The spread is informative, but it understates the true uncertainty.
- Fitting preprocessing on all the data before splitting. Scalers, imputers, and feature selectors must be fit only on each training fold. Otherwise information from the test fold leaks into training. Pipelines solve this, and a later chapter covers them.
- Comparing scores from different splits. If you compare two models using different
random_statevalues, some of the gap may come from the folds. Use the same splitter object for every candidate. - Using plain k-fold when rows are related. Repeated measurements of one patient, or time-ordered rows, break the assumption that the rows are independent. Group and time-series splitters handle these cases.
Summary of the working model
K-fold cross-validation partitions the rows into k folds. It trains on k-1 folds, tests on the remaining one, and rotates until every fold has been the test set. The k scores give an estimate of generalization performance for a training procedure, along with a rough sense of its variability. The cost is k fits, and the estimate holds only if the splitting scheme matches how the data were collected.
Exercise
You run KFold(n_splits=4) on a dataset with 102 rows, with no shuffling. How many rows are in each test fold, and how many rows does each model train on?
Show answer
102 is not divisible by 4, so fold sizes differ by one row. The first two folds hold 26 rows and the last two hold 25 (26 + 26 + 25 + 25 = 102). The models therefore train on 76, 76, 77, and 77 rows, which is 102 minus the test fold size. Because shuffling is off, each fold is a block of consecutive rows. If the file is sorted by class or date, this can skew the folds.
Exercise
A teammate says: "My 5-fold cross-validation gave a mean accuracy of 0.91, so the model I trained on the full data has exactly 0.91 accuracy on new data." Give two reasons this claim is too strong.
Show answer
First, cross-validation evaluates the training procedure, not the final model. The five fold models were trained on 80% of the data, while the final model uses 100%, so its true accuracy will usually be a little higher, though not exactly 0.91. Second, 0.91 is an estimate with uncertainty. The fold scores vary, and because the training sets overlap, their standard deviation understates the real uncertainty. Moreover, the estimate holds only for new data that resembles the data used in the folds. Related rows or a shift over time would make it optimistic.