Sub topic 9
Comparing a candidate to the baseline
This chapter assumes you can train scikit-learn estimators, you know the common metrics, and you know what a standard error is. It also assumes you have already built at least one trivial baseline and chosen a metric. Here you compare a candidate model to that baseline and decide whether the difference is real.
What a fair comparison needs
A comparison is fair when the only thing that differs between the two scores is the model. Everything else must be held fixed:
- Same data. Both models see the same rows and the same features, unless the feature set is the thing you are testing.
- Same splits. Both models train and are scored on identical folds.
- Same metric. Pick it before you look at results, as covered earlier in the tutorial.
- Same preprocessing discipline. Scaling, imputation and feature selection are fitted inside each training fold, never on the full dataset.
- Same effort. If you tune the candidate for a week and run the baseline with defaults, you are measuring tuning effort, not model quality.
The last point is the most common failure. A baseline that is tuned only lightly is still a valid floor. But you should say so, and you should not claim a large win over a deliberately weak opponent.
Paired scores on shared folds
With repeated cross-validation, you get one score per fold for each model. If both models use the same seeded splitter, fold i is the same data for both. That makes the scores paired, and you should analyze the per-fold differences rather than the two means separately.
Pairing matters because some folds are easy and some are hard. Both models do well on easy folds and badly on hard ones. The difference between them cancels most of that shared variation, so it is much less noisy than either score alone.
Running the comparison
The following script scores a majority-class baseline and a logistic regression on the same 15 folds (5 folds, 3 repeats). It then computes the paired differences and two standard errors.
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 = cross_val_score(
DummyClassifier(strategy="prior"), X, y, cv=cv, scoring="balanced_accuracy"
)
candidate = cross_val_score(
LogisticRegression(max_iter=1000), X, y, cv=cv, scoring="balanced_accuracy"
)
diff = candidate - baseline
n = len(diff)
mean_gain = diff.mean()
naive_se = diff.std(ddof=1) / np.sqrt(n)
# Nadeau-Bengio correction: folds share training data, so they are not independent.
# With 5 folds, each test fold is 1/5 of the data and each training set is 4/5.
test_over_train = 1 / 4
corrected_se = np.sqrt((1 / n + test_over_train) * diff.var(ddof=1))
print("baseline mean:", baseline.mean())
print("candidate mean:", candidate.mean())
print("mean gain:", mean_gain)
print("naive SE:", naive_se)
print("corrected SE:", corrected_se)Passing the same cv object to both calls gives identical splits, because an integer random_state makes the splitter reproduce the same folds each time it is used. Check this on your own setup if you change the splitter. A splitter with random_state=None would give each model different folds and break the pairing.
Why the standard error needs a correction
The naive formula divides the standard deviation by the square root of the number of folds. It assumes the 15 differences are independent. They are not. Any two training sets overlap heavily, and repeated runs reuse the same rows. The naive standard error is therefore too small, and it shrinks as you add repeats even though you have gained no new information.
The Nadeau-Bengio correction multiplies the variance by a factor of 1/n + n_test/n_train instead of 1/n. The second term does not shrink with more repeats, which keeps the interval from collapsing. The result is still approximate. Treat it as a guide, not an exact confidence interval.
Reading the numbers
Three things decide what the result means.
- The size of the gain. A mean gain of 0.001 on a 0–1 metric is almost never worth a more complex system, however small its standard error.
- The uncertainty. If the gain is smaller than about twice the corrected standard error, you cannot tell it from noise.
- The minimum useful gain. This is a number you set from the product requirement before running the experiment. It answers the question "how much better must it be to matter?"
A common mistake is to stop at statistical significance. A gain can be real and still too small to justify the cost. The decision rule used in this tutorial combines both: the mean gain minus a noise allowance must still exceed the minimum useful gain.
import numpy as np
# Reuses diff, mean_gain and corrected_se from the previous script.
min_useful_gain = 0.05 # set from the product requirement, not from the data
lower_bound = mean_gain - 2 * corrected_se
print("lower bound:", lower_bound)
print("good enough on this criterion:", lower_bound > min_useful_gain)
print("folds where candidate lost:", int((diff < 0).sum()), "of", len(diff))The last line is a useful sanity check. If the candidate loses on several folds, the mean gain hides an unstable model, even when the lower bound passes.
Several comparisons, one dataset
If you compare ten candidates to the baseline and report the best one, you have selected on the test folds. The winning score is optimistically biased, because the best of ten noisy numbers is higher on average than any single honest estimate.
Ways to limit this:
- Keep a final holdout set that is touched once, for the single chosen model.
- Use nested cross-validation when you tune hyperparameters, so tuning never sees the scoring folds.
- Record how many candidates you tried, and report that number alongside the result.
- Raise the bar for the minimum useful gain as the number of candidates grows.
Common failure modes
| Symptom | Likely cause | What to do |
|---|---|---|
| Candidate beats the baseline by a wide margin on accuracy but not on balanced accuracy | Imbalanced classes and a metric that rewards the majority class | Re-run with the metric fixed in advance |
| Gain is large with one seed and gone with another | Single split, high variance | Use repeated cross-validation and report the spread |
| Candidate wins in cross-validation and loses after deployment | Leakage, or the data distribution shifted | Audit the pipeline for fitting on all data, and check time ordering |
| Naive standard error shrinks every time you add repeats | Treating overlapping folds as independent | Use the corrected standard error |
| Candidate wins on average but loses badly on one group | Averages hide slices | Evaluate slices, covered in the error analysis chapter |
Time series need a different splitter
For forecasting, shuffled folds let the model train on the future and predict the past. Use a splitter that respects time, such as TimeSeriesSplit, and compare against the naive "tomorrow equals today" forecast on those same splits. The paired-difference logic still applies. The independence assumption is weaker still, so give your standard error even less weight.
When the baseline is an existing system
If the baseline is a rule set or a model already in production, you may not be able to re-run it on your folds. In that case, score its logged predictions on the same held-out rows. If its outputs were collected only on rows it flagged or acted on, the comparison is biased, and you need a randomly sampled evaluation set.
A short checklist
- Metric and minimum useful gain are written down before the experiment.
- Both models use one seeded splitter and the same preprocessing inside the folds.
- You report the baseline score, the candidate score, the mean paired gain and a corrected uncertainty estimate.
- You report the number of candidates tried.
- You have looked at the per-fold differences, not only their mean.
Exercise
A candidate scores a mean gain of 0.03 over the baseline across 15 paired folds. The corrected standard error of the differences is 0.012, and the product requirement says the gain must be at least 0.02. Using the rule "mean gain minus 2 standard errors must exceed the minimum useful gain", does the candidate pass? What would you do next?
Show answer
The lower bound is 0.03 - 2 × 0.012 = 0.006, which is below 0.02, so the candidate does not pass. The gain is probably real (0.006 is above zero), but the data does not show that it reaches the required size. Next steps: check the per-fold differences for instability, look at error slices for where the model helps or hurts, and either improve the candidate or gather more evaluation data before deciding.
Exercise
A teammate compares a candidate and a baseline by calling cross_val_score on each with cv=KFold(n_splits=5, shuffle=True) and no random_state. What is wrong, and how do you fix it?
Show answer
With shuffle=True and no random_state, each call draws different folds, so the two models are scored on different splits and the per-fold differences are not paired. Create one splitter with a fixed random_state (for example RepeatedStratifiedKFold(..., random_state=0) for classification) and pass that same object to both calls.