Module 06 · Lesson 6 of 9Free
Overfitting and underfitting
- Level
- Beginner
- Reading time
- 13 min
When you finish this page you can
- Tell underfitting, a good fit and overfitting apart from a model’s training loss and held-out loss.
- Read a held-out log loss against the no-feature floor and say whether a model learned anything.
- Explain why a model with many parameters can drive training loss down while held-out loss rises.
- Pick the right fix for each problem, and say why the wrong one won’t help.
Builds on 4 lessons
Start with Module 05, lesson 1317 minChapters
Show transcript
0:00 Meet Kartly, our example online store. Every Monday, Joseph’s growth team sends vouchers to the 20,000 customers most likely to churn, which means to stop buying. That adds up to 20 lakh rupees of vouchers a week. Farah, an ML engineer, builds the model that ranks who gets one. This week, Farah tries a much bigger network. She trains it for 200 passes over her customers, and it reports a training loss of 0.120. That’s far lower than any model before it. Joseph sees the number and wants to ship it on Monday. Before anything ships, Farah checks it on 50,000 customers it never saw in training. On them, the loss jumps to 0.610. Now compare a model that knows nothing. It gives everyone the same 13% chance of leaving. On those same customers, it scores 0.386. So on new customers, the big network does worse than knowing nothing. How do you tell a model that learned a pattern from one that’s too simple, or one that memorised its training customers?
1:01 One loss can’t answer that. You need two, measured the same way. Training loss is the average loss on the customers the model learned from. Held-out loss is the average on customers kept out of training. Here, that’s 50,000 of the 200,000. Held-out loss is your best guess at how the model will do on next Monday’s customers. That is called generalization. How much worse it does there than on its training customers is called the generalization gap. For log loss, there’s one more landmark: the no-feature floor, at 0.386. A held-out loss near the floor means the features taught the model almost nothing. Above it, the model does harm. Here are Farah’s five models, from smallest to biggest. They all train on the same 150,000 customers. In each pair, the top bar is training loss and the bottom bar is held-out loss. The dashed line is the floor. Watch the training bars. They get shorter on every row. The held-out bars shrink too, down to 0.326 for the small network. Then the big network splits wide open: training far to the left, held-out at 0.610, past the floor.
2:08 Start with the risk score. It looks at just two things: the days since a customer’s last order, and how many orders they’ve placed. It scores 0.362 on its training customers and 0.363 on held-out ones. The gap is tiny, so it behaves the same on new customers. But both numbers sit close to the floor. That’s underfitting: the kind of model is too simple to capture the pattern. It can’t use the other 10 features, however long it trains.
2:34 Now the big network. It has 269,825 adjustable numbers, its parameters, but only 150,000 training customers. More parameters than examples. So it can give almost every training customer an answer of its own. Why is that bad? Because churn labels are noisy. Picture two customers who look the same in all twelve features. One of them leaves, because she moved city. No feature records the move. A model that learns that answer anyway is learning noise. Take four look-alike training customers. One left and three stayed. The best an honest model can say for customers like these is a chance of 0.25. The big network does something else. It gives the three stayers almost nothing, 0.01, and the leaver almost a sure thing. On these four, its training loss looks almost perfect. Now a new look-alike arrives. It lands nearest a stayer, so it gets 0.01 too. But one in four of these customers leaves. When a leaver gets 0.01, log loss charges heavily. On average, the big network’s loss here is about twice the honest model’s. That’s overfitting: the model learns details of its training examples that don’t carry over to new ones. Training loss is low, and held-out loss is much higher. Confident wrong answers can even push it past the floor.
3:53 Model size is one way to overfit. Training time is the other. Farah logs both losses for the big network after every epoch, one full pass over the training customers. For the first few epochs, both losses fall together. The network is learning patterns that hold for every customer. Held-out loss reaches its lowest point at epoch 6, at 0.333. After that, the two lines part. Training loss keeps falling, all the way to 0.120. Held-out loss turns up, crosses the floor, and ends at 0.610. The network is now spending its parameters on the training customers alone.
4:30 The two problems pull in opposite directions, so a fix for one makes the other worse. For underfitting, give the model more to work with: better features, a more flexible model, or longer training. More data of the same kind won’t help. In between sits a good fit: both losses lower, with a small gap. Ship that one, and keep watching it. Overfitting needs the reverse. Get more training data, so each parameter has to serve more customers. Use a smaller model. Stop training earlier. Or add a penalty on large weights. More epochs or more parameters only make it worse. Will more data help? A learning curve tells you. It plots both scores against the number of training examples. If the two lines have already met at a poor score, more data won’t help. Stopping early and penalising large weights have a name: regularization.
5:19 So which model goes on Monday’s list? Not the big network after all those epochs. Its confident wrong scores would push customers who weren’t leaving into the top 20,000. Much of the voucher money would go to the wrong people. What about the big network, stopped at epoch 6? It scores 0.333, worse than both small models. And Farah picked that epoch by looking at the held-out customers, so even that score is a little optimistic. That leaves the two small models. The small network scores 0.326. The weighted sum scores 0.330. A difference that small could flip with another random split of the customers. When two models score about the same, the simpler one wins. The weighted sum has 13 weights, and each one can be read, so Joseph can see why a customer is on the list. Choose by held-out loss, never by training loss.
6:10 Let’s recap. One: read training loss and held-out loss together. Two: near the no-feature floor, little was learned; above it, the model does harm. Three: a model with room to spare can fit noise, and its confident wrong answers cost a lot. Four: overfitting grows with model size and with training time. Five: the two problems need opposite fixes. Farah picked her best epoch by peeking at the held-out customers. Next, we’ll make stopping early, and penalising large weights, part of training itself. See you in Regularization: L1, L2 and early stopping.
A training loss of 0.120
is our example online store. Every Monday, Joseph’s growth team sends ₹100 vouchers to the 20,000 customers most likely to : to stop buying. That is ₹20 lakh of vouchers a week. Farah, an ML engineer, builds the model that ranks the customers, on a notebook sample of 200,000.
Farah’s best churn model so far has a held-out log loss of 0.330. This week she tries a much bigger network. After 200 passes over the data, it reports a of 0.120.
Joseph sees the number and asks to ship it on Monday.
Farah checks it on 50,000 customers it never trained on. There it scores 0.610. Predicting 13% for every customer, with no features at all, scores 0.386 on the same customers.
The 200,000 customers, the 13% leave rate and the 0.386 floor come from the course’s notebook sample. Every training and held-out loss in this lesson is a made-up scenario number, chosen to show the pattern.
This lesson answers one question: how do you tell a model that learned a pattern from one that is too simple, or one that memorised its training customers?
The big network’s training loss is 0.120, far below any earlier model. Its held-out loss is 0.610. Did it learn anything useful about who leaves?Show answer
Two numbers, read together
A single loss can’t answer the question. You need two, measured the same way:
- Training loss: the average loss on the customers the model learned from.
- Held-out loss: the average loss on customers kept out of training. Here, 50,000 of the 200,000. Train, validation and test sets covers how to choose them.
The held-out loss estimates : how the model will do on next Monday’s customers. The difference between the two numbers is called the generalization gap:
- : the average log loss on the held-out customers.
- : the average log loss on the training customers.
For log loss there is one more reference point. Entropy and cross-entropy showed that 0.386 is the loss of a model with no features. A held-out loss near 0.386 means the features taught the model almost nothing. A held-out loss above it means the model does harm.
Here are Farah’s models, the three from Models as functions with learnable parameters plus the big network. All train on the same 150,000 customers.
| Model | Parameters | Training loss | Held-out loss | Gap |
|---|---|---|---|---|
| Always 13%, no features | 1 | 0.386 | 0.386 | 0.000 |
| Risk score, gap and orders | 3 | 0.362 | 0.363 | 0.001 |
| Weighted sum, 12 features | 13 | 0.327 | 0.330 | 0.003 |
| Network 12 → 16 → 1 | 225 | 0.318 | 0.326 | 0.008 |
| Network 12 → 512 → 512 → 1, 200 epochs | 269,825 | 0.120 | 0.610 | 0.490 |
Training loss falls on every row. Held-out loss falls to 0.326, then jumps to 0.610.
Too simple: both losses stay high
The 3-parameter risk score scores 0.362 on training customers and 0.363 on held-out ones. The gap is tiny, so the model behaves the same on new customers. But both numbers sit close to the 0.386 floor.
This is underfitting: the model family is too simple to express the pattern in the data. The risk score sees only the gap since the last order and the order count. It can’t use the other 10 features, however long it trains. scikit-learn’s guide gives the same test: if the training score and the validation score are both low, the model is underfitting.1
Too flexible: the model memorises noise
The big network has 269,825 parameters and only 150,000 training customers. That is more adjustable numbers than examples. So it can give almost every training customer its own answer.
Why is that harmful? Because churn labels contain noise. Two customers can look the same in all 12 features, and one leaves because she moved city. No feature records the move. scikit-learn’s own example describes an overfit model the same way: it “learns the noise of the training data”.2
Four training customers with almost the same 12 values
1 left, 3 stayed: share leaving = 1 ÷ 4 = 0.25
The best any honest model can say for customers like these is 0.25.
Expected loss on a new look-alike, predicting 0.25
0.25 × 1.386 + 0.75 × 0.288 = 0.347 + 0.216 = 0.562
A leaver costs −ln 0.25 ≈ 1.386; a stayer costs −ln 0.75 ≈ 0.288.
The big network gives the 3 stayers 0.01 and the leaver 0.99
training loss on these 4 ≈ −ln 0.99 ≈ 0.010 each
On training customers, it looks almost perfect.
A new look-alike lands nearest a stayer, so it gets 0.01
0.25 × 4.605 + 0.75 × 0.010 = 1.151 + 0.008 = 1.159
A leaver given 0.01 costs −ln 0.01 ≈ 4.605. The expected loss is about twice the honest model’s.
The four look-alike customers are a made-up example for this lesson.
This is : the model learns details of its training examples that don’t carry over to new ones. The symptom is a training loss that is low and a held-out loss that is much higher. Confident wrong answers are why the held-out loss can pass the floor: log loss charges heavily for a 0.01 given to a leaver.
Overfitting grows with training time
Model size is one way to overfit. Training time is the other. Farah logs both losses after every of the big network, as in The training loop.
| Epoch | Training loss | Held-out loss |
|---|---|---|
| 1 | 0.371 | 0.372 |
| 3 | 0.335 | 0.338 |
| 6 | 0.318 | 0.333 |
| 10 | 0.302 | 0.337 |
| 20 | 0.270 | 0.355 |
| 50 | 0.205 | 0.430 |
| 100 | 0.158 | 0.520 |
| 200 | 0.120 | 0.610 |
Early on, the network learns patterns that hold for every customer. After epoch 6, training loss keeps falling and held-out loss turns up.
Each problem needs a different fix
The two problems pull in opposite directions, so a fix for one makes the other worse.
| Symptom | Diagnosis | Fixes that help | Fixes that won’t |
|---|---|---|---|
| Both losses high, close together, near 0.386 | Underfitting | More informative features; a more flexible family; train longer if training loss is still falling | More data of the same kind |
| Both losses lower, small gap | Good fit | Ship it, then watch it | — |
| Training low and falling; held-out high or rising | Overfitting | More training data; a smaller family; stop training earlier; a penalty on large weights | More epochs; more parameters |
More data helps overfitting because each parameter then has to serve more customers. A , which plots both scores against the number of training examples, shows whether it will: if the two lines have already met at a poor score, more data won’t help.1 Stopping earlier and penalising large weights are called regularization. Regularization: L1, L2 and early stopping shows how each works. Bias and variance splits the held-out error into the two parts these fixes target.
Which model goes on Monday’s list
Joseph wants a model on Monday’s list. Which of Farah’s models should rank the 200,000 customers?
The big network after 200 epochs, training loss 0.120.
Held-out 0.610, worse than predicting 13% for everyone. Its confident wrong scores push stayers into the top 20,000, so much of the ₹20 lakh goes to people who weren’t leaving.
The big network, stopped at epoch 6.
Held-out 0.333, worse than both small models, with about 20,000 times the parameters of the weighted sum. Epoch 6 was also picked by looking at the held-out customers, so 0.333 is a little optimistic.
The weighted sum of 12 features.
Held-out 0.330, with a gap of 0.003. Each of its 13 weights can be read, so Joseph can see why a customer is on the list.
The small network, 12 → 16 → 1.
Held-out 0.326, the lowest. The lead over the weighted sum is 0.004, small enough that another random split of the customers could reverse it.
Why this choice
Choose by held-out loss, never by training loss. On that test, the big network is out at any epoch.
Between the two small models, the difference is 0.004. That is too small to trust from one split of 50,000 customers. When two models score about the same, the simpler one wins: it is easier to read, check and retrain.
The choice changes if the small network keeps its lead on fresh customers it has never been judged on, and over several random seeds. Then 0.004 is a real gain, and 200,000 customers is plenty of data for 225 parameters.
Parameter count alone doesn’t predict overfitting
The big network had more parameters than training customers and overfit. But the count is only a warning sign. Zhang and colleagues showed that image networks can fit training labels assigned at random, which no pattern can explain.3 So the ability to memorise doesn’t tell you whether a network will. Only the held-out loss does, which is why you measure it for every model, large or small.
Try it yourself
Run this in a free Colab or Kaggle on a CPU; it takes under a minute. It makes 200,000 made-up customers with 12 features and a 13% leave rate. Then it trains three decision trees, a model that splits customers into groups by asking yes-or-no questions about features. One is very shallow, one is limited, one can grow until each group holds a single customer.
import numpy as np
from sklearn.metrics import log_loss
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
rng = np.random.default_rng(42)
n = 200_000
X = rng.normal(size=(n, 12))
# True chance of leaving uses 4 of the 12 features, one pair together
logit = -2.3 + 0.8 * X[:, 0] - 0.6 * X[:, 1] + 0.4 * X[:, 2] * X[:, 3]
y = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
print("leave rate:", round(y.mean(), 3))
X_tr, X_ho, y_tr, y_ho = train_test_split(X, y, test_size=50_000, random_state=42)
models = {
"1 question": DecisionTreeClassifier(max_depth=1, random_state=42),
"groups of 500+": DecisionTreeClassifier(min_samples_leaf=500, random_state=42),
"no limit": DecisionTreeClassifier(random_state=42),
}
for name, model in models.items():
model.fit(X_tr, y_tr)
train = log_loss(y_tr, model.predict_proba(X_tr)[:, 1])
held = log_loss(y_ho, model.predict_proba(X_ho)[:, 1])
print(f"{name:15} train {train:.3f} held-out {held:.3f}")What to look for. These are expected patterns worked out by reasoning, not output from a run:
- The leave rate prints about 0.13.
- “1 question”: both losses a little below 0.386 and almost equal. It underfits.
- “groups of 500+”: both lower, with a small gap. A good fit.
- “no limit”: a training loss near 0 and a held-out loss far above 0.386, likely above 1. It overfits: every held-out mistake is a confident one.
Where this shows up
- Design: a churn prediction model for an online store: every candidate model is compared on held-out loss against the 0.386 floor.
- Design: a classifier for product photos: a network with millions of parameters on 100,000 photos, where watching the two losses each epoch decides when to stop.
Stopping the big network at epoch 6 cut its held-out loss from 0.610 to 0.333. But Farah chose epoch 6 by looking at the held-out customers. The next lesson makes stopping early, and penalising large weights, part of training itself.
Common mistakes
- Shipping the lowest training loss. Training loss never gets worse as a model grows. It can’t tell a pattern from memorised noise.
- Calling any gap overfitting. A gap of 0.003 is normal. Worry when the gap is large or growing, or the held-out loss is rising.
- Collecting more data for an underfit model. If training loss is already high, the model can’t use what it has. Add features or flexibility first.
- Tuning on the held-out customers, then reporting their score. Every choice made by looking at them makes their score a little optimistic. Keep a separate set for the final number.
Check your understanding
A new model scores 0.371 on training customers and 0.374 on held-out ones. Is it overfitting?Show answer
Farah doubles the training customers for the big network and retrains for 200 epochs. What do you expect to happen to its training loss and its held-out loss?Show answer
A model’s held-out log loss is 0.420. Joseph says that is close to 0.386, so it is nearly as good as having no model. Is he right?Show answer
During training, held-out loss falls for 10 epochs, then flattens while training loss keeps falling slowly. Should Farah keep training?Show answer
Summary
- Read training loss and held-out loss together: underfitting shows both high and close, overfitting shows training low and held-out much higher.
- For a 13% churn label, 0.386 is the no-feature floor; a held-out log loss near it means little was learned, above it means harm.
- A model with more parameters than it needs can fit noise in the labels, and its confident wrong answers raise held-out loss.
- Overfitting grows with both model size and training time; held-out loss is lowest at some point and then rises.
- Underfitting needs more features or flexibility; overfitting needs more data, a smaller model, earlier stopping or a weight penalty.
