Overfitting and Generalization

Updated · 5 min read
mediumPython 3.13aioverfittinggeneralizationtrainingbeginnersinterview

Can you score 100% on practice tests and still fail the exam? Before her driving theory test, Navika's classmate memorized the answers to all 200 practice questions. She scored 100% on every practice test, then failed the real one, because the real questions were worded differently. Navika learned the rules behind the answers instead, scored a little lower in practice, and passed easily.

Models face exactly the same trap. This lesson explains overfitting (memorizing) and generalization (understanding), and how to tell them apart.

Memorizing vs Understanding

Memorizing the practice answers vs understanding the methods

Generalization means doing well on new data the model has never seen. It is the whole point of training: a fruit sorter is useful only if it recognizes tomorrow's apples, not just the ones in its training photos.

Overfitting means learning the training data too closely, including its accidents and noise, so the model does very well on the training examples and badly on new ones. It memorized instead of understanding.

Overfitting in Python

Two tiny fruit models learn from the same four photos. One memorizes the exact examples; the other learned the general pattern that yellow photos are bananas. Then both meet three new photos:

Python
training = {0.9: "banana", 0.2: "apple", 0.8: "banana", 0.3: "apple"}
new_photos = {0.85: "banana", 0.25: "apple", 0.7: "banana"}
 
def memorizer(yellow):
    """Remembers the exact training examples, and nothing else."""
    return training.get(yellow, "no idea")
 
def generalizer(yellow):
    """Learned the general pattern: yellow photos are bananas."""
    return "banana" if yellow > 0.5 else "apple"
 
for name, model in [("Memorizer", memorizer), ("Generalizer", generalizer)]:
    seen = sum(model(x) == label for x, label in training.items())
    new = sum(model(x) == label for x, label in new_photos.items())
    print(f"{name}: training {seen}/{len(training)}, new photos {new}/{len(new_photos)}")
Output
Memorizer: training 4/4, new photos 0/3
Generalizer: training 4/4, new photos 3/3

Both are perfect on the training photos. Only one is useful. That is why "Datasets, Labels and Features" kept a test set aside: without it, you couldn't tell these two models apart.

Why It Happens, and What Helps

CauseWhat helps
Too few examplesCollect more, and more varied, data
A model too complex for the dataUse a simpler model, or fewer parameters
Training too long on the same examplesStop when the validation score stops improving
Unrepresentative data, such as only red applesCollect examples that match the real world

The opposite problem also exists: underfitting, a model too simple to capture the pattern at all, which does badly on training and new data. Good training sits between the two.

Common Mistakes

Celebrating a perfect training score. It may mean the model memorized; check the test score.

Testing on data the model trained on. It hides overfitting completely.

Thinking a bigger model always generalizes better. Without enough varied data, a bigger model can simply memorize more.

Interview Corner

What is overfitting?

When a model learns its training data too closely, including noise and accidents, so it performs well on training data and poorly on new data. It memorized instead of learning the general pattern.

How do you detect and reduce overfitting?

Detect it by comparing the training score with the score on a validation or test set: a big gap means overfitting. Reduce it with more and more varied data, a simpler model, stopping training early, and checking that the data represents the real world.

Practice

Exercise: catch the memorizer. Add two more photos to new_photos, such as 0.95: "banana" and 0.1: "apple", and run the program again. Do the scores change? Then add 0.9: "banana" to new_photos, a photo the memorizer has seen, and explain why its new-photo score improves only for that one example.

Check your understanding:

  1. What is the difference between overfitting and generalization?
  2. Why were both models perfect on the training photos?
  3. Name two ways to reduce overfitting.

Quick check: overfitting and generalization

4 questions
1A model scores 99% on training data and 60% on new data. What is most likely?
2What does generalization mean?
3Which helps reduce overfitting?
4In the exam analogy, what does the real exam stand for?

Key Takeaways

Quick reference

TermMeaning
GeneralizationDoing well on new, unseen data
OverfittingLearning the training data too closely, failing on new data
UnderfittingToo simple to capture the pattern
Early stoppingEnding training when the validation score stops improving

Was this tutorial helpful?

Lesson 22 of 186