
What Cross-Validation Is For: Estimating Performance, Not Picking a Fold's Model
- كاتب موثّق
- scikit-learn 1.9
محتويات المقال
return_estimator=True. One fold scores a perfect 1.000. They pickle that fold's model, and the model card reads "accuracy: 100% (cross-validated)". On the held-out test set the model scores 0.958, exactly what a plain model trained on all the data gets. The "winning" fold model was never special.
The common misconception
cross_validate(..., return_estimator=True)hands you k fitted models, and they look like candidates.Keeping the highest scorer looks like model selection, which is what cross-validation is famous for. The best fold's score is real: it was measured on rows that model never trained on.
What actually happens
It evaluates a recipe, not a model
cross_val_score returns an array of scores and nothing else. cross_validate can keep the fold estimators if you ask for them, which is useful for inspecting coefficients across folds, not for shipping.
Fold scores differ because the folds differ
from sklearn.datasets import load_breast_cancerfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import cross_validate, train_test_splitfrom sklearn.pipeline import make_pipelinefrom sklearn.preprocessing import StandardScalerX, y = load_breast_cancer(return_X_y=True)X_dev, X_te, y_dev, y_te = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)model = make_pipeline(StandardScaler(), LogisticRegression())cv = cross_validate(model, X_dev, y_dev, cv=5, return_estimator=True)best = cv["test_score"].argmax()deployed = cv["estimator"][best] # "the winning fold's model"print(f"fold scores {cv['test_score'].round(3)}")print(f"reported {cv['test_score'][best]:.3f}")print(f"test set {deployed.score(X_te, y_te):.3f}")# fold scores [0.953 0.976 0.965 0.976 1. ]# reported 1.000# test set 0.958from sklearn.datasets import load_breast_cancerfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import cross_val_score, train_test_splitfrom sklearn.pipeline import make_pipelinefrom sklearn.preprocessing import StandardScalerX, y = load_breast_cancer(return_X_y=True)X_dev, X_te, y_dev, y_te = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)model = make_pipeline(StandardScaler(), LogisticRegression())scores = cross_val_score(model, X_dev, y_dev, cv=5) # judges the recipeprint(f"CV estimate {scores.mean():.3f} +/- {scores.std():.3f}")final = model.fit(X_dev, y_dev) # the model you ship: all 426 dev rowsprint(f"test set {final.score(X_te, y_te):.3f}")# CV estimate 0.974 +/- 0.015# test set 0.958Refit on everything, then ship
GridSearchCV uses cross-validation to compare settings, then, with refit=True, its default, refits an estimator with the best parameters on the whole dataset you passed to fit. best_estimator_ is that refit model, not one of the fold models.
Report the spread, not just the mean
How to apply it in your project
Put the whole recipe in a pipeline Wrap preprocessing and the model in a Pipeline, so each fold fits the scaler and the model only on its own training part.Report mean and spread Run cross_val_scoreorcross_validateon the development data and report the mean with the standard deviation, not any single fold.Choose recipes, not fold models Use cross-validation results to compare settings, features or algorithms. Never pick among the fold models themselves. Refit the winner on all development data Call fiton the full development set, or letGridSearchCVrefit it, and ship that model.Confirm once on the test set Score the refit model on the held-out test set one time, and report that number alongside the CV estimate.
Key takeaways
Cross-validation estimates how a recipe performs on unseen data; it doesn't build your final model. Fold scores differ by the luck of the split: the 1.000 fold's model scored 0.958 on the test set. Report the mean and spread across all folds, 0.974 ± 0.015 here, never the best fold. Refit the chosen recipe on all your training data, then confirm it on the test set once.
التعليقات (0)