# Train, Validation and Test Splits

> How to split data into training, validation and test sets, why the test set stays locked, and the leaks that ruin it, explained for your AI interview.

**In short:** Train, validation and test splits cut your labelled data into three parts. The model learns from the training part, you tune settings on the validation part, and you report one honest score from the test part, which stays locked until the end.

AI and LLM interview question Q422, Classic ML and deep-learning basics. Beginner, very common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/train-validation-test-splits

## Say it in 30 seconds

Train, validation and test sets are three parts of your data. The model learns from the training part. I tune its settings on the validation part. Then I score it once on the test part, which I keep locked until the end. I split first, and rows that belong together, like one patient's visits, stay on the same side. Otherwise the score looks better than the model really is.

## Say it in 2 minutes

Before a model meets real customers, I need an honest test of it. So I split my labelled data into three sets. The training set is where the model learns. The validation set is where I compare settings and pick the best version. The test set is the final exam, and I score it only once.

The order matters. Split the data first, then fit any scaler or gap filler on the training rows only, because those steps learn numbers from the rows they see. Then keep rows that belong together on the same side. If one patient's five hospital visits land in both training and test, the model partly memorises that patient, and the score looks better than it really is. For data over time, like loan applications, I train on the older months and test on the newest ones, so the test looks like the future.

The test set must stay locked. Each time I read its score and change something, I learn a little about the test set, and the model fits it a little more. After enough rounds, the score stops measuring new data. I make those decisions on the validation set instead. If data is scarce, cross-validation, which takes turns testing on different parts of the training rows, gives steadier scores, but I still keep a test set held out for the final check.

## What are train, validation and test sets, in plain words?

You start with a pile of past examples where the right answer is already known, such as loan applications where the outcome is known, like which ones later defaulted. Before the model meets real customers, you cut that pile into parts, so you can test it on examples it never learned from.

Think of a hospital training a new triage nurse. She studies past cases, practises on mock cases while the course is still being adjusted, and then sits one sealed exam at the end. If the exam questions leaked out in advance, the pass mark would tell the hospital nothing. The same logic decides whether a loan model is safe to launch.

- **Training set:** The examples the model learns from.
- **Validation set:** Examples used to compare settings and choose a model while you build.
- **Test set:** Examples held back for one final, honest score.
- **Overfitting:** When a model memorises its training examples and fails on new ones.
- **Data leakage:** When information from the test set, or from the future, reaches training.

## How do you split the data, and in what order?

The order is the whole trick: split first, then train, tune and test. Cleaning or scaling the whole dataset before splitting it lets the test rows shape the numbers the model sees, so the score can come out too high. scikit-learn's guide names not keeping the test and train data separate as a common cause of this kind of error.

*Diagram, Three sets, one job each: One dataset is cut into three sets before training starts. Only the training set teaches the model, the validation set helps you choose, and the test set gives one final score.*
1. About 70% of the rows go to the model to learn from.
2. About 15% of the rows are used to compare settings.
3. About 15% are set aside and not looked at until the end.
4. One score from the test rows is the only number reported.

1. **Split first:** Cut the rows into three sets before fitting any scaler or gap filler.
2. **Train on the training set:** The model learns its numbers here, and nowhere else.
3. **Tune on the validation set:** Try settings, compare models, and keep the best version.
4. **Score the test set once:** Run the chosen model on the locked test set and report that one number.

Duplicates are the one thing to fix after splitting: delete any validation or test row that copies a training row, because a copied row lets the model score well by memorising it.

> "Dividing the dataset into two sets is a decent idea, but a better approach is to divide the dataset into three subsets." (Google, Machine Learning Crash Course)
>
> "A test set should still be held out for final evaluation, but the validation set is no longer needed when doing CV." (scikit-learn, cross-validation guide)
>
> "Always split the data into train and test subsets first, particularly before any preprocessing steps." (scikit-learn, common pitfalls)

## Why does a random split go wrong for patients and dates?

A random split is fine when rows are independent, like scanned invoices from many different suppliers. In scikit-learn, a random split is one helper call, train_test_split. Rows that belong together break the rule. scikit-learn's classic splitters, such as KFold and ShuffleSplit, assume the samples are independent and identically distributed, and time-ordered data breaks that assumption too.

- **Random split: Patient rows scattered.** A readmission model sees some of a patient's visits in training and others in testing, so it partly remembers that patient.
- **Grouped split: Each patient on one side.** All visits for a patient go to one set, so the test score reflects patients the model has never seen.
- **Time split: Test on the newest months.** Train on older months and test on newer ones, so the test looks like the future the model will face.

A mid-size bank has 36,000 made-up loan applications from 2021 to 2023. A random split mixes the three years, so the test rows are mixed across time and say little about the future the bank will face. A time split trains on 2021 and 2022, validates on early 2023, and tests on late 2023. scikit-learn's guide says it is very important to evaluate a model for time series data on the future observations.

Here is a small hospital example with made-up data. Patients have two to eight visits each. The random split puts one patient's visits on both sides, and the grouped split keeps each patient on one side.

```python
# Made-up hospital data: 300 patients, each with 2 to 8 visits.
import random

random.seed(7)
visits = [(p, v) for p in range(300) for v in range(random.randint(2, 8))]

# Naive split: shuffle every visit, keep 20% for testing.
random.shuffle(visits)
cut = int(len(visits) * 0.8)
train, test = visits[:cut], visits[cut:]
both = {p for p, _ in train} & {p for p, _ in test}
print("visits:", len(visits), "train:", len(train), "test:", len(test))
print("patients in both sets:", len(both))

# Grouped split: each patient goes wholly to one side.
ids = list(range(300))
random.shuffle(ids)
held_out = set(ids[:60])
train2 = [(p, v) for p, v in visits if p not in held_out]
test2 = [(p, v) for p, v in visits if p in held_out]
print("grouped split, patients in both:", len({p for p, _ in train2} & {p for p, _ in test2}))
print("grouped split, test visits:", len(test2))
```

Output:

```text
visits: 1435 train: 1148 test: 287
patients in both sets: 175
grouped split, patients in both: 0
grouped split, test visits: 283
```

> **Tip:** The second line of the output shows the leak: after a random split, 175 patients appear in both sets. The grouped split has none, so its test score reflects patients the model has never seen.

## Why must the test set stay locked?

Every time you read the test score and change something, you learn a little about the test set. Those lessons seep back into your choices. scikit-learn warns that there is still a risk of overfitting on the test set, because settings can be tweaked until the model scores best on it.

Google's course says many rounds of this procedure might cause the model to fit the peculiarities of the test set.

> **Tip:** Asked what to do when the test score disappoints? Don't tune on it. Go back to the validation set, or collect fresh test data for a new check.

### How would you split the data for a new loan model?

The bank gives you 36,000 made-up loan applications from three years. Here is the plan you would describe in the interview.

1. **Lock the newest 15%:** Those rows are the test set. They stay locked until the final check.
2. **Cross-validate the older 85%:** Take turns testing on parts of these older rows (cross-validation), using time-ordered folds, so each training set holds only the earlier months.
3. **Fit the final model:** Train on all the older rows, and fit any scaler or gap filler on these rows only.

The 15% and 85% are a starting point. Size each set by how many examples you need for a score you can trust.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] Three sets, and what each one is for.
- [ ] Split first, then fit any cleaning or scaling on the training rows only.
- [ ] A grouped or time split when rows are linked: patients, customers or dates.
- [ ] The test set is touched once, at the end, or the score stops being honest.
- [ ] Cross-validation when data is small, with a test set still held out.
- [ ] A real case from your own work, with the numbers you would check.

**Common traps**

- Trap: "I split randomly, 80 and 20, and that's it." Better: Random is fine for independent rows. Check for patients, customers or dates that repeat first.
- Trap: "I tuned on the test set until the score was best." Better: That makes the score optimistic. Tune on validation, then score the test set once.
- Trap: "70, 15 and 15 is the rule." Better: It's a starting point. Size the sets by how many examples you need for a stable score.

## Can you spot the leak?

**Spot the leak:** A loan team's notebook has four steps. Which one leaks the test set into training?

A. Split the applications by date, so the test set is the newest year.
B. Fit the feature scaler on all 36,000 rows, then split them.
C. Tune the decision threshold on the validation set.
D. Report the test score once, after the last change.

**Answer:** B. The scaler (the step that rescales each column to a similar range) learns its numbers from every row, so the test rows shape what the model trains on. Split first, then fit the scaler on the training rows only.

**Quick check:** A team tunes its model on the test set for three weeks, then reports the test score. What is the main problem?

A. The test set was too small to be useful.
B. The score is now optimistic, because the choices were fitted to the test set.
C. They should have used a bigger model.
D. They should have lowered the learning rate.

**Answer:** B. Every choice made against the test set makes the score less honest. Model size and learning rate do not fix that; a fresh test set or a held-out check does.

## Can you answer these from memory?

**Flash cards**

- **What are the three sets?** Training to learn, validation to tune, test to judge once at the end.
- **Why a validation set?** It gives honest feedback while you tune, without touching the test set.
- **What is data leakage?** Information that would not be available at prediction time gets into training.
- **Why split by patient or date?** So the test set holds people or periods the model has never seen.
- **Why keep the test set locked?** Each peek fits it a little more, so the final score stops being honest.

## Likely follow-up questions

- Q412 Bias vs variance? https://designervenkat.online/interview/ai/bias-vs-variance
- Q413 Overfitting vs underfitting? https://designervenkat.online/interview/ai/overfitting-vs-underfitting
- Q423 What is cross-validation? (full answer coming)
- Q424 What is data leakage? (full answer coming)
- Q247 Offline vs online evaluation? https://designervenkat.online/interview/ai/offline-vs-online-evaluation
- Q429 What is early stopping? (full answer coming)

## Learn it in depth

- [Train - Test Data: splitting your data](https://designervenkat.online/learn/machine-learning/train-test-split)
- [Validation techniques: testing fairly](https://designervenkat.online/learn/machine-learning/validation-techniques)
