Sub topic 11
Reading outer scores and per-fold chosen hyperparameters
This chapter assumes you can run GridSearchCV and cross_val_score, and that you know why the best score of a search is optimistic. It also assumes you have seen the nested setup, where an inner search runs inside each outer training set. Here the question is what to do with the output. You will pull out the outer scores and the hyperparameters chosen in each fold, compare them, and decide what to report.
What nested cross-validation returns
Nested cross-validation gives you one outer test score per outer fold. Each score comes from a model that was tuned only on that fold's training data, and the outer test fold was never used for tuning. The mean of these scores estimates how well your whole tuning procedure performs on new data. The procedure is the pipeline, the grid, the inner splitter, and the scoring rule together.
The nested score does not describe one specific set of hyperparameters. Each outer fold may pick different hyperparameters, so the scores belong to the procedure, not to a single model.
Getting more than the scores
cross_val_score returns only the outer scores. To see what each inner search chose, use cross_validate with return_estimator=True. It returns the fitted GridSearchCV object from every outer fold.
import pandas as pd
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV, StratifiedKFold, cross_validate
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)
results = cross_validate(search, X, y, cv=outer_cv, return_estimator=True)
rows = []
for fold, (est, score) in enumerate(zip(results["estimator"], results["test_score"])):
rows.append(
{
"fold": fold,
"outer_score": score,
"inner_best": est.best_score_,
"C": est.best_params_["svc__C"],
"gamma": est.best_params_["svc__gamma"],
}
)
df = pd.DataFrame(rows)
df["gap"] = df["inner_best"] - df["outer_score"]
print(df.round(3).to_string(index=False))
print()
print(f"outer mean: {df['outer_score'].mean():.3f}")
print(f"outer std: {df['outer_score'].std():.3f}")
print(f"mean gap: {df['gap'].mean():.3f}")The table has one row per outer fold. Four columns matter:
| Column | Meaning |
|---|---|
| `outer_score` | Score on the untouched outer test fold. This is the honest number. |
| `inner_best` | The inner search's `best_score_`, computed on the inner folds that chose the winner. |
| `C`, `gamma` | The winning hyperparameters for that outer training set. |
| `gap` | `inner_best` minus `outer_score`. A rough view of selection optimism in that fold. |
Reading the outer scores
Look at three things: the center, the spread, and the outliers.
- Center. The mean of
outer_scoreis your headline estimate. Use the same metric you tuned on, unless you have a reason to report something else. - Spread. The standard deviation across folds shows how much the score moves from one test fold to the next. With five folds on a small dataset, each fold holds few samples, so some of that spread is plain sampling noise.
- Outliers. One fold far below the others often points to a hard subgroup in that test fold. It can also point to a split problem, such as missing groups or time order. Check the splitter before blaming the model.
Do not treat mean ± std as a confidence interval for generalization. The outer training sets overlap heavily, so the fold scores are correlated. The naive standard error, std / sqrt(k), is usually too small. Report the spread as variability across folds. Chapter 14 covers repeating the procedure to get a better view of the noise.
Reading the gap
The gap column compares the inner search's best score with the outer score. A positive mean gap is the optimism from the previous chapters, made visible. The inner score is a maximum over candidates on the folds that picked it. The outer score is not.
A gap near zero means that on this problem, selection added little bias. This is common when the grid is small and the candidates perform almost the same. A large gap means the grid is rich relative to the data, and the winner partly fits noise in the inner folds.
The gap is a diagnostic. Do not subtract it from inner_best to "correct" a score. The outer mean is the estimate.
Reading the chosen hyperparameters
The per-fold choices tell you how stable the tuning is. Count them:
from collections import Counter
choices = Counter(
(est.best_params_["svc__C"], est.best_params_["svc__gamma"])
for est in results["estimator"]
)
for params, count in choices.most_common():
print(params, "chosen in", count, "of", len(results["estimator"]), "folds")Three patterns come up often:
- The same setting wins every fold. The data clearly prefers it. You can be confident about the final choice.
- A few neighboring settings share the wins. The score surface is flat there, and any of them would do. This is the most common pattern.
- Very different settings win in different folds. The inner search is unstable, or the data is small, or the score depends weakly on the grid.
Look carefully at what "different" means. In this grid, gamma="scale" means 1 / (n_features * X.var()). After StandardScaler, the data has variance 1, and the dataset has 30 features, so "scale" is about 0.033. A fold that picks "scale" and a fold that picks 0.01 chose nearby values, even though the labels look unrelated. Compare numeric values, not strings.
Also check whether any winner sits on the edge of the grid, for example the largest C or the smallest gamma. If so, the best value may lie outside the range you searched. Extend the grid and rerun the nested procedure.
A reading checklist
What to report
A clear report has these parts:
- The metric, the pipeline, the grid, and the inner and outer splitters, including fold counts and seeds.
- The outer mean and the spread across folds, for example
0.975 ± 0.010if that is what your run gives. - The per-fold chosen hyperparameters, or a count of them.
- A statement of what the number estimates: the expected performance of the full tuning procedure, not of one fixed model.
Avoid reporting best_score_ from a plain search next to the nested score as if they measure the same thing. If you show both, label the first as optimistic and use the gap to explain why.
Common reading mistakes
- Using the inner score as the result.
inner_bestis optimistic by construction. - Treating the per-fold winners as a ranking. Winners from different training sets are not comparable on the outer scores. Each outer score belongs to a different tuned model.
- Comparing two procedures on different splits. If you compare two algorithms, use the same outer splitter and seed so that both see identical test folds. Otherwise part of the difference is split luck.
- Overreading small differences. A difference of 0.003 between two procedures is almost certainly within the noise of a five-fold estimate.
- Ignoring fold sizes. If outer folds have unequal sizes, as with grouped splits, a plain mean of scores weights small folds too much. Consider a size-weighted mean, or report both.
Exercise
A nested run with five outer folds gives outer scores 0.96, 0.97, 0.95, 0.97, 0.96 and inner best scores of about 0.98 in every fold. In four folds the inner search chose C=10, and in the fifth it chose C=10 too, but at the largest value in the grid. What do you conclude about the estimate, and what would you do next?
Show answer
The outer mean is about 0.962, and that is the estimate for the tuning procedure. The gap of roughly 0.02 shows the inner score is optimistic, so do not report the inner score. The scores are consistent across folds, so the estimate looks stable. However, C=10 is the largest value in the grid, so the true optimum may be higher. Extend the grid, for example to 100 and 1000, rerun the nested procedure, and report the new outer mean. Only then fit the final model.