
Your Tuned CV Score Is Optimistic: Nested Cross-Validation Explained
- كاتب موثّق
- scikit-learn 1.9
محتويات المقال
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
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.
What actually happens
Tuning trains on the validation folds
GridSearchCV, where it's easy to forget.
How big the bias gets
Nested CV: a search inside each fold
cross_val_score or cross_validate.
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.758from sklearn.datasets import make_classificationfrom sklearn.model_selection import GridSearchCV, StratifiedKFold, cross_validatefrom 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]X_new, y_new = X[200:], y[200:]grid = {"max_depth": range(1, 11), "min_samples_leaf": [1, 10]}inner = StratifiedKFold(5, shuffle=True, random_state=0)outer = StratifiedKFold(5, shuffle=True, random_state=1)search = GridSearchCV(DecisionTreeClassifier(random_state=0), grid, cv=inner)nested = cross_validate(search, X_dev, y_dev, cv=outer, return_estimator=True)print(f"nested CV {nested['test_score'].mean():.3f}") # the number to reportprint([tuple(s.best_params_.values()) for s in nested["estimator"]])final = search.fit(X_dev, y_dev) # the model you ship: all 200 rowsprint(f"new data {final.score(X_new, y_new):.3f}")# nested CV 0.765# [(2, 1), (2, 10), (2, 1), (2, 10), (2, 1)]# new data 0.758best_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
refit=True by default, and nested CV is the estimate of how that procedure performs.
best_score_ is an unbiased estimate | |
best_score_ is fair | |
How to apply it in your project
Put the whole recipe in the search Wrap preprocessing and the model in a Pipeline, and tune the pipeline, so every inner fold refits everything.Wrap the search in an outer loop Pass the GridSearchCVorRandomizedSearchCVobject tocross_validatewith a separate outer splitter.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.Ship the refit search Fit the search once on all your data and deploy best_estimator_; the nested score describes it.Budget the fits Nested 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.
📚 المصادر
Nested versus non-nested cross-validation — scikit-learn examples Tuning the hyper-parameters of an estimator — scikit-learn User Guide GridSearchCV — scikit-learn API Reference Cross-validation: evaluating estimator performance — scikit-learn User Guide Cawley and Talbot, On Over-fitting in Model Selection and Subsequent Selection Bias in Performance Evaluation (JMLR 2010)
التعليقات (0)