Sub topic 3
How k-fold cross-validation works
This chapter assumes you know supervised learning basics, overfitting, accuracy, NumPy, and scikit-learn's fit and predict API. It also assumes you have seen why a single holdout split gives a noisy estimate. Here you will see how k-fold cross-validation fixes that.
The idea
A holdout split scores a model on one test set. If that set happens to be easy or hard, the score is misleading. K-fold cross-validation repeats the holdout idea k times, so every sample is used for testing exactly once.
The procedure:
- Shuffle the data (optional but usual) and split it into k folds of roughly equal size.
- For each fold i, hold out fold i as the test set and train a fresh model on the other k-1 folds.
- Score the model on fold i.
- Combine the k scores, usually with the mean and the standard deviation.
Seeing the mechanics
The next example uses 10 samples and 5 folds. It prints only the sizes of each split, so you can check the arithmetic.
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))Each line shows 8 training samples and 2 test samples. Over the five folds, all 10 samples appear in a test set once. kf.split yields index arrays, not data, so you use them to slice X and y yourself.
Setting shuffle=True matters when your rows are ordered, for example sorted by label. Without it, folds are contiguous blocks, and one fold could contain only one class. random_state makes the shuffle reproducible.
Running it on a real model
You rarely write the loop by hand. cross_val_score does the splitting, fitting, and scoring.
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)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
scores = cross_val_score(model, X, y, cv=cv, scoring="accuracy")
print(scores)
print(f"mean={scores.mean():.3f} std={scores.std():.3f}")Points to notice:
cross_val_scoreclones the model for every fold, so no fitted state carries over between rounds.- The scaler sits inside the pipeline, so it is refit on each training fold. The test fold never influences the scaling. Later chapters cover this leakage issue in detail.
StratifiedKFoldkeeps class proportions similar in every fold. It is the default for classifiers when you pass an integercv.- The output is an array of five accuracies. The mean is your performance estimate. The standard deviation shows how much the score moves from fold to fold.
Common errors
- Reporting only the mean. Always include the spread. Two models with means of 0.95 and 0.96 may be indistinguishable if the standard deviation is 0.02.
- Forgetting to shuffle ordered data with plain
KFold, which gives biased folds. - Fitting preprocessing on the full dataset before splitting. This leaks test information into training.
- Treating the fold scores as independent. The training sets overlap heavily, so the standard deviation understates the true uncertainty.
Exercise
You run KFold(n_splits=4) on 100 samples with no shuffling. How many samples are in each training set and each test set, and how many times is each sample used for testing?
Show answer
Each test set has 25 samples and each training set has 75. Every sample is in a test set exactly once and in a training set 3 times.