Skills / Machine learning basics / Training and testing: learning without cheating

Machine learning basics, lesson 2 of 8

Training and testing: learning without cheating

A model that is graded on the same examples it learned from can look brilliant and still be useless, like a student who memorised last year's exam answers. To know how a model will do on new data, you must test it on data it has never seen.

The train/test split. Before training, set aside part of the data, often around 20%, as the test set. Train only on the remaining training set. Then measure performance on the test set. That score is your honest estimate of real-world performance. In scikit-learn, train_test_split does this in one line.

Overfitting is when a model learns the training examples too closely, including their noise and accidents, and fails on new data. The sign: excellent scores on training data, much worse on test data. Causes include models that are too complex for the amount of data, and too little data.

Underfitting is the opposite: the model is too simple to capture the real pattern, so it does badly on both.

Data leakage is a sneakier way of cheating. It happens when information that would not be available at prediction time slips into the training data. For example, predicting whether a customer will cancel using a column called "cancellation_reason", which only exists *after* they cancel. The model looks amazing in testing and fails in real life.

Healthy habits:

  • Split before you do anything else with the data
  • Never tune your model by looking at test scores again and again; use a separate validation set or cross-validation for tuning
  • Be suspicious of results that look too good to be true
Try it: A model scores 99% on training data and 61% on test data. Name the problem, and suggest two things you might try to fix it.

Check yourself

1. Why keep a separate test set?

2. Training score 99%, test score 61%. What is this?

3. Which is an example of data leakage?