Sub topic 4
Cross-validation as the score estimator behind the curves
Every point on a learning curve or a validation curve is a cross-validated score. This chapter explains how that score is produced, what it estimates, and which settings change it. You need supervised learning basics, comfort with scikit-learn's fit/predict/score, and the idea that training and validation scores can differ. The learning_curve and validation_curve calls themselves come in later chapters.
Why one split is not enough
You could estimate generalization by holding out one validation set and scoring on it once. That number depends on which samples landed in the hold-out set. A different random split can shift it by several points, especially on small datasets. If a curve were built from single splits, you could not tell a real trend from the luck of one split.
Cross-validation fixes this by repeating the split-fit-score cycle and keeping every result. You get a set of scores, not one number. The curves plot the average of that set, and the spread tells you how much to trust the average.
How k-fold cross-validation works
In k-fold cross-validation, the data is divided into k parts called folds. For each fold in turn:
- Hold that fold out as the validation fold.
- Fit a fresh copy of the estimator on the other
k - 1folds. - Score the fitted model on the validation fold, and optionally on the training folds too.
Each sample is used for validation exactly once and for training k - 1 times. The result is k validation scores. Their mean estimates how the model would perform on unseen data of the same kind.
Getting both scores with cross_validate
The curves compare training and validation scores. cross_validate returns both for a plain fixed-size run, and it makes a good first look at what the curve functions compute internally.
from sklearn.datasets import load_digits
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_validate
X, y = load_digits(return_X_y=True)
results = cross_validate(
LogisticRegression(max_iter=2000),
X,
y,
cv=5,
scoring="accuracy",
return_train_score=True,
)
print(results["train_score"])
print(results["test_score"])
print(results["test_score"].mean(), results["test_score"].std())Training scores are not returned unless you set return_train_score=True. The validation scores are stored under the key test_score, because scikit-learn calls the held-out part the test fold. In this book, "validation" means the same thing.
What learning_curve adds
learning_curve runs the same loop with one extra step. For each fold it takes only the first n samples of that fold's training part, for each requested size n. It fits on those samples, then scores on both the n samples it fitted on and the full validation fold. The validation fold never shrinks. Only the training portion does.
Two consequences matter in practice.
- The training score is measured on the subset the model was fitted on, not on the full training part. Training scores at small sizes are therefore computed on very few samples.
- Training sizes cannot exceed the training part of a split. With 5-fold cross-validation on the 1,797 digits, the training part holds about 1,438 samples. The curve never shows what happens with all 1,797.
If you pass fractions such as np.linspace(0.1, 1.0, 5), they are fractions of that maximum training size. Floats are converted to absolute counts, and the function returns those counts as its first output.
validation_curve uses the same splits but keeps the training size fixed and changes one hyperparameter. Both functions return score arrays whose last axis is the fold axis. Averaging over axis=1 collapses the folds.
The splitting strategy matters
Passing cv=5 hides a decision. With an integer, scikit-learn uses StratifiedKFold for classifiers with a class label target, and KFold otherwise. Neither shuffles by default. If your rows are ordered, unshuffled folds can be badly unrepresentative.
The iris dataset stores its 150 rows sorted by class. Look at what happens with three unshuffled folds:
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import KFold, cross_val_score
X_iris, y_iris = load_iris(return_X_y=True)
model = LogisticRegression(max_iter=1000)
plain = KFold(n_splits=3)
shuffled = KFold(n_splits=3, shuffle=True, random_state=0)
print(cross_val_score(model, X_iris, y_iris, cv=plain))
print(cross_val_score(model, X_iris, y_iris, cv=shuffled))With plain, each fold holds out exactly one whole class, so the model never sees the class it is asked to predict. Every score is 0.0. With shuffled, scores are high. The model is the same and the data is the same. Only the split changed.
The common choices are summarized below.
| Splitter | Use it when | Notes |
|---|---|---|
| `StratifiedKFold` | Classification, especially imbalanced classes | Keeps class proportions similar in every fold. Default for classifiers with integer `cv`. |
| `KFold(shuffle=True)` | Regression with rows in arbitrary order | Set `random_state` for reproducible curves. |
| `GroupKFold` | Several rows come from the same patient, user, or session | Keeps each group on one side of every split. |
| `RepeatedStratifiedKFold` | Small datasets with noisy scores | Repeats k-fold with different shuffles, giving more score samples. |
| `ShuffleSplit` | You want control over validation size and number of splits | Folds may overlap, and some samples may never be validated. |
| `TimeSeriesSplit` | Rows are ordered in time | Validation always comes after training in time. |
Choosing k
Larger k means each model trains on a bigger share of the data, so the score is closer to what you would get training on everything. It also means more fits and more expensive curves. Smaller k is cheaper but trains on less data, which tends to give a slightly pessimistic estimate.
For curves, k = 5 is a sound default and k = 10 is common when data is scarce. There is a second effect specific to learning curves. The largest point is always (k - 1) / k of the dataset. With k = 3 the curve stops at two thirds of the data, which can hide whether the validation curve was still rising.
What the spread means
The mean of the fold scores is the estimate, and their standard deviation describes how much the score moves from fold to fold. This spread feeds the bands you will draw later. Two cautions apply.
- The fold scores are not independent. Training sets overlap heavily, and every sample is validated once. Dividing the standard deviation by
sqrt(k)to get a standard error therefore understates the true uncertainty. - With few samples per validation fold, the spread is mostly sampling noise. A 5-fold run on 100 samples validates on 20 samples at a time, so each score moves in steps of 5 percentage points.
When the spread is large relative to the differences you care about, add more folds or repeat the splits with different shuffles. Repetition gives more score samples without changing the model:
import numpy as np
from sklearn.datasets import load_digits
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import RepeatedStratifiedKFold, learning_curve
X, y = load_digits(return_X_y=True)
cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=3, random_state=0)
train_sizes, train_scores, val_scores = learning_curve(
LogisticRegression(max_iter=2000),
X,
y,
train_sizes=np.linspace(0.1, 1.0, 5),
cv=cv,
scoring="accuracy",
)
print(train_sizes)
print(val_scores.shape)The score arrays now have 15 columns, five splits times three repeats, instead of 5. This costs three times as many fits, so use it when the noise matters and the model is cheap.
Keeping the estimate honest
A cross-validated score is only trustworthy if nothing from the validation fold influences training. Fitting a scaler, imputer, or feature selector on the whole dataset before splitting lets information from the validation rows leak into the training step, and scores come out optimistic. Put every data-dependent step inside a Pipeline so it is refitted on each training part. Grouped samples need the same care: rows from one patient on both sides of a split inflate the validation score. The pitfalls chapter returns to both.
A second honesty issue arises when you use the validation score to choose something. Picking the best hyperparameter from a validation curve means the winning score is the best of several noisy numbers, so it is slightly optimistic for new data. Keep a separate final test set for the last check.
Key points
- Each curve point is the mean of per-fold scores, and the fold axis is the last axis of the returned arrays.
- The validation fold stays the same size in
learning_curve. Only the training portion grows. - The default splitters do not shuffle. Ordered data needs
shuffle=Trueor a splitter that fits the data's structure. - The largest learning-curve size is
(k - 1) / kof the dataset. - Fold scores overlap in their training data, so their spread is a rough guide and not a formal confidence interval.
Exercise
You run learningcurve on a dataset of 1,000 samples with cv=4 and trainsizes=[0.5, 1.0]. What are the two training sizes, and what is the size of each validation fold?
Show answer
With 4 folds, each validation fold holds 250 samples and each training part holds 750. Fractions apply to the training part, so the sizes are 375 and 750. The curve cannot show a training size of 1,000. The validation fold stays at 250 samples for both sizes.
Exercise
A colleague loads a CSV sorted by label, then runs crossvalscore with cv=KFold(n_splits=5) on a classifier. Scores are near zero. What is the likely cause, and what are two fixes?
Show answer
The unshuffled folds each contain a narrow, nonrepresentative range of labels, so the model is validated on classes it barely saw in training. Fixes: use KFold(nsplits=5, shuffle=True, randomstate=0), or use StratifiedKFold with shuffle=True so each fold keeps the class proportions.