SeeingML
How Machines Learn Guide 5 of 6 · tap to switch
✦ Interactive Visual Guide 8 min · 4 hands-on labs · Beginner friendly

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.

Interactive Lab 1: Lucky Split Roulette (40 Clinical Patients)
Spread so far: 75% to 75%
Purple dot: close to average (within 10 pts)Red dot: big luck swing (10+ pts off)Stable average across all patients (explained next): 70%
Validation Score (%)Stable average across all patients (explained next): 70%55%70%85%100%#1#2#3#4#5#6#7#8#9#10#11#12Different Random 80/20 Splits of the Exact Same Model (32 Train, 8 Exam)75%
Try clicking several splits in a row to feel how luck changes the reported accuracy:
Split #1 tested 8 random patients and scored 75% (stable average is 70%). Click "Try Another Random 80/20 Split" to watch the exact same model's score swing when a different 8 patients take 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.

Interactive Lab 2: Step Through K-Fold Cross-Validation
Click any round below to see which slice takes the exam:
Train (80%)Validation Exam (20%)
Tested: 8/40Round 1: 88%Running Avg: 87.5%
Round 1 of 5: Fold 1 (8 unseen patients) takes the exam and scores 88%, while the other 4 folds (32 patients) train a fresh copy of the model. 8 of 40 patients tested so far.

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).

✓ Tip

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:

  1. 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.
  2. 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.

Interactive Lab 3: When Plain K-Fold Leaks (Groups & Time Series)
Reported score: 96% (Patient Leak!)
A#1 = Patient A, Scan 1 (each color is one person with 4 MRI scans)
ABCDEF
Training Fold (18 MRI scans)
A#1
A#2
A#3
B#1
B#2
B#3
C#1
C#2
C#3
D#1
D#2
D#3
E#1
E#2
E#3
F#1
F#2
F#3
Validation Fold (6 scans)Leaked: 6/6
A#4
B#4
C#4
D#4
E#4
F#4
Every color here also sits in Training on the left!
Hidden patient leak! Standard K-Fold put 3 scans of every patient in Train and their 4th scan in Validation (6 of 6 patients leaked). The model recognizes each person's skull shape and reports a fake 96% score!

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.
💡 Insight

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.

Interactive Lab 4: Choosing K (Accuracy vs. Compute Cost)
Models trained: 5 models
How 1 round slices a 40-row table (5-Fold (Default)):
TrainValidation Exam
5 equal slices: 32 rows train (80%), 8 rows take the exam each round.
Training Data Available per Round (Higher is closer to full model)80% of rows
Score Looks Slightly Too Harsh (Lower is more accurate)Low
Compute Time & Cost (Lower is faster)5 models
The industry workhorse. Each round trains on 80% of your rows, keeping the score estimate honest and steady while only paying for 5 model trainings.
See the formal CV estimator, bias-variance properties & Nested CVThesis / Reference

1. Formal K-fold CV risk estimator: Partition indices {1,…,n}\{1, \dots, n\} into KK disjoint folds V1,…,VKV_1, \dots, V_K. Let f^(−k)\hat{f}^{(-k)} denote the model (and all preprocessing steps!) fitted strictly on S∖VkS \setminus V_k. The K-fold cross-validation estimate is:

CV^K=1K∑k=1K1∣Vk∣∑i∈Vkℓ ⁣(f^(−k)(xi), yi)\widehat{\text{CV}}_K = \frac{1}{K} \sum_{k=1}^{K} \frac{1}{|V_k|} \sum_{i \in V_k} \ell\!\left(\hat{f}^{(-k)}(x_i),\, y_i\right)

2. Bias and variance of the CV estimator (Kohavi, 1995; Hastie, Tibshirani & Friedman, ESL Ch. 7.10):

  • Small KK (e.g., K=2K=2) fits each model on only K−1Kn=50%\frac{K-1}{K}n = 50\% of the dataset, introducing pessimistic upward bias in estimated error when learning curves are still steep.
  • Leave-One-Out CV (K=nK=n) trains on n−1n-1 rows (almost zero bias), yet the nn training sets overlap by (n−2)/n(n-2)/n, producing strongly positively correlated fold errors whose average can exhibit higher variance than K=5K=5 or 1010, at n×n\times compute cost.
  • Note for rigorous thesis reporting (Bates, Hastie & Tibshirani, 2024, JASA): naive fold standard errors s/Ks/\sqrt{K} 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 λ\lambda 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
python
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

  1. 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.
  2. 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.)
  3. 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.
✓ Self-Check

Quick Intuition Check

Four quick real-world scenarios. No scores, just test your intuition.

1

Why is 5-fold cross-validation much more trustworthy than a single 80/20 split on a 60-patient medical dataset?

Pick an option first, or peek anytime
2

You have 1,200 chest X-rays taken from 300 patients (4 scans per patient). Which fold rule prevents patient-identity leakage?

Pick an option first, or peek anytime
3

When running 5-fold cross-validation, where should you calculate feature scaling stats (each column's average and spread)?

Pick an option first, or peek anytime
4

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.

Pick an option first, or peek anytime
Quick Reference

Common Questions

What is K-fold cross-validation in plain English?
K-fold cross-validation splits your training dataset into K equal chunks (folds). It trains the model K separate times, each time holding out a different chunk as the validation exam, then averages the K scores into one much more reliable grade.
Why is 5-fold or 10-fold cross-validation the standard choice?
Five and ten folds hit the sweet spot: each round trains on 80% to 90% of the data (keeping training-size bias low), averages out lucky splits cleanly, and stays fast enough for everyday model tuning.
Does cross-validation replace the final test set?
No. Cross-validation replaces a single validation split while you compare models and tune settings. You still keep a sealed Test Vault untouched until all tuning is finished, or use Nested Cross-Validation when data is too small for a separate holdout.
Can I use regular K-fold cross-validation on time-series data?
No. Shuffling time-ordered rows lets future months leak into past training folds. Always use chronological walk-forward validation (TimeSeriesSplit), where every training window stays strictly earlier than its validation window.
What is Group K-Fold and when do I need it?
Group K-Fold ensures that all records belonging to the same underlying entity (such as multiple MRI scans from one patient or multiple sessions from one user) stay together in either Train or Validation, preventing the model from memorizing individual identities.

Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference

https://seeingml.com/learn/cross-validation/ Open GitHub issue Suggest an edit
Cite this guide in a paper, thesis, or course (BibTeX & APA)
BibTeX
@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}
}
APA

Irshad, M. A. (2026). Cross-Validation & K-Fold Cross-Validation: Interactive Visual Guide. SeeingML. https://seeingml.com/learn/cross-validation/