Cross-Validation in Machine Learning: K-Fold, Stratified and Time Series Explained
On this page
Cross-validation is a way to estimate how well a machine learning model will perform on new data by testing it on several different slices of your dataset instead of just one. The most common form, k-fold cross-validation, splits the data into k equal parts (folds), trains the model k times, each time holding out a different fold for testing, and averages the k scores. The result is a more reliable performance estimate than a single train/test split, plus a measure of how much that performance varies.
Why one train/test split is not enough
With a single split, your score depends on which rows happen to land in the test set. To show this, we trained the same logistic regression model on scikit-learn’s breast cancer dataset (569 rows) three times, changing only the random seed of an 80/20 split:
| Split random seed | Test accuracy |
|---|---|
| 1 | 0.991 |
| 2 | 0.982 |
| 3 | 0.974 |
Same model, same data, and the reported accuracy moves by almost two percentage points. If you compared two models using one lucky or unlucky split, you could easily pick the wrong one. Cross-validation reduces this luck factor.
How k-fold cross-validation works
- Shuffle the data and split it into k folds of roughly equal size (k = 5 is a common choice).
- Train the model on k−1 folds and test it on the remaining fold.
- Repeat k times so every fold is used as the test fold exactly once.
- Report the mean score and the standard deviation across folds.
Every row is used for testing exactly once and for training k−1 times, so you make full use of a limited dataset.
A tested example with scikit-learn
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(model, X, y, cv=cv, scoring="accuracy")
print("fold scores:", scores.round(3))
print(f"mean {scores.mean():.3f} +/- {scores.std():.3f}")
When we ran this (scikit-learn 1.9), the five fold scores were 0.974, 0.947, 0.965, 0.991 and 0.991, giving a mean of 0.974 ± 0.017. That single line tells you far more than one split: the model is around 97% accurate, and on a different sample of data it could reasonably score anywhere from about 95% to 99%.
Types of cross-validation and when to use them
| Method | How it splits | Use it when | scikit-learn |
|---|---|---|---|
| K-fold | k random, equal folds | Regression and balanced data | KFold |
| Stratified k-fold | Each fold keeps the original class proportions | Classification, especially imbalanced classes (fraud, churn, disease) | StratifiedKFold |
| Group k-fold | All rows from the same group stay in the same fold | Several rows per customer, patient or student, so the model cannot memorise a person | GroupKFold |
| Leave-one-out (LOOCV) | Each single row is a test set once | Very small datasets; expensive on large ones | LeaveOneOut |
| Repeated k-fold | Runs k-fold several times with different shuffles | Small datasets where you want a steadier estimate | RepeatedStratifiedKFold |
| Time series split | Always trains on the past and tests on the future | Sales forecasting, stock and sensor data | TimeSeriesSplit |
For time-ordered data, never shuffle: training on next month to predict last month leaks the future into the model and gives a falsely high score. Our guide to time series forecasting covers this in more detail.
The most common mistake: data leakage
If you scale, impute or select features on the whole dataset before cross-validation, information from the test folds leaks into training and your scores look better than reality. The fix is to put every preprocessing step inside a Pipeline, as in the example above. scikit-learn then fits the scaler (or imputer, or feature selector) on the training folds only, every time.
- Wrong:
X_scaled = StandardScaler().fit_transform(X), thencross_val_score(model, X_scaled, y). - Right:
cross_val_score(make_pipeline(StandardScaler(), model), X, y).
Cross-validation, hyperparameter tuning and the test set
Cross-validation is also the engine behind hyperparameter tuning: GridSearchCV and RandomizedSearchCV score every combination with cross-validation. The safe workflow is:
- Split off a final test set and do not touch it.
- Use cross-validation on the training set to compare models and tune hyperparameters.
- Retrain the chosen model on the full training set.
- Evaluate once on the test set and report that number.
If you tune many models on the same folds, the best cross-validation score becomes slightly optimistic. For research-grade estimates, nested cross-validation (an inner loop for tuning and an outer loop for scoring) removes that bias.
How many folds should you use?
- 5 or 10 folds are the standard choices and work well for most datasets.
- Small datasets (a few hundred rows): 10 folds or repeated k-fold give steadier estimates.
- Large datasets or slow models (deep learning): 3 folds, or a single validation set, keep training time manageable.
- More folds means more training runs, so the cost grows with k.
Frequently asked questions
Does cross-validation improve model accuracy?
No. It does not change the model; it gives a more trustworthy estimate of its accuracy and helps you choose between models and settings fairly.
What is the difference between cross-validation and a validation set?
A validation set is one fixed held-out slice. Cross-validation rotates the held-out slice across the whole dataset and averages the results, which is more reliable but takes longer.
Should I use the cross-validation score or the test score in my report?
Use cross-validation to choose your model, then report the score on the untouched test set as your final estimate. Mention the cross-validation mean and standard deviation as supporting evidence.
Why is my cross-validation score much higher than my test score?
Common causes are data leakage (preprocessing outside a pipeline), duplicate rows across folds, shuffling time-ordered data, or over-tuning to the folds. See overfitting vs underfitting for related symptoms.
Related reading
- Hyperparameter tuning: grid search vs random search
- How to evaluate a machine learning model
- Overfitting vs underfitting
- Feature engineering explained
- Logistic regression explained
- KNN algorithm explained: choosing k with cross-validation
Want to practise building, validating and tuning models on real datasets with guidance? See our Machine Learning course or the complete Data Science course.
A note from Mehul Prajapati
I have spent 18+ years in IT and training and have personally mentored 12,000+ students. If you are planning your next step in machine learning and want a second opinion on your learning path, I am happy to help.
“The technology you learn today may change tomorrow, but your ability to learn will always be your biggest strength. Stay curious, keep upgrading yourself, and never stop growing.”
Message me on WhatsApp at +91 99301 12627 and tell me which blog you read. I would love to hear from you.
Learn with Mehul Prajapati in Borivali West
At Mehul Prajapati’s institute, you get 100% practical, hands-on training by industry experts with a minimum of 5+ years of experience, plus job-oriented programmes with placement support and placement assistance on the Machine Learning course. Weekday and weekend batches are available, with multiple 2-hour slots between 8 am and 6 pm.
Address: 12th Floor, 1214, Gold Crest Business Centre, LT Rd, Above Westside Showroom, Borivali West, Mumbai, Maharashtra 400092
Call: +91 99301 12627 / +91 96645 45072
Visit the centre or call us to choose the right course and batch and to know the current fee structure.