How Machines Learn Guide 5 of 6 · tap to switch
Cross-Validation & K-Fold Cross-Validation
How rotating every slice of your dataset through the exam seat turns lucky split roulette into a trustworthy score.
Would you write a five-star restaurant review after tasting one lucky dish on a quiet Tuesday? Probably not. You would taste across several different evenings before trusting your verdict.
Small machine learning datasets face the exact same luck problem. Suppose a clinic has 40 patients for a new blood-test classifier. If you take a single 80/20 split, 32 patients go into training and only 8 patients land in the validation exam. If 2 tricky borderline patients happen to fall inside those 8, your score plunges; if all 8 happen to be clear-cut cases, your score looks miraculous.
Click Try Another Random 80/20 Split below to watch the exact same model on the exact same 40 patients bounce wildly just from changing which 8 patients happen to land in the exam.
Notice how dangerous a single split is when rows are scarce: two engineers running the exact same code with different random shuffles could report 63% or 100% and walk away with completely opposite conclusions. We need a way to test the model across all 40 patients instead of gambling on one lucky draw.
Rotating the exam seat: K-fold cross-validation
Instead of trusting one lucky 20% slice, chop your dataset into K equal slices (say, 5 slices of 8 patients each) and let every slice take a turn in the exam seat. In machine learning, each slice is called a fold, and this rotating-exam technique is called K-fold cross-validation.
Here is how a 5-fold run works:
- In Round 1, Fold 1 sits in the validation exam while Folds 2, 3, 4, and 5 train the model.
- In Round 2, Fold 2 takes the exam while Folds 1, 3, 4, and 5 train a fresh copy of the model from scratch.
- Keep rotating until every single patient has been tested exactly once, without ever letting the model peek at the exam answers during training.
Switch between 3-Fold, 5-Fold, and 10-Fold below and click Run All Folds to watch the exam seat slide cleanly across all 40 patients.
Averaging all K rounds gives you two valuable numbers instead of one fragile guess: the mean score (your expected average performance) and the standard deviation (the spread showing how steady your model stays from slice to slice).
Bonus tip for uneven outcomes: If only 5% of patients have a rare illness, a plain shuffle might accidentally drop zero sick patients into one fold. Using balanced folds (officially called Stratified K-Fold) keeps the exact same healthy-to-sick ratio inside every slice.
When plain K-fold quietly leaks: groups and time series
Standard K-fold assumes every row is an independent stranger. In real-world projects, rows frequently travel in clusters or move forward along a calendar:
- Multiple rows per person or group: A hospital table often stores 4 MRI scans for each patient. Plain shuffled K-fold scatters the same patient’s scans into both Train and Validation, letting the model cheat by memorizing each person’s skull shape instead of learning the illness. Patient-grouped folds (officially Group K-Fold) lock all scans from the same person together on one side of the split.
- Time-ordered records: Shuffling quarterly sales lets future quarters sit in the training set while the model guesses earlier quarters. Forward-in-time splits (officially Walk-Forward cross-validation) keep every training window strictly in the past and every validation exam strictly in the future.
Inspect both leaks below (each tab starts in the broken setup!) and toggle to the safe fix to watch an inflated fake score turn into an honest one.
Choosing K: why 5 and 10 rule in practice
If rotating folds is helpful, how many folds should you pick? You could split your data into 2 big halves (2-Fold), 5 slices (5-Fold), 10 slices (10-Fold), or go all the way to K = n, where n simply means the total number of rows in your table. Setting K = n is called Leave-One-Out cross-validation: if your table has 1,000 rows, you run 1,000 rounds, holding out just 1 single row as the exam each time.
Why not always pick the smallest K to save time, or the biggest K to train on more rows?
- Too few folds (like 2-Fold): Each round trains on only 50% of your rows. Because the model learns from half a textbook, its cross-validation score looks slightly harsher (lower) than the score your final model will earn when retrained on 100% of the data.
- Too many folds (like Leave-One-Out): Training on every row except 1 removes that harshness, yet you pay for n full model trainings (painfully slow on large tables!) and the nearly identical training sets can actually make fold-to-fold scores noisier.
Do not confuse two meanings of “bias”: When people say 2-Fold has score-underestimation bias (pessimistic bias), they mean the validation score looks slightly weaker than the full model really is because each fold trained on fewer rows. That is completely separate from model bias (a stiff model, like forcing a straight line through curved data).
Click each option below to see how your data bar slices up, how harsh the score estimate becomes, and how many full model trainings you have to pay for.
See the formal CV estimator, bias-variance properties & Nested CVThesis / Reference
1. Formal K-fold CV risk estimator: Partition indices into disjoint folds . Let denote the model (and all preprocessing steps!) fitted strictly on . The K-fold cross-validation estimate is:
2. Bias and variance of the CV estimator (Kohavi, 1995; Hastie, Tibshirani & Friedman, ESL Ch. 7.10):
- Small (e.g., ) fits each model on only of the dataset, introducing pessimistic upward bias in estimated error when learning curves are still steep.
- Leave-One-Out CV () trains on rows (almost zero bias), yet the training sets overlap by , producing strongly positively correlated fold errors whose average can exhibit higher variance than or , at compute cost.
- Note for rigorous thesis reporting (Bates, Hastie & Tibshirani, 2024, JASA): naive fold standard errors underestimate true confidence interval width because folds share training data. Report both the fold mean/SD and, whenever possible, an untouched external test set.
3. Nested Cross-Validation (Varma & Simon, 2006): When a small dataset cannot spare a separate final test vault and you are tuning hyperparameters (like Ridge or tree depth), standard K-fold reports an optimistically biased winning score. Nested CV places an inner K-fold loop inside each outer training fold strictly to choose hyperparameters, then evaluates the winning pipeline once on the untouched outer fold.
See leak-free Stratified, Group & TimeSeries CV in PythonOptional Code
from sklearn.model_selection import StratifiedKFold, GroupKFold, TimeSeriesSplit, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
# CRITICAL: Put StandardScaler INSIDE the Pipeline so it refits cleanly inside every fold!
pipe = make_pipeline(StandardScaler(), LogisticRegression())
# 1. Classification with rare classes -> Stratified 5-Fold
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(pipe, X, y, cv=cv, scoring="accuracy")
print(f"5-Fold CV: {scores.mean():.3f} ± {scores.std():.3f}")
# 2. Multiple scans per patient -> GroupKFold(n_splits=5).split(X, y, groups=patient_ids)
# 3. Time-ordered data -> TimeSeriesSplit(n_splits=5)Three rules to keep cross-validation honest
- Preprocess fresh inside every fold: Never compute feature scaling stats (each column’s average and spread), missing-value fill-ins, or category encodings on the entire table before splitting, because that leaks information from the held-out validation slice into training. Bundle your data-prep steps with the model so each fold learns its scaling rules strictly from its own training slices, then applies those exact same numbers to its held-out validation slice.
- Pick the right fold rule for your data: Use balanced folds for classification when classes are uneven, patient-grouped folds whenever multiple rows share a person, customer, or store ID, and forward-in-time splits whenever rows follow a calendar timeline. (Open the optional code block above to see ready-to-run Python examples of all three.)
- Watch out when classes are rare: Even spotless 10-fold cross-validation can still report a deceptive 99% accuracy if 99% of your rows belong to one class. Next up in Imbalanced Data, we unpack why plain accuracy misleads on rare events and how to measure rare-class predictions honestly.
Quick Intuition Check
Four quick real-world scenarios. No scores, just test your intuition.
Why is 5-fold cross-validation much more trustworthy than a single 80/20 split on a 60-patient medical dataset?
You have 1,200 chest X-rays taken from 300 patients (4 scans per patient). Which fold rule prevents patient-identity leakage?
When running 5-fold cross-validation, where should you calculate feature scaling stats (each column's average and spread)?
Because 2-fold cross-validation only trains each model on 50% of the available data, it tends to underestimate how well your final model will perform when retrained on 100% of the data.
Common Questions
What is K-fold cross-validation in plain English?
Why is 5-fold or 10-fold cross-validation the standard choice?
Does cross-validation replace the final test set?
Can I use regular K-fold cross-validation on time-series data?
What is Group K-Fold and when do I need it?
Related Visual Guides
Train Test Split (Train, Validation & Test)
How to test a machine learning model honestly without letting it cheat, peek at the exam, or leak future data.
Precision, Recall, F1 Score & Imbalanced Data
Why 99% accuracy can hide a totally broken model, how Precision, Recall, F1, and PR curves expose the truth, and what fixes actually work.
Gradient Boosting (XGBoost & LightGBM)
Build a relay team of small trees where every new tree fixes the leftover mistakes of the previous ones, dominating real-world tabular ML.
Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference
Cite this guide in a paper, thesis, or course (BibTeX & APA)
@misc{irshad2026crossvalidation,
author = {Irshad, Muhammad Aashir},
title = {Cross-Validation & K-Fold Cross-Validation: Interactive Visual Guide},
howpublished = {SeeingML},
year = {2026},
month = {dec},
url = {https://seeingml.com/learn/cross-validation/},
note = {Interactive visual guide}
} Irshad, M. A. (2026). Cross-Validation & K-Fold Cross-Validation: Interactive Visual Guide. SeeingML. https://seeingml.com/learn/cross-validation/