Sub topic 8
Telling a real improvement from noise
This chapter assumes you can train and score scikit-learn models, know accuracy, balanced accuracy and mean absolute error, and understand mean, standard deviation and standard error. It also assumes you have met cross-validation, which the previous chapter covers. The goal here is to decide whether a candidate model's higher score is a real improvement or just run-to-run variation.
Why a single score misleads
A score is one draw from a distribution. Change the random seed, the split or the training sample, and the score moves. Several things cause this:
- Test-set sampling. A small test set has few examples of the rare class, so one or two cases change the score visibly.
- Training-set sampling. A different training subset gives a slightly different fitted model.
- Algorithm randomness. Random forests, gradient boosting with subsampling, and neural networks depend on a seed.
- Split choice. Which examples land in which fold changes every fold's score.
If model A scores 0.81 and baseline B scores 0.80, you cannot yet say A is better. You need an estimate of how much 0.01 could move by chance.
Compare on identical folds
The first rule is to score both models on the same folds. Differences between folds, such as an easy fold or a fold with few positives, then affect both models equally. This is called a paired comparison. You look at the per-fold difference, not at two separate averages.
With a seeded RepeatedStratifiedKFold, every call to cross_val_score that receives the same cv object produces the same splits. The example below scores a constant baseline and a logistic regression on the same 15 test folds (5 folds, 3 repeats).
import numpy as np
from sklearn.datasets import make_classification
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import RepeatedStratifiedKFold, cross_val_score
X, y = make_classification(n_samples=2000, weights=[0.95, 0.05], random_state=0)
cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=3, random_state=0)
baseline_scores = cross_val_score(
DummyClassifier(strategy="prior"), X, y, cv=cv, scoring="balanced_accuracy"
)
model_scores = cross_val_score(
LogisticRegression(max_iter=1000), X, y, cv=cv, scoring="balanced_accuracy"
)
print("baseline:", baseline_scores.mean(), baseline_scores.std())
print("logreg: ", model_scores.mean(), model_scores.std())
diff = model_scores - baseline_scores
print("per-fold differences:", np.round(diff, 3))Two numbers matter here. The standard deviation of each model's scores shows how far a single fold can stray from the average. The per-fold differences show whether the candidate wins consistently or only on average.
A rough interval for the gain
Treat the per-fold differences as a sample. Their mean is the estimated gain. The standard error of that mean is the sample standard deviation divided by the square root of the number of differences. Two standard errors below the mean give a rough lower bound. If the lower bound is still above your required gain, the improvement is probably real and large enough.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import RepeatedStratifiedKFold, cross_val_score
X, y = make_classification(n_samples=2000, weights=[0.95, 0.05], random_state=0)
cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=3, random_state=0)
baseline_scores = cross_val_score(
DummyClassifier(strategy="prior"), X, y, cv=cv, scoring="balanced_accuracy"
)
model_scores = cross_val_score(
LogisticRegression(max_iter=1000), X, y, cv=cv, scoring="balanced_accuracy"
)
diff = model_scores - baseline_scores
mean_gain = diff.mean()
std_err = diff.std(ddof=1) / np.sqrt(len(diff))
min_useful_gain = 0.05 # set from the product requirement, not from the data
lower_bound = mean_gain - 2 * std_err
print("mean gain:", mean_gain)
print("rough lower bound:", lower_bound)
print("good enough on this criterion:", lower_bound > min_useful_gain)Set min_useful_gain before you look at results. If you choose it afterwards, you will tend to pick a value your model happens to clear. It should come from the task: what improvement changes a decision, saves a cost or meets a requirement.
Why this standard error is optimistic
The formula above treats the 15 differences as independent. They are not. Within one repeat, each training set shares about 75% of its examples with every other training set (with 5 folds, any two training sets overlap on three of the five parts). Across repeats the same examples appear again in new folds. The differences are positively correlated, so the real uncertainty is larger than std_err suggests, and the interval is too narrow.
Nadeau and Bengio proposed a correction for this. It inflates the variance of the differences by adding a term based on the ratio of test size to training size:
import numpy as np
# Reuses diff from the previous example. The setup used 5 folds and 3 repeats.
n_splits = 5
n_resamples = len(diff) # 15 scored folds in total
test_to_train = 1 / (n_splits - 1) # test size / train size for k folds
corrected_se = np.sqrt(diff.var(ddof=1) * (1 / n_resamples + test_to_train))
naive_se = diff.std(ddof=1) / np.sqrt(n_resamples)
print("naive SE: ", naive_se)
print("corrected SE:", corrected_se)The corrected value is usually several times larger. Using it is the conservative choice, and it stops you from declaring wins that more data would not confirm. Neither version is exact, so use either as a guide and not as a verdict.
Reading the result
Compare three quantities: the mean gain, the uncertainty around it, and the minimum useful gain you set earlier. They give four cases.
| Situation | Interpretation | Action |
|---|---|---|
| Lower bound above the minimum useful gain | Real and large enough | Move on to cost and error analysis |
| Lower bound above zero but below the minimum | Probably real but small | Weigh the added cost, or look for larger gains elsewhere |
| Interval includes zero | Not distinguishable from noise | Prefer the simpler model, or collect more data |
| Mean gain is negative | The candidate is worse | Check for bugs, then reconsider the approach |
When the interval includes zero, the result does not prove the models are equal. It only says your evidence is too weak to separate them. That is still useful, because with equal evidence the cheaper and simpler model is the better choice.
Common errors
- Comparing against different splits. If each model gets its own random split, the differences in fold difficulty count as differences in model quality.
- Reporting the best of many runs. Running ten seeds and quoting the highest score builds in an upward bias. Report the mean and spread.
- Tuning on the comparison folds. If you selected hyperparameters using the same folds you now use for the comparison, the candidate's score is inflated. Use nested cross-validation or a held-out test set the tuning never saw.
- Ignoring the metric's own noise. Rare-class metrics such as recall on a 5% class are noisier than overall accuracy. A test fold with 20 positives moves by 0.05 when a single case flips.
- Treating a significance test as the goal. A tiny gain can be statistically clear and still worthless. A large gain can be statistically unclear on a small dataset. You need both the interval and the minimum useful gain.
- Forgetting unit-level dependence. If the data contain several rows per customer or patient, plain stratified folds put the same person in training and test. Use grouped splitting, or the scores will be too high for both models and the gap will be unreliable.
Edge cases
When the baseline is a constant predictor, as above, its scores barely vary, so almost all the noise comes from the candidate. When the baseline is itself a trained model, the differences also carry its variance, and pairing matters more.
On small datasets, each fold's test set is small and the per-fold scores are noisy. Use more folds with repeats, and treat the corrected standard error as the main guide.
For time series, shuffled folds break the temporal order. Use expanding-window splits instead, compare the two models on the same windows, and expect fewer, more correlated differences.
If the candidate uses randomness internally, fix its seed for reproducibility but also check a few seeds. A gain that disappears when the seed changes is noise.
Exercise
A candidate model has a mean balanced-accuracy gain of 0.03 over a baseline across 15 paired folds. The standard deviation of the 15 differences is 0.04. Your product requirement is a gain of at least 0.02. Compute the rough lower bound using the naive standard error and two standard errors, and say whether the criterion is met. Then say why you might still hesitate.
Show answer
The standard error is 0.04 / sqrt(15), which is about 0.0103. Two standard errors are about 0.0206, so the lower bound is 0.03 - 0.0206, about 0.0094. That is below 0.02, so the criterion is not met. The gain is probably above zero, but you cannot claim it clears the required 0.02. The naive standard error is also optimistic because the folds overlap. With the corrected formula for 5 folds (variance multiplied by 1/15 + 0.25, about 0.317), the standard error would be about 0.0225, so the lower bound would be negative. The evidence is even weaker than the naive calculation suggests.