Sub topic 10
Fold-to-Fold Variability and Error Bands
This chapter assumes you can already compute a learning curve and a validation curve with learning_curve and validation_curve, and that you know what k-fold cross-validation does. Those functions return one score per fold. The mean of those scores gives the curve you plot. The spread gives the error band around it. This chapter explains where the spread comes from, how to draw it, and what it can and cannot tell you.
Why the scores differ between folds
Each fold gives a different score for the same model and the same hyperparameters. There are four main causes:
- Validation fold composition. A small validation fold contains only a few samples, so its accuracy moves in large steps. A fold that happens to hold more hard examples scores lower.
- Training subset composition. In a learning curve, each fold trains on a different subset of the data. At small training sizes, which samples you picked matters a lot.
- Estimator randomness. Random forests, stochastic gradient descent, and neural networks give different results with different seeds, even on identical data.
- Class imbalance. With a rare class, one fold may hold only a few positives, which makes metrics such as recall or F1 very noisy.
The diagram shows how these causes combine into one band.
Computing the spread
Both curve functions return arrays with one row per setting (training size or hyperparameter value) and one column per fold. Reducing along axis=1 gives one statistic per setting. The block below uses repeated stratified k-fold, which gives more columns than plain 5-fold and so a steadier estimate of the spread.
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",
n_jobs=-1,
)
print("scores per size:", val_scores.shape) # (5, 15)
val_mean = val_scores.mean(axis=1)
val_std = val_scores.std(axis=1, ddof=1)
for n, m, s, lo, hi in zip(
train_sizes, val_mean, val_std, val_scores.min(axis=1), val_scores.max(axis=1)
):
print(f"n={n:5d} mean={m:.3f} std={s:.3f} range=[{lo:.3f}, {hi:.3f}]")Two details matter here.
- NumPy's
stdusesddof=0by default, which divides byn. For a sample of fold scores,ddof=1is the usual choice. With 5 folds the two differ by about 12 percent. With 15 columns they differ by about 3 percent. - The minimum and maximum are worth printing next to the standard deviation. With only a handful of folds, the range shows you the actual worst and best fold, which is often more concrete than a standard deviation.
Drawing the band
fill_between shades the area between mean - std and mean + std. This block continues from the previous one and reuses its variables.
import matplotlib.pyplot as plt
# Continues from the previous block: train_sizes, train_scores, val_scores.
train_mean = train_scores.mean(axis=1)
train_std = train_scores.std(axis=1, ddof=1)
val_mean = val_scores.mean(axis=1)
val_std = val_scores.std(axis=1, ddof=1)
fig, ax = plt.subplots()
ax.plot(train_sizes, train_mean, marker="o", label="Training score")
ax.fill_between(train_sizes, train_mean - train_std, train_mean + train_std, alpha=0.2)
ax.plot(train_sizes, val_mean, marker="o", label="Cross-validation score")
ax.fill_between(train_sizes, val_mean - val_std, val_mean + val_std, alpha=0.2)
ax.set_xlabel("Number of training samples")
ax.set_ylabel("Accuracy")
ax.legend()
plt.show()Shaded bands can hide a skewed distribution. Scores near 1.0 cannot go above 1.0, so the true spread is lopsided, and a symmetric band may extend past the maximum possible score. If that happens, plot the minimum and maximum, or percentiles, instead of the standard deviation.
What the band means
A band of one standard deviation describes how much a single fold's score varies. It does not describe how uncertain the mean is. The uncertainty of the mean is smaller. If the folds were independent, the standard error of the mean would be the standard deviation divided by the square root of the number of folds.
The folds are not independent, though. Any two training sets in k-fold share most of their samples, so the scores are positively correlated. The naive standard error therefore underestimates the true uncertainty. The same problem is worse with repeated k-fold: 15 scores from 3 repeats carry far less information than 15 independent scores.
Reading bands on a learning curve
Bands change what you can conclude from the curve shapes covered in earlier chapters.
- Is the gap real? Compare the gap between the training and validation means with the width of the validation band. A gap of 0.02 inside a band of plus or minus 0.03 is not evidence of overfitting.
- Has the curve flattened? If the last two validation means differ by less than the band width, you cannot tell whether more data would help. The curve may be flat, or it may still be rising slowly.
- Why is the band wide at small sizes? The band normally narrows as the training size grows, because the training sets overlap more and each sample matters less. A band that stays wide at the largest size points to something else, such as a tiny validation fold, a rare class, or a high-variance estimator.
- Is the training band wide? A wide band on the training curve is a sign of an unstable fit, for example an optimizer that sometimes fails to converge.
Bands on a validation curve and the one-standard-error rule
On a validation curve the band tells you how flat the top of the curve is. If several hyperparameter values score within one band width of the best, they are statistically hard to tell apart. A common rule is to pick the simplest model whose mean score is within one standard error of the best mean score. This is the one-standard-error rule. It trades a tiny, probably unreal score gain for a simpler model that is likely to generalize as well.
For an RBF SVM, a smaller gamma gives a smoother, simpler decision boundary. The code below picks the smallest gamma that is within one standard error of the best.
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import RepeatedStratifiedKFold, validation_curve
from sklearn.svm import SVC
X, y = load_digits(return_X_y=True)
param_range = np.logspace(-6, -1, 6) # ascending: simplest model first
cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=2, random_state=0)
train_scores, val_scores = validation_curve(
SVC(kernel="rbf"),
X,
y,
param_name="gamma",
param_range=param_range,
cv=cv,
scoring="accuracy",
n_jobs=-1,
)
val_mean = val_scores.mean(axis=1)
val_se = val_scores.std(axis=1, ddof=1) / np.sqrt(val_scores.shape[1])
best = val_mean.argmax()
threshold = val_mean[best] - val_se[best]
within = np.flatnonzero(val_mean >= threshold)
chosen = within.min() # smallest gamma inside the threshold
print(f"best gamma: {param_range[best]:.0e} mean={val_mean[best]:.3f}")
print(f"chosen gamma: {param_range[chosen]:.0e} mean={val_mean[chosen]:.3f}")Because the standard error here is optimistic, as explained above, this rule is a little less conservative than it looks. It still gives a sensible tie-breaker, and it stops you from chasing a peak that is only noise.
Reducing variability
You can narrow a band, but only some methods address the true cause.
| Method | What it reduces | Cost and caveat |
|---|---|---|
| More folds (for example 10 instead of 5) | Training set differences between folds | More fits. Each validation fold is smaller, so single scores get noisier. |
| Repeated k-fold | Dependence on one particular split | Multiplies run time. Gives a steadier mean, but not independent samples. |
| Stratified splits | Class proportion differences between folds | Only helps classification. |
| Fixed random seeds on the estimator | Run-to-run randomness | Hides randomness instead of measuring it. Report results over several seeds as well. |
| More data | All of the above | Often the real fix, and often unavailable. |
Fixing random_state on the splitter makes your plot reproducible, but it does not make the result more certain. A different seed gives a different curve, and that difference is what the band describes.
Common errors
- Reporting only the mean. Two models with means of 0.91 and 0.92 are not different if both bands are plus or minus 0.02.
- Mixing up standard deviation and standard error in axis labels or captions. State which one the band shows.
- Ignoring dependent samples. If several rows come from the same patient or user, ordinary folds leak related rows across the split. Scores become too high and the band becomes too narrow. Use
GroupKFoldand passgroups, as covered in the pitfalls chapter. - Too few folds for a band. A standard deviation from 3 folds is very unreliable. Prefer at least 5, and use repeats when data is small.
- Reading bands as confidence intervals. A one-standard-deviation band covers roughly two thirds of fold scores if they are roughly normal. It is not a 95 percent interval for the true score.
Exercise
A validation curve for a random forest shows mean accuracy 0.874 at maxdepth=8 and 0.881 at maxdepth=16, with a standard deviation of 0.015 across 5 folds for both. Which depth would you choose, and why?
Show answer
Choose max_depth=8. The difference of 0.007 is much smaller than the fold-to-fold standard deviation of 0.015 (the standard error is about 0.007), so the two settings cannot be reliably told apart. The shallower forest is simpler and cheaper, and it is at least as likely to generalize. Under the one-standard-error rule, 0.874 lies within one standard error of the best mean of 0.881, so the simpler setting wins.
Exercise
Your learning curve's validation band is still wide at the largest training size, while the training band is narrow. List two likely causes and one change to try for each.
Show answer
One cause is a small validation fold or a rare class, which makes each fold's score noisy. Try stratified splits, or use repeated k-fold to average over more splits. Another cause is that the samples differ a lot from each other, or are related across folds, for example several rows per patient. Try GroupKFold with a group label, and check whether the band widens, which would mean the earlier scores were too optimistic. High estimator randomness is a third possible cause, to be checked by refitting with several seeds.