Choosing inflates the winner
The best of many noisy scores is too good, even when every score is honest. See the winner's curse, nested cross-validation and what plays the outer loop in the app.
What runs in CodeSplash
- XGBoost Verified in Python and R
You will be able to
- Explain why the best cross-validated score is optimistic
- Describe nested cross-validation and when it's worth the cost
- Use the locked test set as the outer check on a tuning run
Read first
The honest scores, and the dishonest maximum
ReadEach model's cross-validated score may be fair on its own. Now take 40 settings and keep the best.
Part of why it came top is real, and part is luck on these folds. Choosing the top score selects for the luck too, so the winner's number overstates what it will do next. This is selection biasSelection biasA systematic gap between the sample and the population, caused by how units got into the data., and it grows with how many candidates you try and how noisy each score is.
All equal, one winner
PredictPredict first
Suppose 100 settings are all exactly as good as each other, and each cross-validated score has the same random error. What will the best score look like compared with the truth?
Reveal
Well above it. The maximum of 100 noisy draws sits about two and a half standard deviations above their mean, and none of that lift is real. With 1,000 draws it's over three. The same thing happens in studies, where only the striking results get reported.
See the curse
ExploreLower n per group and watch how much the significant studies overstate the truth. It's the same arithmetic as keeping the best model: the filter favors lucky draws.
BExplorable · The winner's curse
Why do significant results from small studies overstate the effect?
Among the significant studies, how many times larger than the truth is the average reported effect?
Commit your prediction above to see the result
Make your prediction to see the result.
Nested cross-validation
ReadTo score the whole tuning recipe honestly, wrap it in another loop.
- Outer folds hold rows out of everything.
- Inner folds tune on what's left.
- The outer score judges the tuned recipe.
DExplorable · Cross-validation folds
Which rows should be held out so the score predicts real performance?
Each scheme has a tempting shortcut: training error, plain random folds, or the best score from a search. Will the shortcut here look better than the true error on new data?
Scheme
Commit your prediction above to see the result
Make your prediction to see the result.
Compare The shortcut, the best inner score, with This scheme and True new-data error.
In the app
ReadNesting multiplies the fits, so by default the app uses a cheaper pair: tuning runs on the folds, and the locked test set plays the outer loop once, on the setting it picked.
With too few rows for a trusted test set, turn on Nested cross-validation in the Validation step. Each outer fold tunes on its own inner folds, and the run reports the nested estimate, its interval and how much the inner scores flattered the winner.
The gap between a tuned run's CV and Test columns is partly noise and partly this inflation. Expect the test score to be lower. If it comes out far lower, suspect too many trials on too few rows, or leakage.
Keep the search small
ReflectYou have 150 rows and are about to search 500 settings across 8 hyperparameters. Before you press Tune…, what would make the winner's number more believable? Think about fewer trials, fewer parameters, a simpler learner, or more rows. Which would you give up first?
Check your understanding
CheckpointCheck yourself
Why is the best tuning score optimistic, even though each trial was scored on held-out folds?
Show the answer
Answer: b
Each score is fair alone, and it's the selection that biases the winner's. Plain cross-validation is, if anything, slightly pessimistic.
Check yourself
When is full nested cross-validation most worth its cost?
Show the answer
Answer: a
With plenty of rows a locked test set does the job. Nesting earns its cost when you can't afford to hold rows out once.
Check yourself
A tuning run tries 40 settings. How many of them should score the locked test set?
Show the answer
Answer: 1
One: the best setting is refit and scored once. In the app, the rest are scored only on folds.
See it on a tuning run
In the appSelect a model in the Learners step, as the walkthrough does for {{target}}, and press Tune…. The dialog says each trial cross-validates on this experiment's folds, and the best setting is refit and scored once. When it finishes, the Tuning tab shows the Trials, and the Leaderboard shows the tuned run's CV and Test side by side.
import pandas as pd
from sklearn.model_selection import GridSearchCV, cross_val_score
from sklearn.tree import DecisionTreeClassifier
df = pd.read_csv("pima.csv")
X, y = df.drop(columns="diabetic"), df["diabetic"]
search = GridSearchCV(DecisionTreeClassifier(random_state=1),
{"max_depth": [2, 3, 4, 6, 8], "min_samples_leaf": [1, 5, 20]},
cv=5, scoring="roc_auc")
print("best inner score", search.fit(X, y).best_score_.round(3))
print("nested score", cross_val_score(search, X, y, cv=5, scoring="roc_auc").mean().round(3))library(rpart)
df <- rbind(MASS::Pima.tr, MASS::Pima.te)
grid <- expand.grid(depth = c(2, 3, 4, 6, 8), leaf = c(1, 5, 20))
auc <- function(y, p) as.numeric(pROC::auc(y, p, quiet = TRUE))
cv_auc <- function(d, g) {
fold <- sample(rep(1:5, length.out = nrow(d)))
mean(sapply(1:5, function(k) {
ctl <- rpart.control(maxdepth = g$depth, minbucket = g$leaf, cp = 0)
fit <- rpart(type ~ ., d[fold != k, ], control = ctl)
auc(d$type[fold == k], predict(fit, d[fold == k, ])[, "Yes"])
}))
}
set.seed(1)
inner <- sapply(seq_len(nrow(grid)), function(i) cv_auc(df, grid[i, ]))
outer <- sample(rep(1:5, length.out = nrow(df)))
nested <- sapply(1:5, function(k) {
d <- df[outer != k, ]
g <- grid[which.max(sapply(seq_len(nrow(grid)), function(i) cv_auc(d, grid[i, ]))), ]
ctl <- rpart.control(maxdepth = g$depth, minbucket = g$leaf, cp = 0)
auc(df$type[outer == k], predict(rpart(type ~ ., d, control = ctl), df[outer == k, ])[, "Yes"])
})
round(c(best_inner = max(inner), nested = mean(nested)), 3)Recap
Recap- The best of many honest scores is optimistic, and more trials on fewer rows make it worse.
- Nested cross-validation scores the whole tuning recipe, at a cost.
- In the app the locked test set checks the winner, once.
Concepts in this lesson