Coding Now – Best AI & Full Stack Courses in Delhi NCR | 100% Placement
Limited Offer: Get 50% OFF on AI & Full Stack Courses
📞 Call Now: +91 9667708830
Back to Machine Learning Notes
Topic #1704

K-Fold Cross-Validation

K-fold cross-validation is the standard way to run cross-validation: split the data into \(k\) equal parts ("folds"), and rotate which fold serves as the test set — every row gets used for testing exactly once, and for training \(k-1\) times.

Graphical Intuition

Fold 1 Fold 2 Fold 3 Fold 4 Fold 5 = test fold

Each row runs 5 times, using a different fifth of the data as its test set each time — the red block rotates position across all 5 runs.

Formula and Algorithm

StepWhat Happens
1Split the data into \(k\) roughly equal folds
2For each fold \(i\): train on all other \(k-1\) folds, test on fold \(i\), record the score
3Average the \(k\) recorded scores

Python Implementation

from sklearn.model_selection import KFold, cross_val_score
from sklearn.linear_model import LogisticRegression
import numpy as np

kf = KFold(n_splits=5, shuffle=True, random_state=42)

model = LogisticRegression(max_iter=1000)
scores = cross_val_score(model, X_train, y_train, cv=kf, scoring="accuracy")
print(scores)
print(f"Mean: {scores.mean():.3f}, Std: {scores.std():.3f}")

# Manually iterating over folds, for full control
for fold_num, (train_idx, test_idx) in enumerate(kf.split(X_train)):
    print(f"Fold {fold_num+1}: {len(train_idx)} train, {len(test_idx)} test rows")

Choosing k

k ValueTradeoff
Small (e.g. 3)Faster, but each fold's training set is smaller and test set larger — higher variance in per-fold scores
Common default (5 or 10)A reasonable, widely-used balance
Large (approaching \(n\), "leave-one-out")Uses almost all data for training each time, but very slow — trains the model \(n\) separate times

Practical Use Cases

  • The standard method for reliably comparing models and hyperparameter choices
  • Small-to-medium datasets, where a single held-out validation set would waste too much data

Common Mistakes

  • Not shuffling the data before splitting into folds, when the original row order isn't already random (e.g. sorted by date or class) — this can create wildly unrepresentative folds.
  • Using plain K-Fold on classification data with imbalanced classes instead of Stratified K-Fold.

Interview Relevance

Q: "Why does k-fold cross-validation use every row for both training and testing?" Rotating which fold serves as the test set means every row is tested on exactly once and trained on \(k-1\) times — this uses the full dataset for both purposes without ever testing on data the current model was trained on, maximizing data efficiency compared to a single fixed split.

Practice Question

With \(k=10\) on a dataset of 1000 rows, how many rows are in each fold's test set, and how many training runs does the full cross-validation process require?

Related ML Notes

Want to go beyond the notes?

Join CodingNow's Machine Learning course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available
💬 Talk to Advisor
1
WhatsApp

Latest from Our Blog

Insights on AI, Data Science, Full Stack & Career

View All Articles →