Sub topic 16
Interpreting and reporting results
A tuning run ends with a table of scores and a "best" row. This chapter covers how to decide what that row means, how much to trust it, and what to write down so someone else can check it. It assumes you can run GridSearchCV or RandomizedSearchCV and know the roles of the training, validation, and test splits from earlier chapters.
The best score is a biased estimate
The best cross-validation score is the maximum over many noisy measurements. Each setting's score has random error from the fold split and the data sample. Picking the maximum favors settings that were lucky as well as good. This is the winner's curse. The more settings you try, the larger the effect.
Two consequences follow:
best_score_from a search is usually a little too high as an estimate of future performance.- The gap grows with the number of trials and shrinks with more data.
Report best_score_ as "the score used to select a setting", not as the expected performance. For expected performance, use one of two sources:
- A held-out test set, scored once after the search finishes.
- Nested cross-validation, which scores the whole tuning procedure on outer folds.
If the test score is clearly lower than the best cross-validation score, a small gap is normal. A large gap points to leakage in the search, an over-large search space, or a test set that differs from the training data.
Look at the whole results table
best_params_ hides how the search behaved. Scikit-learn stores every trial in cv_results_, which converts directly to a DataFrame.
import numpy as np
import pandas as pd
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV, train_test_split
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)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0, stratify=y
)
pipe = make_pipeline(StandardScaler(), SVC())
param_grid = {
"svc__C": [0.1, 1, 10],
"svc__gamma": [0.001, 0.01, 0.1],
}
search = GridSearchCV(
pipe, param_grid, cv=5, scoring="accuracy", return_train_score=True
)
search.fit(X_train, y_train)
results = pd.DataFrame(search.cv_results_)
cols = [
"param_svc__C",
"param_svc__gamma",
"mean_test_score",
"std_test_score",
"mean_train_score",
"mean_fit_time",
"rank_test_score",
]
table = results[cols].sort_values("rank_test_score")
print(table.head(5).to_string(index=False))
# Which settings are within one standard error of the best?
best_row = results.loc[results["rank_test_score"] == 1].iloc[0]
std_error = best_row["std_test_score"] / np.sqrt(search.cv)
threshold = best_row["mean_test_score"] - std_error
close = results[results["mean_test_score"] >= threshold]
print(f"{len(close)} of {len(results)} settings are within one standard error")The columns to read are:
mean_test_scoreandstd_test_score: the validation score and its spread across folds.mean_train_score: only present withreturn_train_score=True. A large gap between train and validation score means the setting overfits.mean_fit_time: the cost of each setting, which matters when scores are close.rank_test_score: ties share a rank, so several rows can have rank 1.
Decide whether differences are real
If the best setting scores 0.972 and the second scores 0.970, with a fold standard deviation of 0.015, the data cannot separate them. Treat them as tied.
A practical rule is the one-standard-error rule. Take the standard error of the best setting, which is the fold standard deviation divided by the square root of the number of folds. Then choose the simplest or cheapest setting whose mean score is within that distance of the best. "Simplest" means a smaller max_depth, a stronger regularization penalty, fewer trees, or a faster fit. The code above lists the candidates. You then apply your own ordering of simplicity to pick one.
The standard error from CV folds is only a rough guide. Folds share training data, so they are not independent, and the true uncertainty is larger. Use the rule to break near-ties, not to claim a statistical result.
Check the shape of the landscape
Scores across the search space carry information beyond the winner.
- Best value on the boundary. If the best
Cis the largest value you tried, the optimum may lie outside the range. Extend the range and rerun. - Flat plateau. If many settings score the same, the model is insensitive to those hyperparameters. You can fix them at defaults and drop them from future searches.
- Sharp peak. If one narrow setting is far above its neighbors, suspect noise or a fragile result. Rerun with different fold seeds to see if it holds.
- Train score near 1.0, validation score much lower. The model overfits at that setting. Look for settings with more regularization.
- Both scores low. The model underfits. Tuning inside this range will not help. Consider a more flexible model or better features.
For random search, plot the score against each hyperparameter separately, using a log axis for log-scaled parameters. A scatter shows which parameters matter. This works because random search varies all parameters at once, so each plot averages over the others.
Refit and score the test set once
By default, GridSearchCV and RandomizedSearchCV refit the best setting on the whole training set (refit=True). Calling search.score(X_test, y_test) or search.predict(X_test) then uses that refit model.
If you choose a different setting by hand, for example by the one-standard-error rule, fit a new pipeline with those parameters on the training set and score that on the test set.
Score the test set one time. If you look at the result, change the search, and score again, the test set becomes part of the tuning data. The estimate is then optimistic in the same way as the best CV score. If you do need repeated looks, hold out a fresh set or use nested cross-validation.
Report uncertainty with the number
A single accuracy such as "0.965" invites more confidence than the data supports. A test set of 114 samples, as in the example above, has a sampling error of roughly 1.5 to 2 percentage points at this accuracy. Report one of these:
- The test score with a bootstrap or binomial confidence interval.
- The mean and standard deviation of outer scores from nested cross-validation.
- The test score and the CV score side by side, so readers see the gap.
When comparing two tuned models, a difference smaller than the interval is not evidence that one is better. Compare on the same folds and, where possible, use a paired comparison.
What to include in a report
A reader should be able to rerun your search and get the same table. Record the following:
| Item | Example |
|---|---|
| Data and split | 80/20 stratified split, `random_state=0` |
| Model and pipeline steps | `StandardScaler` then `SVC` |
| Search space with scales | `C` log-uniform 1e-2 to 1e2 |
| Search method and budget | random search, 30 trials, 5-fold CV |
| Metric used for selection | accuracy |
| Seeds | split seed, search seed, model seed |
| Library versions | scikit-learn, Optuna, Python |
| Selected setting and rule | one-standard-error rule, `C=1`, `gamma=0.01` |
| Validation result | mean 0.974, standard deviation 0.011 |
| Test result, scored once | 0.965, 95% interval 0.91 to 0.99 |
| Compute | total fit time, number of fits |
Also record what you rejected and why, for example "extended C upper bound after best value landed on the edge". Trial histories are cheap to save. Write cv_results_ to a CSV file, or for Optuna save study.trials_dataframe(), and store it with the report.
Common mistakes
- Reporting only the winner and omitting the number of trials. A best score from 500 trials means less than one from 5.
- Comparing a tuned model against an untuned baseline. Give the baseline the same tuning budget.
- Changing the search space after seeing test results.
- Leaving out the metric. "Best" is meaningless without the scoring rule.
- Treating a rank-1 row as unique when several rows share that rank.
Exercise
A random search with 200 trials reports bestscore = 0.951 on 5-fold CV. The single test-set score is 0.934 on 150 samples. A colleague says the model is overfit to the test set. Is that the right diagnosis, and what would you report?
Show answer
No. The test set was scored once, so it is not overfit by tuning. The gap is expected because bestscore is the maximum over 200 noisy scores, so it is biased upward, and the 150-sample test score also has a sampling error of about 2 percentage points. Report the test score (0.934) with a confidence interval as the performance estimate, give bestscore as the selection score, and state the number of trials, search space, metric, and seeds. For a stronger estimate, add nested cross-validation.
Exercise
In a grid search, the best C is 100, the largest value in your grid, and the second-best C is 10 with a score 0.002 lower and a fold standard deviation of 0.01. What two actions follow, and in what order?
Show answer
First, extend the grid upward (for example to 1000) and rerun, because the optimum may lie outside the range. Second, once the best value is inside the range, apply the one-standard-error rule. The scores for C=100 and C=10 differ by much less than the noise, so choose the simpler or cheaper setting, which is likely C=10 if it fits faster or regularizes more.