A single train/test split is noisy — you might get a lucky or unlucky test set. Cross-validation splits the data multiple ways, trains and tests on each, and averages — giving a far more trustworthy estimate of performance.
K-fold cross-validation
from sklearn.model_selection import cross_val_scorescores = cross_val_score(model, X, y, cv=5, scoring="accuracy")scores.mean(), scores.std() # average performance and its variability
With cv=5, the data is split into 5 folds; each fold is the test set once while the other four train. You get five scores — their mean is your estimate, their spread tells you how stable it is.
Key takeaways
- 01Cross-validation averages performance over multiple train/test splits for a reliable estimate.
- 02K-fold: each of k folds is the test set once; average the k scores.
- 03The score spread tells you how stable the estimate is.
- 04Pass a pipeline so preprocessing is re-fit per fold (no leakage); stratify for classification.
