Artificial Intelligence Fundamentals / Check and Troubleshoot Models

Spot overfitting and underfitting

Lesson 13 of 26. Open to read. No account needed.

Learning the Pattern, Not the Examples

In the classifier lesson, the decision tree classified every training wine correctly but scored 0.889 on the test wines. That gap is the subject of this lesson. A model's purpose is to generalise: to capture the pattern behind its training examples well enough to handle new ones. It can fail in two opposite ways:

  • Underfitting: the model is too simple to capture the pattern. It does poorly on the training data and on new data alike.
  • Overfitting: the model is so flexible that it learns the training examples themselves, including their noise and mistakes. It does very well on the training data and noticeably worse on new data.

Every real dataset contains noise: measurement errors, mislabelled examples, cases that are simply unusual. A model that reproduces its training data perfectly has learned that noise as if it were part of the pattern.

Reading the Two Scores Together

Comparing the training score with the test score diagnoses the problem:

Training scoreTest scoreDiagnosis
LowLow, similarUnderfitting
HighClearly lowerOverfitting
GoodClose to trainingReasonable fit

Neither score alone is enough. A high training score can hide overfitting; a low test score could mean underfitting or overfitting, and only the training score tells you which.

Complexity Controls the Balance

Most models have settings that control how flexible, or complex, they can become. For a decision tree, the main one is max_depth, the number of question levels it may ask. A depth-1 tree asks one question; a tree with no limit keeps splitting until every training sample is classified correctly. As complexity grows, the training score rises steadily, while the test score first rises, then levels off or falls once the model starts learning noise.

As model complexity grows from left to right, the training score rises towards a perfect score. The test score rises at first, peaks, and then falls. The left region, where both scores are low, is labelled underfitting; the middle, where the test score peaks, is labelled a good fit; the right, where the gap between the scores widens, is labelled overfitting.

Read the diagram from left to right. The solid line is the training score and the dashed line the test score. The distance between them is the gap. On the left, both are low and close together. In the middle, the test score is at its highest. On the right, the training line keeps climbing while the test line falls away: the widening gap is the sign of overfitting.

Exercise: Watch a Tree Overfit

You will train trees with depths 1 to 12 on noisy generated data and find where they stop generalising.

Starting state: the course environment, active in your terminal. The script generates its own data.

  1. Create the exercise folder. macOS and Linux:

    mkdir -p ~/ai-practice/tree-depths
    cd ~/ai-practice/tree-depths
    

    Windows PowerShell:

    mkdir $HOME\ai-practice\tree-depths
    cd $HOME\ai-practice\tree-depths
    

    Save this as tree_depths.py in that folder:

    """Train decision trees of increasing depth and compare training and test accuracy."""
    import matplotlib
    
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    from sklearn.datasets import make_classification
    from sklearn.model_selection import train_test_split
    from sklearn.tree import DecisionTreeClassifier
    
    X, y = make_classification(n_samples=600, n_features=10, n_informative=4, flip_y=0.15, random_state=1)
    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1, stratify=y)
    
    depths = range(1, 13)
    train_scores, test_scores = [], []
    print("depth  train  test")
    for depth in depths:
        tree = DecisionTreeClassifier(max_depth=depth, random_state=1).fit(X_train, y_train)
        train_scores.append(tree.score(X_train, y_train))
        test_scores.append(tree.score(X_test, y_test))
        print(f"{depth:5}  {train_scores[-1]:.3f}  {test_scores[-1]:.3f}")
    
    fig, ax = plt.subplots()
    ax.plot(depths, train_scores, marker="o", label="training")
    ax.plot(depths, test_scores, marker="s", linestyle="--", label="test")
    ax.set_xlabel("max_depth")
    ax.set_ylabel("accuracy")
    ax.legend()
    fig.savefig("tree_depths.png")
    print("Saved tree_depths.png")
    
  2. Run it:

    python tree_depths.py
    

    Output, which should match exactly:

    depth  train  test
        1  0.711  0.720
        2  0.747  0.720
        3  0.842  0.813
        4  0.867  0.827
        5  0.889  0.800
        6  0.924  0.793
        7  0.953  0.780
        8  0.971  0.793
        9  0.982  0.760
       10  0.993  0.747
       11  1.000  0.747
       12  1.000  0.747
    Saved tree_depths.png
    

    The chart in tree_depths.png shows the same twelve pairs of numbers as two lines.

How the Script Works

Noisy data. make_classification generates 600 samples with 10 features, of which 4 carry information. flip_y=0.15 gives a random 15% of the samples the wrong label, so no model can be right about all of them on new data.

The loop. For each depth from 1 to 12, the script trains a tree on the training samples only, then records its accuracy on the training samples and on the test samples. The two lists, train_scores and test_scores, grow by one value each time, and [-1] picks the value just added for printing.

The chart. Two ax.plot calls draw the training and test scores against depth, with different markers and line styles so the lines differ without relying on colour, and ax.legend() labels them.

What the results show. At depth 1, both scores are about 0.71: the tree is too simple, underfitting. The test score peaks at 0.827 at depth 4, where the training score is 0.867, a small gap. From there the training score keeps climbing until it reaches 1.000 at depth 11, while the test score drifts down to 0.747. The deep trees have memorised the training samples, including the deliberately wrong labels. A depth around 4 generalises best here.

Looking at test scores for twelve depths is fine for seeing the pattern, but choosing the depth this way would use the test set to make a decision, which the split lesson warned against. The next lesson shows how to choose fairly.

Success: the output matches; you can point to the underfitting region, the best depth and the overfitting region, using both columns.

If something differs:

What you seeLikely causeNext step
Different numbersrandom_state, flip_y or n_samples was changedRestore the values shown
The training score is 1.000 at every depthmax_depth=depth is missing, so every tree is unlimitedPass max_depth=depth
No tree_depths.pngThe script stopped before the chart lines, or ran in another folderRead the error message; run ls in the exercise folder
ModuleNotFoundErrorThe course environment is not activeActivate it and rerun
  1. Clean up. macOS and Linux:

    cd ~/ai-practice
    ls
    rm -rf tree-depths
    ls
    

    Windows PowerShell:

    cd $HOME\ai-practice
    ls
    Remove-Item -Recurse tree-depths
    ls
    

    Check that the first ls shows tree-depths before removing it. Do the independent task first.

Independent task: change n_samples=600 to n_samples=1200 and predict how the gap between the training and test scores at the deepest trees will change. Run the script and compare.

Check Your Understanding

Label each pair of training and test accuracy as underfitting, overfitting or a reasonable fit:

  1. Training 0.99, test 0.71.
  2. Training 0.62, test 0.60.
  3. Training 0.86, test 0.84.
  4. Training 0.75, test 0.88.

Answer and Reasoning

Independent task

With 1,200 samples, the training score climbs more slowly: it reaches only 0.979 at depth 12, instead of 1.000 at depth 11. At depth 12 the gap is 0.979 against 0.750, about 0.23, slightly smaller than the 0.25 with 600 samples. The best test score, 0.783, now comes at depth 5. More data makes memorising harder, so overfitting sets in a little later and a little less sharply. It does not remove the problem: 15% of the labels are wrong, and a deep enough tree still learns them.

Understanding check

  1. Overfitting: nearly perfect on training data, much worse on test data.
  2. Underfitting: both scores are low and close together.
  3. A reasonable fit: both are good and close.
  4. None of the three patterns. A test score far above the training score is unusual and worth investigating: the test set may be too small, easier by chance, or contaminated, for example by duplicates of training samples or by leakage.

References

Study this course with an account

Course access adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

See course access

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy