Overfitting and Underfitting in Machine Learning
Overfitting happens when a model learns the training data too well, including its noise and accidents, so it does worse on new data. Underfitting is the opposite: the model is too simple to capture the real pattern and does poorly everywhere.
Noise is the trap
Real labels contain mistakes and oddities: a mislabeled photo, a customer who behaved unusually. A flexible enough model can memorize every one of them. On training data that looks like perfection. On new data, those memorized quirks become wrong answers, because the quirks do not repeat.
Watching it happen
The example builds forty points along a line from 0 to 39. The true pattern is simple: label 1 from 20 upward, 0 below. A few labels are flipped on purpose to simulate noise. Even positions train, odd positions test.
Two models compete:
- The memorizer stores every training point and, for a new point, copies the label of the closest training point. It is a 1-nearest-neighbor model, and it can represent any pattern, noise included.
- The threshold learns a single cut-off, the same kind of model as in the first chapter. It cannot represent the noise at all.
Expected output
learned threshold: 20 memorizer train 1.00 test 0.70 threshold train 0.80 test 0.90
The memorizer is perfect on its training data and clearly worse on the test data. The threshold makes mistakes on training data, the flipped points it cannot fit, but it does better on the test set. Its simplicity is exactly what protects it.
The signs
| Training score | Test score | |
|---|---|---|
| Underfitting | low | low |
| Good fit | high | close to training |
| Overfitting | very high | much lower |
A large gap between training and validation scores is the classic symptom. scikit-learn's validation-curve tools plot both scores while one setting changes, which makes the sweet spot easy to see.
Remedies
- Simpler models, or settings that limit flexibility, such as using more neighbors in k-NN or a shallower decision tree.
- More training data, which makes noise a smaller share of what the model sees.
- Regularization, a penalty that discourages extreme models; most libraries expose it as a parameter.
- Better features that capture the real signal.
- Honest evaluation on validation data, so overfitting shows up before release.
Summary
- Overfitting: great on training data, poor on new data. Underfitting: poor on both.
- Compare training and validation scores to spot it.
- Simpler models, more data and regularization are the main fixes.
Quiz: Overfitting