Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 110/ 160
06. Feature Engineering & Model Evaluation

K-Fold & Stratified Cross-Validation

Estimate generalization with K-fold and preserve class ratios via stratification.

BeginnerK-Fold · Stratified3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Split your data into parts, practise on all but one, test on the one you left out, and repeat so every part gets a turn; the average score is a fairer estimate.

Think of it like…

Taking five different practice exams from five different parts of the syllabus and averaging the marks, rather than trusting one exam that happened to cover your favourite chapter.

Where you’ve seen it

A dataset has n = 1,000 rows with 100 positives (10%). 5-fold CV gives 200 validation rows and 800 training rows per fold. With plain random folds the number of positives per fold varies: the standard deviation is about √(200 × 0.1 × 0.9 × 800/999) ≈ 3.8, so folds range from roughly 12 to 28 positives (about ±7 at 95%), making metrics like recall noisy; stratification forces exactly 20 positives per fold. Fold AUCs are 0.82, 0.85, 0.80, 0.84 and 0.83: mean 0.828, sample standard deviation 0.019 and a naive standard error of 0.019/√5 = 0.0086 (optimistic because folds overlap in training data). The team reports 0.828 ± 0.019 and compares two models with the same folds (paired differences), finding model B better by 0.012 ± 0.004 in each fold. For hyperparameter tuning they use nested CV: the inner 3-fold search picks parameters inside each outer training set, and the outer 5 folds give an unbiased estimate (0.821 versus 0.837 for the optimistic non-nested tuned score).

Words you’ll hear

K-fold
Partition into K folds; train on K − 1 and validate on 1, rotating.
Stratified K-fold
Folds that preserve the class proportions of the whole dataset.
Repeated CV
Repeating K-fold with different shuffles to reduce variance.
Nested CV
An inner loop for tuning inside an outer loop for evaluation.

Visual diagram

Loading interactive diagram

Theory & deep dive

How K-fold works and how to choose K

KFold(n_splits=5, shuffle=True, random_state=42) partitions row indices into K folds; each iteration trains on K − 1 folds and scores on the remaining one. The CV estimate is the mean of the K scores; the spread (standard deviation across folds) shows how stable performance is. Stratified K-fold (StratifiedKFold, the default for classifiers in cross_val_score) keeps class proportions: with 100 positives in 1,000 rows, each of 5 folds has exactly 20, whereas random folds vary (SD ≈ 3.8 positives per fold, so some have only 12), which makes recall and precision per fold noisy. For regression with skewed targets, stratify on target quantile bins.

Choosing K trades bias against variance and cost. Small K (2 to 3) trains on much less data than the final model (pessimistic bias); large K (10, or leave-one-out) has less bias but costs K fits, and estimates from highly overlapping training sets are strongly correlated (high variance of the CV estimate in some settings). K = 5 or 10 is the standard compromise. For small datasets use repeated K-fold (for example 5 × 3 repeats) to average over splits. Always shuffle unless the data is time ordered (then use time-series splits), and set a random seed for reproducibility.

Mean and spread

Fold AUCs 0.82, 0.85, 0.80, 0.84, 0.83: mean 0.828. Deviations −0.008, 0.022, −0.028, 0.012, 0.002; squares sum to 0.00148; sample variance 0.00148/4 = 0.00037; SD = 0.019; naive SE = 0.019/√5 = 0.0086.

Key takeaway: K-fold averages performance over rotating validation folds; stratify for classes, choose K around 5–10 and report the spread.

Correct use: pipelines, groups, nesting and uncertainty

Leakage control: everything learned from data (imputation, scaling, encoding, selection, resampling) must be fitted inside each training fold via a Pipeline; otherwise the validation folds influence preprocessing. Group structure: if rows from the same customer, patient or device appear in several folds, use GroupKFold or StratifiedGroupKFold so entities stay together; otherwise the model memorises them. Time order requires time-series splits (see that lesson). Hyperparameter tuning with CV and then reporting the best CV score is optimistic because you selected the maximum over noisy estimates; use nested CV (an inner 3-fold search for parameters inside each outer training set; outer 5 folds estimate performance) or a final untouched test set. In the example, non-nested tuned AUC 0.837 drops to 0.821 under nested CV.

Interpret CV scores with care: the fold scores aren't independent (training sets overlap), so the naive standard error (SD/√K) understates uncertainty; use repeated CV and paired comparisons (compare two models on the same folds and look at the per-fold differences) rather than overlapping intervals. Report mean ± SD and the metric used; check that the CV estimate matches a held-out test set within noise (a big gap indicates leakage or distribution shift). Remember CV measures performance on data like the training data; if production differs (new customers, a new period), design the split to mimic that shift. Use cross_validate to collect multiple metrics, fit times and train scores in one pass, and cross_val_predict for out-of-fold predictions used in calibration, stacking and error analysis.

Paired comparison

Model A folds: 0.82, 0.85, 0.80, 0.84, 0.83. Model B: 0.83, 0.86, 0.81, 0.85, 0.85. Differences: +0.01, +0.01, +0.01, +0.01, +0.02: mean +0.012, SD 0.004. B is consistently better, which a comparison of overlapping ±0.019 intervals would miss.

Key takeaway: Keep preprocessing in the pipeline, respect groups and time, nest tuning loops and compare models on identical folds.

How it works, step by step

Step 1 of 4
Analyst

1. Choose the splitter

Use StratifiedKFold for classification, GroupKFold for grouped rows and time-series splits for temporal data.

StratifiedKFold(5, shuffle=True)
Key numbers at this step
Seed
for reproducibility

When to use it & trade-offs

What it is

K-fold cross-validation estimates how well a model generalises by splitting the data into K equal folds, training on K − 1 folds and validating on the held-out fold, rotating until every fold has been the validation set once; the K scores are averaged. Stratified K-fold preserves the class proportions in every fold, which matters for imbalanced classification. Variants include repeated K-fold (different shuffles), leave-one-out, GroupKFold (keep related rows together) and nested CV (an outer loop for evaluation, an inner loop for tuning). CV uses data efficiently and gives a mean and a spread, but it's valid only when preprocessing happens inside each fold and when rows are exchangeable (no time ordering or grouping that leaks).

Why it matters: A single train/validation split can be lucky or unlucky, especially on small data: the estimate depends on which rows landed in validation. Cross-validation averages that noise away and reveals the variability of performance, which is essential for comparing models and judging whether a difference is real. Done wrongly (leaky preprocessing, random folds on grouped data), it produces confident, wrong numbers.

When to reach for it

  • Estimating generalisation on small and medium datasets
  • Model selection and hyperparameter tuning
  • Comparing models with paired folds

When to avoid or be careful

  • Preprocessing on the full data before CV
  • Reporting the best CV score from tuning as a performance estimate
  • Random folds on grouped or time-ordered data

Validation schemes

Stratified K-fold
Best for: Standard classification with independent rows

Strengths: Stable class ratios; uses all data.

Watch out: Invalid with groups or time order.

Group or time-aware CV
Best for: Grouped or temporal data

Strengths: Matches deployment; prevents leakage.

Watch out: Uneven folds; fewer training rows.

Single holdout split
Best for: Very large datasets

Strengths: Fast and simple.

Watch out: High variance on small data.

Interview signals & numbers to know

When this topic comes up

  • “CV score is higher than the test score”
  • StratifiedKFold
  • GroupKFold
  • Nested cross-validation
  • Paired comparison of models

Benchmarks & rules of thumb

≈ 3.8 -
SD of positives per random 200-row fold at 10% prevalence
0.828 ± 0.019 -
mean and SD of the five fold AUCs
0.821 vs 0.837 -
nested versus non-nested tuned AUC

Common mistakes & follow-ups

Common interview mistakes

  • Using the SD/√K standard error as if folds were independent.
  • Shuffling time-ordered data.
  • Selecting features before CV.

Likely interviewer follow-ups

  • Why stratify folds?
  • What is nested cross-validation and why use it?
  • How do you choose K?
Interview tip: Mention paired per-fold differences when comparing models. They are far more sensitive than comparing overlapping intervals.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply K-Fold & Stratified Cross-Validation with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Handling Imbalanced Datasets (SMOTE, Class Weights)
Next topic
Time-Series Split Validation