Skip to main content

Overfitting and underfitting

Why This Matters

A model that scores 100% on its training data sounds perfect. Often it is the opposite: it memorised the training data, including its noise and mistakes, and will do worse on anything new. A model that scores badly everywhere is the other failure: too simple to capture the pattern. Both are found the same way, by comparing scores on data the model has seen and data it has not.

What you will learn

  • What overfitting and underfitting are, and what causes them
  • How to detect each by comparing training, validation and test performance
  • How to read a model-complexity sweep, in code

Syllabus: AI-6.1.8.

Two ways to fit badly

  • Overfitting: the model has captured noise along with the pattern. It is excellent on its training data and generalises poorly to new data. Causes: a model too complex for the amount of data, training too long, too few examples.
  • Underfitting: the model is too simple, or lacks key features, to capture the pattern. It does badly on the training data and on new data.
          underfitting          good fit            overfitting
training      low                 high               very high (≈100%)
validation    low                 high               lower than training
test          low                 ≈ validation       clearly lower than validation

How testing detects them

  • Overfitting: test on a separate test set that is rich in the less common cases. Significantly worse performance on the test data than on the validation data suggests overfitting. (A large gap between training and validation scores is the first warning.)
  • Underfitting: poor performance on both training and validation data.
  • Check the metrics (accuracy, precision, recall, F1) on both sets, and inspect learning curves: scores plotted against model complexity or amount of training. If training and validation errors stay high and close together without improving, the model is underfitting.

Test for both during training, evaluation and tuning, not only at the end.

Hands-on: a complexity sweep

Train the decision tree from module 3 with increasing depth, and record three scores for each: training and validation accuracy (5-fold cross-validation, lesson 16) and accuracy on the independent test set. You continue in the practice project; create module-7/test_fitting.py:

"""Lesson "Overfitting and underfitting": compare training, validation and test scores as the model gets more complex."""
import sys
from pathlib import Path

import pandas as pd
import pytest
from sklearn.model_selection import StratifiedKFold, cross_validate
from sklearn.tree import DecisionTreeClassifier

sys.path.insert(0, str(Path(__file__).parent.parent / "module-3"))
from test_data_preparation import prepare  # noqa: E402

FEATURES = ["age", "income", "creditScore"]
DEPTHS = [1, 2, 3, 4, 6, None]


@pytest.fixture(scope="module")
def scores(api):
    train = prepare(pd.DataFrame(api.get(f"{api.base}/datasets/loans-train", timeout=10).json()["data"]))
    test = pd.DataFrame(api.get(f"{api.base}/test-set", timeout=10).json()["data"])
    folds = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
    rows = []
    for depth in DEPTHS:
        model = DecisionTreeClassifier(max_depth=depth, random_state=0)
        cv = cross_validate(model, train[FEATURES], train["approved"] == "Yes", cv=folds, return_train_score=True)
        model.fit(train[FEATURES], train["approved"] == "Yes")
        rows.append({
            "max_depth": str(depth),
            "training": cv["train_score"].mean(),
            "validation": cv["test_score"].mean(),
            "test": (model.predict(test[FEATURES]) == test["repaid"]).mean(),
        })
    table = pd.DataFrame(rows).set_index("max_depth")
    print("\n" + table.round(3).to_string())
    return table


def test_depth_1_underfits(scores):
    row = scores.loc["1"]
    assert row["training"] < 0.85 and row["validation"] < 0.75   # poor on training AND validation


def test_no_depth_limit_overfits(scores):
    row = scores.loc["None"]
    assert row["training"] == 1.0                                 # perfect on what it has seen
    assert row["test"] < row["validation"] - 0.05                 # clearly worse on new data


def test_depth_2_generalises(scores):
    row = scores.loc["2"]
    assert row["training"] - row["validation"] < 0.10

Run it

pytest module-7/test_fitting.py -v -s
           training  validation   test
max_depth
1             0.833       0.729  0.775
2             0.938       0.851  0.800
3             0.964       0.851  0.825
4             0.995       0.851  0.750
6             1.000       0.851  0.750
None          1.000       0.851  0.750

Read it as a learning curve over complexity:

  • Depth 1 underfits. One question cannot express “credit score and income”; training accuracy is only 0.833 and validation 0.729. Both low.
  • Depth 2 and 3 fit well. Training is high but not perfect, validation is at its best (0.851), and the test score is close to it (0.800 and 0.825).
  • Depth 4 and deeper overfit. Training climbs to 1.000, validation stays at 0.851, and the test score drops to 0.750, 10 points below validation. The deep trees learned the noise, including the two wrongly labelled rows, and it costs them on new applicants.

Notice that validation did not drop. With only 48 training rows, the cross-validation folds are small and similar to each other, so validation could not see the overfitting; the independent test set, drawn from a slightly different population, could. That is exactly why the syllabus says to test on a separate test set rich in less common cases.

Exercise

A neural network is trained for 200 epochs. After every epoch, the team records the loss (error) on the training data and on the validation data:

  • epochs 1-40: both losses fall steadily, staying close together
  • epochs 40-80: training loss keeps falling; validation loss flattens
  • epochs 80-200: training loss approaches zero; validation loss rises

Where does the model start to overfit, and which model would you keep? If both losses had stayed high and close together from the start, what would that mean?

Show suggested answer

Overfitting starts around epoch 40 to 80, where validation loss stops improving while training loss keeps falling; after epoch 80 it is clear (validation loss rises). Keep the model from around the point where validation loss was lowest (early stopping), and confirm it once on the test set.

If both losses had stayed high and close together, the model would be underfitting: too simple or missing important features. More epochs would not help; a more complex model or better features would.

Exam-style questions

Quiz

1. A model achieves 99% accuracy on the training data, 92% on the validation data and 78% on the test data. What does this most likely indicate?

  • A. Underfitting
  • B. Overfitting
  • C. Data drift
  • D. A good fit
Show answer
B. Significantly worse performance on test than on validation.
Quiz

2. A model performs poorly on both the training data and the validation data. What is the most likely cause?

  • A. Overfitting
  • B. Underfitting: the model is too simple or lacks key features
  • C. The test data is not independent
  • D. The model is non-deterministic
Show answer
B.

Your project so far

ai-testing-practice/
├── ...
└── module-7/
    ├── ...
    └── test_fitting.py    new in this lesson

The finished version is in the example repository: module-7/test_fitting.py.