# What Is Cross-Validation?

> How cross-validation tests a model on every slice of your data, how to read the spread of its scores, and the leakage trap, for your AI interview.

**In short:** Cross-validation tests a model on several different slices of the data, then averages the scores. Each slice takes a turn as the unseen test set, so the final number does not depend on one lucky split.

AI and LLM interview question Q423, Classic ML and deep-learning basics. Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/what-is-cross-validation

## Say it in 30 seconds

Cross-validation is how I check a model without trusting one lucky test. I cut the data into five folds, train on four, test on the fifth, and rotate until every fold has been the test once. Then I average the scores and look at the spread. A wide spread means the model is unsteady. The big trap is leakage: any step, like scaling, that learns from test rows makes the score look better than it is. So I put the scaler inside a pipeline, and cross-validation refits it on each training fold.

## Say it in 2 minutes

Imagine a lender with 10,000 past loan applications and a model that flags likely defaults. I lock 2,000 of them away for a final check, and cross-validate on the other 8,000. If I test it on one random 20 percent, the score depends on which loans happened to land in that slice. Cross-validation fixes that. I cut the data into five equal folds, then run five rounds. In each round the model trains on four folds and is scored on the fold it has never seen. Every loan in those 8,000 gets tested exactly once.

The five scores go into an average, and I also look at the spread. Say the recall sits between 0.78 and 0.84. The average tells me the likely level, and the spread gives me a rough idea of how steady it is. A wide spread is a warning that the model is unsteady or the data is mixed. For data with a time order, such as sales by week, I would not shuffle. I would train on the past and test on the next period, because shuffling lets the model peek at the future.

The mistake I watch for most is data leakage. Suppose I scale all 8,000 loans before cutting the folds. Then every test fold has already shaped the numbers the model learns from, and the score comes out overly optimistic. The fix is to put the scaler and the model in one pipeline, so cross-validation refits both on each training fold.

Last, the final test set. I keep the 2,000 locked away, out of all of this, and use them once at the end to report the honest number. Cross-validation is for choosing and comparing models, and the final slice is for telling the truth about the one I picked.

## What is cross-validation, in plain words?

Cross-validation is a fair way to test a model. You cut your past data into equal slices, called folds. Then you take turns: train the model on all the folds but one, test it on the fold you left out, and repeat until every fold has had a turn as the test. The final score is the average of those tests.

Why bother? One test set can flatter a model, or punish it, purely because of which rows landed in it. Cross-validation gives a score from several different tests, and every row gets tested once.

Picture a loan officer who wants to know whether a new rule would have caught bad loans. She checks the rule against five boxes of old files, one box at a time. Each time she sets one box aside, learns only from the other four, and tests on the box she set aside. She never trusts a single box.

The AI version: a lender has 10,000 past loan applications with known outcomes. It locks 2,000 away as a final check, and cross-validates a model that flags likely defaults on the other 8,000.

- **Fold:** One equal slice of the data. Five folds means five slices.
- **Held-out fold:** The one fold scored in a round, and never trained on in that round.
- **Final test set:** Rows locked away until the very end, used once to report the honest number.
- **Overfitting:** A model that memorises its training rows and then fails on new ones.
- **Data leakage:** Information from the test rows getting into training, so the score looks better than it is.

## How does k-fold cross-validation work?

The most common form is k-fold, where k is the number of folds. The steps are the same for any k.

1. **Shuffle and cut:** Shuffle the rows once, then cut the data into k equal folds. With the 8,000 loans to cross-validate and k set to 5, each fold holds 1,600 loans.
2. **Train and test, once per fold:** For each fold, train on the other four folds, which is 6,400 loans, then score the model on the fold left out.
3. **Average and report the spread:** Average the five scores. Keep the spread too, so you know how steady the result is.

*Diagram, Five rounds, one honest score: Five rounds, each with a different fold held out. The model learns from four folds and is scored on the fifth. The final number is the average of the five scores, shown with its spread.*
1. Shuffle once, then cut the rows into five equal folds.
2. Four folds go in to teach the model.
3. The model is scored on the fold it never saw.
4. Each round's score goes into the average.

Here is a made-up run for a lender's default model. Defaults are rare, so the team uses stratified folds, which keep about the same default share in every fold. Each round is scored on recall: the share of real defaults the model catches.

- **Round 1:** Tested on 1,600 loans it never saw. Recall 0.81.
- **Round 2:** A different 1,600 loans. Recall 0.79.
- **Round 3 to 5:** Recalls of 0.84, 0.80 and 0.78.
- **The result:** Average about 0.80, with rounds between 0.78 and 0.84. Stratified folds can make that spread look tighter than it really is, so treat 0.80 as an estimate that can still move.

To see the rotation in code, here is a simplified 4-fold run on 12 loans. The code trains no model. It shows the folds and the rounds, and its assert line checks that no round trains on its own test loans.

```python
# A simplified 4-fold split of 12 past loan applications. Seeded, so every run prints the same thing.
import random

applications = [f"loan-{i:02d}" for i in range(1, 13)]
random.Random(7).shuffle(applications)  # shuffle once, before cutting the folds
k = 4
folds = [applications[i::k] for i in range(k)]

for n in range(k):
    train = [a for i, fold in enumerate(folds) if i != n for a in fold]
    assert not set(train) & set(folds[n]), "a test loan was in training"
    print(f"round {n + 1}: test {sorted(folds[n])}, trains on {len(train)} loans")

tested = [a for fold in folds for a in fold]
print("every loan tested exactly once:", sorted(tested) == sorted(applications))
```

Output:

```text
round 1: test ['loan-01', 'loan-08', 'loan-09'], trains on 9 loans
round 2: test ['loan-05', 'loan-07', 'loan-12'], trains on 9 loans
round 3: test ['loan-03', 'loan-04', 'loan-10'], trains on 9 loans
round 4: test ['loan-02', 'loan-06', 'loan-11'], trains on 9 loans
every loan tested exactly once: True
```

## Why not use one train and test split?

A single split is quick, but the scikit-learn guide warns that results can depend on one random choice. Cross-validation spreads that luck across several rounds.

*Diagram, One split or five honest tests: One train and test split gives one score, and that score can be lucky or unlucky. Cross-validation tests every row once and reports the average with its spread.*
1. One split can flatter or punish the model by luck.
2. Five folds give five scores that you can average.

> "The performance measure reported by k-fold cross-validation is then the average of the values computed in the loop." (scikit-learn)
>
> "the results can depend on a particular random choice for the pair of (train, validation) sets" (scikit-learn)

The cost is time. Five folds means five training runs, so a slow model takes about five times as long. The scikit-learn guide says it can be computationally expensive, but that it does not waste too much data.

## Which kinds of cross-validation are there?

- **Plain k-fold:** The default. Shuffle the rows, cut the folds, and rotate. It assumes each row is independent of the others, so repeated customers or the same patient in many rows break that.
- **Stratified k-fold:** Each fold keeps roughly the same mix of outcomes as the full data. Useful when some outcomes are rare, such as confirmed fraud.
- **Group k-fold:** All rows from one customer, patient or store stay in the same fold, so the model is tested on people or places it has never seen.
- **Time series split:** For data with a time order, the model trains on the past and is tested on the period that comes next. Shuffling would let it see the future.

> **Tip:** Name the split that fits the data before you name the model. Shuffled folds on a time series is a classic wrong answer.

## Where does cross-validation go wrong?

The big trap is data leakage. A step learns from rows that the test fold should never see. Scaling is the classic case. If you compute the average and spread of all 8,000 loans before cutting the folds, every test fold has already shaped the numbers the model trains on.

*Diagram, Scaling before or after the cut: Scale before cutting the folds and every test fold has already shaped the numbers. Scale inside each training fold, or use a pipeline, and the test fold stays clean.*
1. Scaling saw the test rows, so the score is inflated.
2. Each training fold is scaled alone, and the test fold only follows those numbers.

> "Test data should never be used to make choices about the model." (scikit-learn)
>
> "preprocessing (such as standardization, feature selection, etc.) and similar data transformations similarly should be learnt from a training set and applied to held-out data for prediction" (scikit-learn)

The fix is a pipeline: the scaler and the model go together, so cross-validation refits both on each training fold. The scikit-learn guide says pipelines also help avoid leaking the test data into the training data.

### How would you cross-validate a weekly demand forecast?

A retailer forecasts weekly demand for 400 stores from three years of sales. Shuffled folds would mix next winter's weeks into training and test on last spring. The score could look excellent while the forecast fails in production.

I would use a time series split: train on the earliest weeks, test on the next block of weeks, then move the test block forward, with the training weeks growing. Each test is on weeks the model has not seen, in the order they happen. I would also say the rolling runs cost more time, and I would keep the most recent months aside for one final check.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] A plain definition: train on most folds, test on the one left out, then average.
- [ ] Why one split can mislead: the score depends on which rows were picked.
- [ ] The spread as well as the average, and what a wide spread means.
- [ ] Leakage, with scaling as the classic example, and a pipeline as the fix.
- [ ] The right split for the data: stratified, grouped, or time-ordered.
- [ ] A final test set that is never used to pick models.

**Common traps**

- Trap: "Cross-validation means I train on everything, then test on everything." Better: No. Each round tests on rows the model did not train on. That is the whole point.
- Trap: "I scale the data first, then cross-validate." Better: Then the test folds shaped the scaler. Put the scaler in a pipeline so each fold refits it.
- Trap: "I shuffle the sales weeks and run 5-fold." Better: With a time order, shuffling lets the model see the future. Train on the past and test on what comes next.

## Can you spot the leak?

**Pick the clean setup:** A team has 8,000 loans to cross-validate. Which setup keeps every test fold clean?

A. Fit the scaler on all 8,000 rows, then run 5-fold cross-validation.
B. Put the scaler and the model in one pipeline, and cross-validate the whole pipeline.
C. Keep the 1,000 loans with the best scores as the test set, and train on the rest.
D. Report the single highest fold score as the model's accuracy.

**Answer:** B. The pipeline refits the scaler on each training fold, so the test fold never shapes it. The first option leaks test rows into the scaler. The last two pick a result by its score, which inflates it.

**Quick check:** A retailer trains a weekly demand model on three years of sales. Which check is most honest?

A. Shuffle all the weeks, then run 5-fold
B. Train on the earlier weeks, test on the next week, and roll forward
C. Keep the ten weeks with the best scores and report them
D. Score the model on the weeks it trained on

**Answer:** B. Demand has a time order, and nearby weeks look alike. A rolling test only ever scores the model on weeks it has not seen, in the order they happen.

## Can you answer these from memory?

**Flash cards**

- **What is cross-validation?** Testing a model on several folds in turn, then averaging the scores.
- **What is k-fold?** Cut the data into k folds. Train on k minus one, test on the one left out.
- **Why not one split?** One split can be lucky or unlucky. Several rounds show the honest level and spread.
- **What is stratified k-fold for?** Keeping the mix of outcomes in each fold, so rare cases appear in every fold.
- **Why not shuffle a time series?** Shuffling lets the model see the future. Train on the past, test on what follows.
- **What is the classic leak?** Scaling or fitting on all rows before the split. Use a pipeline instead.

## Likely follow-up questions

- Q422 Train/validation/test splits? https://designervenkat.online/interview/ai/train-validation-test-splits
- Q424 What is data leakage? https://designervenkat.online/interview/ai/what-is-data-leakage
- Q412 Bias vs variance? https://designervenkat.online/interview/ai/bias-vs-variance
- Q413 Overfitting vs underfitting? https://designervenkat.online/interview/ai/overfitting-vs-underfitting
- Q436 How do you tune hyperparameters? https://designervenkat.online/interview/ai/how-do-you-tune-hyperparameters
- Q425 How do you handle class imbalance? https://designervenkat.online/interview/ai/how-do-you-handle-class-imbalance

## Learn it in depth

- [K-Fold Cross Validation: every slice counts](https://designervenkat.online/learn/machine-learning/k-fold-cross-validation)
- [Validation techniques: testing fairly](https://designervenkat.online/learn/machine-learning/validation-techniques)
- [LOOCV: leave one out, test every example](https://designervenkat.online/learn/machine-learning/leave-one-out-cross-validation)
