Sub topic 12
From Nested Estimate to a Final Model
This chapter assumes you can write a GridSearchCV call, you know what cross_val_score returns, and you have already run nested cross-validation as shown in the previous chapters. Here we answer the question that follows it: nested cross-validation gives you a number, but which model do you ship?
The nested score evaluates a procedure, not a model
Nested cross-validation fits many models. Each outer fold trains its own inner search, and each inner search may pick different hyperparameters. None of those models is "the" model. The nested score does not describe any single fitted object.
What it estimates is the performance of the whole recipe: "run this grid search with this inner splitter on a training set of this size, then fit the winner." The outer test folds measure how well that recipe works on data it did not use for any choice.
This has a direct consequence for the final model. To deploy something whose quality the nested score describes, you rerun the same recipe on all your data.
Rerun the whole procedure on all data
The final fit is an ordinary grid search on the full dataset. The search must use the same pipeline, the same parameter grid and the same kind of inner splitter that you used inside the nested loop.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV, StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = load_breast_cancer(return_X_y=True)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=1)
pipe = make_pipeline(StandardScaler(), SVC())
param_grid = {"svc__C": [0.1, 1, 10], "svc__gamma": ["scale", 0.01, 0.001]}
# Final model: rerun the whole selection procedure on all the data.
final_search = GridSearchCV(pipe, param_grid, cv=cv)
final_search.fit(X, y)
final_model = final_search.best_estimator_GridSearchCV has refit=True by default. After it finds the best parameters, it refits the pipeline with those parameters on all the data it received. That refitted pipeline is best_estimator_. Because the scaler is inside the pipeline, it is also refitted on all of X, which is what you want for deployment.
The grid search here also reports a best_score_. Do not report that number as your performance. It is the optimistic score from the earlier chapters. Report the nested score instead.
What to say about the nested score
A correct statement has this shape: "Tuning an SVC over this grid with 5-fold inner selection, then evaluating on 5 outer folds, gave 0.97 ± 0.01 accuracy. We expect a model produced by the same procedure on all the data to perform about that well, or slightly better, since it trains on more data."
Three points matter in that sentence.
- The estimate belongs to the procedure. If you change the grid, the scaler, the inner splitter or the estimator after seeing the nested result, the number no longer describes what you ship.
- Training size is a small mismatch. Each outer training set holds a fraction of the data (80% with five folds). The final model sees 100%. For most learners, more data helps a little, so the nested score is mildly pessimistic about the final model. With few samples or a steep learning curve, the gap can be noticeable.
- The spread is across folds, not a confidence interval. The standard deviation of outer scores understates the true uncertainty, because the folds share training data. Later chapters cover the variance of the estimate.
Do not pick a "best" outer fold
A common mistake is to look at the per-fold results, find the outer fold with the highest score, and deploy that fold's fitted search. This throws away the guarantee. The outer score of that fold was measured on a small test set, and choosing the maximum of several noisy scores brings back the optimistic selection bias that nesting was meant to remove. It also trains on only part of the data.
The same applies to choosing hyperparameters by majority vote across outer folds and then calling the nested score the score of that choice. The vote is a reasonable heuristic. But the resulting configuration was selected using all the data, so the nested score is not a clean estimate for it. The cleanest option is to rerun the search on everything.
Per-fold chosen hyperparameters are still useful for diagnosis. The next code shows how to collect them with a manual outer loop.
from sklearn.base import clone
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV, StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = load_breast_cancer(return_X_y=True)
inner_cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=1)
outer_cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=2)
pipe = make_pipeline(StandardScaler(), SVC())
param_grid = {"svc__C": [0.1, 1, 10], "svc__gamma": ["scale", 0.01, 0.001]}
search = GridSearchCV(pipe, param_grid, cv=inner_cv)
for fold, (train_idx, test_idx) in enumerate(outer_cv.split(X, y)):
fold_search = clone(search)
fold_search.fit(X[train_idx], y[train_idx])
score = fold_search.score(X[test_idx], y[test_idx])
print(fold, fold_search.best_params_, round(score, 3))Read the output for stability. If every fold picks the same parameters, the final search will very likely pick them too, and your result is robust. If the choices vary widely but the outer scores are similar, the grid probably has a flat region where many settings perform alike, and the choice among them matters little. If the choices vary and the outer scores vary too, the procedure is unstable on this data, and the final model could land on a poor setting.
What the final model's own scores mean
Once you have final_search, it is tempting to call final_search.score(X, y) or to read final_search.best_score_. Neither is a fair estimate.
| Number | Where it comes from | Fair estimate of new-data performance? |
|---|---|---|
| `final_search.score(X, y)` | Final model scored on its own training data | No. It is a training score. |
| `final_search.best_score_` | Best candidate on the folds that selected it | No. Optimistic from selection. |
| Mean of nested outer scores | Procedure evaluated on folds not used for selection | Yes, for the procedure. |
| Score on a fresh, untouched test set | Final model on data never used for anything | Yes, for this specific model. |
The last row is worth noting. If you can afford to set aside a test set before any tuning, you get a direct estimate for the exact model you ship. Nested cross-validation is the better choice when data is too scarce to hold out a large test set, because every sample serves for both selection and evaluation.
Edge cases
refitset to a metric name. With several scorers,GridSearchCVneedsrefit="name"to choose which metric picks the winner. The nested score you report should use that same metric.- Different scoring in the final search. If the inner search used
scoring="roc_auc", the final search must as well. Otherwise it is a different procedure. - Randomized procedures. If the estimator or the search uses randomness (
RandomizedSearchCV, a random forest), fixrandom_statefor reproducibility, but remember the nested score describes the procedure averaged over that randomness, not one seed. - Grid at the edge. If the final search picks a value at the boundary of your grid, the optimum may lie outside it. Extending the grid changes the procedure, so you would need to rerun nested cross-validation to get an honest estimate.
- Model persistence. Save the whole
best_estimator_, not only the classifier, so the fitted scaler travels with it. Usejoblib.dump(final_model, "model.joblib").
Exercise
A colleague runs nested cross-validation and gets a mean outer accuracy of 0.94. Then they take the outer fold with the best score (0.98), deploy the search fitted on that fold's training data, and report 0.98 as its expected accuracy. List two problems with this.
Show answer
First, the 0.98 comes from choosing the maximum of several noisy outer scores, so it is optimistically biased. The fold's test set was used to make a decision, so it no longer gives an honest estimate. Second, that model was trained on only part of the data, and its quality is not what the nested score describes. The correct approach is to rerun the whole procedure (the grid search with its inner splitter) on all the data to get the final model, and to report the mean outer score (0.94) as the estimate for that procedure.
Exercise
Why is the nested score slightly pessimistic for the final model, and when would the gap be large?
Show answer
Each outer training set uses only a fraction of the data (80% with five outer folds), while the final model trains on all of it. More training data usually helps, so the final model tends to do a little better than the nested score suggests. The gap is large when the sample is small or the learning curve is still steep, because adding data then changes performance noticeably.