Sub topic 3
K-fold cross-validation in a nutshell
This chapter assumes you know what a train/test split is and how to call fit, predict and score on a scikit-learn estimator. It also assumes you have met the idea of overfitting.
The idea
A single holdout split gives one score, and that score depends on which rows landed in the test set. K-fold cross-validation reduces that dependence by repeating the split several times.
- Shuffle the data and divide it into K parts of roughly equal size, called folds.
- For each fold in turn, train a fresh model on the other K-1 folds.
- Score that model on the held-out fold.
- Report the K scores, usually as a mean and a standard deviation.
Every row is used for testing exactly once and for training K-1 times. No model is ever scored on rows it was trained on.
Running it in scikit-learn
cross_val_score does the loop for you. It clones the estimator for each fold, so no state carries over between rounds.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
scores = cross_val_score(model, X, y, cv=cv)
print("fold scores:", scores)
print(f"mean {scores.mean():.3f} +/- {scores.std():.3f}")The default metric is the estimator's own score, which is accuracy for classifiers. Pass scoring="roc_auc" or another scorer name to change it.
The scaler sits inside the pipeline on purpose. It is refit on the training folds in each round, so the held-out fold never influences the scaling. A later chapter covers this in detail.
Choices that matter
| Choice | Typical value | Effect |
|---|---|---|
| Number of folds K | 5 or 10 | Larger K trains on more data per round, so the estimate is less pessimistic, but it costs K fits. |
| `shuffle` | `True` when row order is arbitrary | Without it, folds are contiguous blocks, which can be badly unbalanced if the file is sorted. |
| Stratification | `StratifiedKFold` for classification | Keeps class proportions similar in every fold. |
| `random_state` | A fixed integer | Makes the splits reproducible. |
When you pass an integer such as cv=5 to a classifier, scikit-learn already uses stratified folds without shuffling. Passing an explicit splitter object makes your choices visible and lets you reuse the same folds across experiments.
What the score means
The mean of the K scores estimates how well this modeling procedure performs when trained on about (K-1)/K of your data. It does not describe one particular fitted model. The K models differ, and none of them is the model you will deploy.
The standard deviation shows how much the score moves between folds. It is a rough guide only. The training sets overlap heavily, so the fold scores are not independent, and the spread tends to understate the true uncertainty.
Common errors
- Sorted data without shuffling. If rows are ordered by class or by date, unshuffled folds see very different data. Shuffle, or use a splitter designed for the structure.
- Preprocessing outside the loop. Fitting a scaler or imputer on all the data before splitting lets test-fold information leak into training. Put it in a
Pipeline. - Reusing the score for decisions. The K-fold mean is a fair estimate for one fixed model. If you also use it to choose among many candidates, it becomes optimistic. That problem is the subject of the next chapters.
Exercise
You run 5-fold cross-validation on a classification dataset whose rows are sorted by class, using KFold(n_splits=5) with no shuffling. Fold scores range from 0.00 to 0.95. What is the likely cause, and what two changes would you try?
Show answer
Unshuffled folds are contiguous blocks, so some test folds contain classes the training folds barely saw. Use StratifiedKFold so each fold keeps the class proportions, and set shuffle=True with a fixed random_state so the rows are mixed and the splits are reproducible.