الانتقال إلى المحتوى
Machine Learningتقييم الموديلات· 7 دقائق للقراءة

Your Tuned CV Score Is Optimistic: Nested Cross-Validation Explained

best_score_ is the score of the luckiest of many candidates. Nested cross-validation puts the whole search inside an outer loop and scores it on rows it never saw.

ReadIn

مقال كل يوم يفرق معاك

22 نوفمبر 2026
  • كاتب موثّق
  • scikit-learn 1.9
محتويات المقال

A team has 200 labeled rows and tunes a decision tree with GridSearchCV: 20 settings, 5 folds each. The pipeline is clean, nothing leaks, and best_score_ reads 0.790, so the model card promises 79% accuracy. There's no test set, because 200 rows felt too few to split. On new data, the shipped model gets 0.758. Nothing broke; the 0.790 was never an estimate of the shipped model's accuracy.

The common misconception

Many developers treat best_score_ as an unbiased estimate of how the tuned model will perform on new data. It's an easy belief to hold:

  • It's a cross-validated score: every candidate was scored only on rows it didn't train on.
  • The API reference defines it as the mean cross-validated score of the best estimator, which sounds like exactly the number you want to report.
  • Cross-validation is the method you were told to trust over a single validation split.

The half-truth: each candidate's cross-validated score is a fair estimate for that candidate, as long as you don't choose among them. The moment the search keeps the maximum of 20 noisy scores, the winner's score is no longer fair: the folds that measured it are the folds that chose it.

What actually happens

A grid search does two jobs with one set of folds: it selects the settings, and it reports how well they did. The second number inherits a bias from the first.

Tuning trains on the validation folds

scikit-learn's grid search guide describes model selection as a way of using the labeled data to "train" the parameters of the grid. The inner folds aren't just measuring the ; they're fitting them. The nested CV example in the scikit-learn gallery says the consequence directly: choosing the parameters that maximize non-nested CV biases the model to the dataset and yields an overly optimistic score. This is the same effect as picking the best of many models on a test set, covered earlier in this path, except that it lives inside GridSearchCV, where it's easy to forget.

How big the bias gets

The same example says the size of the effect depends mainly on the size of the dataset and the stability of the model. On iris, with 6 candidates for an SVM, it measures an average gap of 0.0076 between non-nested and nested scores over 30 trials: small. Small datasets, unstable models such as deep trees, and large grids push it up. Cawley and Talbot found that the loss from over-fitting the model selection criterion can be surprisingly large, comparable to the differences between learning algorithms, so it can't be ignored when you compare them.

Nested CV: a search inside each fold

gives each job its own loop. The outer loop splits the data into training and test parts. On each outer training part, the full grid search runs with its own inner folds, picks a setting and refits on that whole part. The outer test part, which the search never touched, scores the result. The average over outer folds estimates the performance of the procedure "tune with this grid, then fit". In scikit-learn it's one line: pass the search object to cross_val_score or cross_validate.

Python
from sklearn.datasets import make_classificationfrom sklearn.model_selection import GridSearchCV, StratifiedKFoldfrom sklearn.tree import DecisionTreeClassifierX, y = make_classification(n_samples=5200, n_features=20, n_informative=4,                           flip_y=0.1, random_state=1)X_dev, y_dev = X[:200], y[:200]  # the labeled rows you haveX_new, y_new = X[200:], y[200:]  # stands in for production trafficgrid = {"max_depth": range(1, 11), "min_samples_leaf": [1, 10]}inner = StratifiedKFold(5, shuffle=True, random_state=0)search = GridSearchCV(DecisionTreeClassifier(random_state=0), grid, cv=inner)search.fit(X_dev, y_dev)  # 20 candidates x 5 foldsprint(f"best_score_ {search.best_score_:.3f}")  # goes into the model cardprint(f"new data    {search.score(X_new, y_new):.3f}")# best_score_ 0.790# new data    0.758

The 5,000 extra rows play production, something you rarely have. best_score_ promised 0.790; new data gave 0.758. Nested CV, using only the 200 development rows, estimated 0.765, within a point. One run proves little, so the same script ran on eight datasets drawn the same way (random_state 0 to 7): best_score_ overstated new-data accuracy by 2.3 points on average, nested CV by 0.7.

What nested CV gives you, and what it doesn't

It gives you no model and no single best setting. Every outer search here picked a depth of 2, while the search on all 200 rows picked a depth of 4. That's expected: the outer searches see 160 rows each, and their choices tell you how stable the tuning is. The model you ship is the search refit on all the data, refit=True by default, and nested CV is the estimate of how that procedure performs.

The outer scores also show the spread: from 0.60 to 0.875 across the five outer folds. With 40 rows per outer test fold, that's the honest uncertainty of any number you report from 200 rows.

MythReality
best_score_ is an unbiased estimateIt's the maximum of 20 noisy estimates, judged by the folds that chose it: 0.790 against 0.758
Cross-validation already protects youIt protects each candidate's score, not the winner's after selection
Nested CV finds the best hyperparametersIt evaluates the tuning procedure; the outer folds may pick different settings
Comparing algorithms by best_score_ is fairBigger grids get more optimism; compare nested scores instead
The bias is always bigIt depends on data size, model stability and grid size: 0.0076 on iris

How to apply it in your project

  1. Put the whole recipe in the searchWrap preprocessing and the model in a Pipeline, and tune the pipeline, so every inner fold refits everything.
  2. Wrap the search in an outer loopPass the GridSearchCV or RandomizedSearchCV object to cross_validate with a separate outer splitter.
  3. Report the nested score, not best_score_Put the nested mean and the spread of the outer folds in the model card. Use best_score_ only to pick.
  4. Ship the refit searchFit the search once on all your data and deploy best_estimator_; the nested score describes it.
  5. Budget the fitsNested CV costs outer folds × inner folds × candidates: 5 × 5 × 20 = 500 fits here, before the final search. With plenty of data, a single held-out test set does the same job far more cheaply.

Key takeaways

  • best_score_ is measured on the folds that chose the winner, so it's optimistic: 0.790 against 0.758 on new data.
  • Nested CV runs the search inside each outer fold and scores it on rows the search never saw.
  • It estimates the tuning procedure, not one setting; ship the search refit on all the data.
  • The bias grows with smaller data, unstable models and bigger grids; compare algorithms by nested scores.

📚 المصادر

  1. Nested versus non-nested cross-validation — scikit-learn examples
  2. Tuning the hyper-parameters of an estimator — scikit-learn User Guide
  3. GridSearchCV — scikit-learn API Reference
  4. Cross-validation: evaluating estimator performance — scikit-learn User Guide
  5. Cawley and Talbot, On Over-fitting in Model Selection and Subsequent Selection Bias in Performance Evaluation (JMLR 2010)

التعليقات (0)