"The model is overfitting" is one of the first things you hear when you start training neural networks. Definitions only go so far. The clearest way to see it is to train the same network several ways and put the loss charts side by side.
This post walks through that experiment. Same dataset, same training code. The main things that change are how many neurons the model has and how much data it sees. At the end, I try one common fix, dropout, on the overfitting model.
The setup
The dataset is MNIST: 28×28 grayscale images of handwritten digits 0–9. There are 60,000 images for training and 10,000 separate images for testing.
The model is as small as it gets: one hidden layer.
from torch import nn
model = nn.Sequential(
nn.Linear(784, hidden), # 784 pixels in, `hidden` neurons
nn.ReLU(),
nn.Linear(hidden, 10) # 10 outputs, one score per digit
)
Each image is flattened to 784 numbers, and the model outputs 10 scores. The highest score is the predicted digit.
Two losses, two questions
After every epoch (one full pass over the training data), I measure the loss on two different sets of images:
- Train loss: the error on the images the model learns from. It answers: how well does the model do on images it has already seen?
- Validation loss: the error on images the model never trains on. It answers: how well does it do on new images?
model.eval()
with torch.no_grad(): # measure only, don't learn
for X, y in val_dataloader:
loss = loss_fn(model(X.reshape(-1, 784)), y)
...
Think of it as an exam. Train loss is your score on practice questions you've studied many times. Validation loss is your score on the real exam, with questions you've never seen.
The real exam is what matters. Nobody needs a model that only recognizes the 60,000 images it trained on.
Experiment 1: Underfitting (2 neurons)
First, a model that's far too small: 2 hidden neurons, 1,600 parameters in total, trained on all 60,000 images.
| Train | Validation | |
|---|---|---|
| Loss after 10 epochs | 0.997 | 0.998 |
| Loss after 30 epochs | 0.939 | 0.954 |
| Accuracy after 30 epochs | 69.8% | 70.2% |
My first run stopped at 10 epochs, and the lines were still going down, so it wasn't clear whether the model just needed more time. I ran it for 30 epochs. From about epoch 20 the lines go flat at around 0.95, and accuracy stops at about 70%. Three times the training bought about 0.05 of loss.
Two things to notice in the chart:
- Both lines flatten out high. The dashed line is the validation loss of the good model in Experiment 2 (0.086). The 2-neuron model ends up more than 10 times worse.
- Train and validation sit almost exactly on top of each other. The model does just as badly on images it trained on as on new ones.
That second point is the giveaway. The model isn't memorizing anything. It doesn't have the capacity to learn the full pattern. It gets about 3 digits in 10 wrong, on old and new images alike.
But it did learn something
Looking at the falling lines, I wondered: doesn't the drop in loss mean 2 neurons still picked something up? Yes, quite a lot.
A model that learned nothing would guess at random among 10 digits: loss 2.30 (that's ln 10) and 10% accuracy. I actually hit this by accident with a 1-neuron model, whose only neuron "died" (ReLU output stuck at 0), and it sat at exactly 2.30 the whole time.
| Random guessing | 2 neurons | 50 neurons | |
|---|---|---|---|
| Validation loss | 2.30 | 0.95 | 0.09 |
| Accuracy | 10% | 70% | 97% |
From 10% to 70% is real learning, and most of it happened in the first epoch.
So what can 2 neurons learn? In this model, every image is squeezed into just 2 numbers before the last layer picks a digit. That means you can draw exactly what the model "sees": each test image as a point on a 2-D map, colored by its true digit.
You can read the model's whole report card off this map:
- Separated digits get classified well. 1s sit in their own corner at the bottom (93% correct). 6s are pushed into a tall stripe on the left (87%).
- Overlapping digits get confused. 5 and 8 land almost on the same spot, and 8 is the worst digit at 44%: it's mistaken for a 5 more often than any other. 4 and 9 overlap at the top (4 is most often mistaken for 9, and 9 for 4). 2 and 3 crowd together at the bottom left.
- The points stuck on the axes are ReLU at work. ReLU turns negative values into 0, so about a third of the images have a 0 in one of the two neurons. That throws away even more of the little room the model has.
| Digit | 1 | 6 | 4 | 0 | 9 | 2 | 7 | 3 | 5 | 8 |
|---|---|---|---|---|---|---|---|---|---|---|
| Accuracy | 93% | 87% | 81% | 74% | 73% | 67% | 65% | 59% | 55% | 44% |
So underfitting doesn't mean "learned nothing". It means the model learned as much as its size allows, and that's not enough for the task. Two numbers are enough to tell a 1 from a 6, but not a 5 from an 8.
This is underfitting: the model is too simple for the problem. Training longer doesn't fix it, as the extra 20 epochs show. It needs more capacity.
(A chart-reading tip I learned here: check the y-axis. Zoomed in from 1.00 to 1.28, the 10-epoch chart made a small drop look dramatic. Starting the axis at 0 shows how little it actually improved.)
Experiment 2: A good fit (50 neurons)... if you stop in time
Next, 50 hidden neurons (39,760 parameters), again on all 60,000 images.
My first run stopped at 10 epochs, and the validation loss was still going down at the end. So, as with Experiment 1, I ran it for 30 epochs to see where it really goes.
| Train | Validation | |
|---|---|---|
| Loss at epoch 9 (best) | 0.034 | 0.086 |
| Accuracy at epoch 9 | 99.1% | 97.3% |
| Loss after 30 epochs | 0.003 | 0.128 |
| Accuracy after 30 epochs | 99.9% | 97.4% |
For the first 10 epochs, this is what a good fit looks like. Both losses drop low and stay fairly close. A small gap is normal: a model is always a little better on the data it trained on. 97.3% on images it has never seen means it learned what digits look like.
Then it turns. After epoch 9:
- Train loss keeps falling, almost to zero (0.003). The model gets 99.9% of the training images right.
- Validation loss starts climbing, from 0.086 to about 0.13, almost 50% worse.
That's the overfitting pattern from the next experiment, appearing even with all 60,000 images. With enough epochs, even a reasonably sized model on plenty of data starts memorizing.
So "good fit" isn't a property of the model alone. It's the model plus when you stop training. Here, the right moment is epoch 9, where validation loss is lowest. Keeping the weights from that epoch is called early stopping.
The other thing to notice: validation accuracy barely moved (97.3% → 97.4%) while validation loss got 50% worse. I'll come back to why in the next experiment.
Experiment 3: Overfitting (100 neurons, 1,000 images)
Then a bigger model, 100 hidden neurons (79,510 parameters), but trained on only 1,000 images instead of 60,000, for 50 epochs.
| Train | Validation | |
|---|---|---|
| Accuracy after 50 epochs | 100% | 87.5% |
| Loss after 50 epochs | 0.005 | 0.519 |
| Best validation loss | 0.402 (around epoch 10) |
The two lines tell completely different stories:
- Train loss goes to almost zero. From around epoch 17, the model gets every single training image right.
- Validation loss bottoms out around epoch 10, then climbs, from 0.40 to 0.52.
That split is overfitting. The model has 79,510 parameters and only 1,000 images to learn from: about 80 parameters per image. That's enough room to simply memorize each image, including the quirks of each person's handwriting, instead of learning what makes a 3 a 3.
One detail surprised me: validation accuracy stayed flat at around 87% while validation loss got worse. The model wasn't getting more answers wrong. It was getting more confident about the ones it got wrong. Loss punishes confident mistakes heavily, so it shows the problem before accuracy does.
Why overfitting happens
The weights end up storing noise and details specific to the training examples, instead of the general pattern. The common causes:
- Too little training data. A few examples are easy to memorize. (Experiment 3.)
- A model that's too large for the data. More parameters means more capacity to memorize. A small model can't store everything, so it's forced to learn the main patterns.
- Training too long. Every extra epoch past the best point is more memorizing.
- Noisy or wrong labels. If some 7s are labeled as 1s, the model learns those mistakes too.
- No regularization. Without it, training has one goal: make the training loss as small as possible, and memorizing every image is often the easiest way to get there. Regularization is any technique that makes memorizing harder, for example dropout (randomly switch off neurons, see Experiment 4) or weight decay (penalize large weights, which specific memorized details usually need).
- Training data that doesn't match real use. Train only on neat handwriting, test on messy handwriting.
A common misconception is that too few neurons can also cause overfitting. It's the other way around. Too few neurons causes underfitting (Experiment 1).
How to read your own loss chart
| Underfitting | Good fit | Overfitting | |
|---|---|---|---|
| Train loss | high | low | very low (near 0) |
| Validation loss | high, close to train | low, close to train | stops improving, then rises |
| What happened | model too simple | learned the pattern | memorized the examples |
| Exam analogy | didn't study enough | understood the material | memorized the practice answers |
| Fix | bigger model (training longer only helps while the loss is still falling) | ship it | more data, smaller model, stop earlier, regularization |
Fixing overfitting
- Get more data. The single most effective fix. I gave the same 100-neuron model from Experiment 3 all 60,000 images instead of 1,000: its best validation loss dropped from 0.402 to 0.076, and accuracy went from 87.5% to 97.8%. It still started overfitting after about 7 epochs, though, so early stopping is still needed.
- Early stopping. Track validation loss and keep the weights from the epoch where it was lowest. That's epoch 9 in Experiment 2 and around epoch 10 in Experiment 3.
- A smaller model. Fewer parameters, less room to memorize.
- Regularization. Make memorizing harder. Weight decay keeps weights small. Dropout is the one I tried, below.
Experiment 4: Does dropout fix it?
Dropout randomly switches off neurons during training. In PyTorch it's one extra layer:
model = nn.Sequential(
nn.Linear(784, 100),
nn.ReLU(),
nn.Dropout(0.5), # each training step, switch off a random 50% of these 100 neurons
nn.Linear(100, 10)
)
Every batch, a different random half of the hidden neurons outputs zero. The network can't rely on any single neuron or any single path to remember a specific image, because that neuron might be switched off next time. It's forced to spread what it learns across many neurons, which pushes it toward general patterns instead of memorized details.
During inference (making predictions), dropout is turned off and all neurons are used. This is what model.train() and model.eval() switch:
model.train() # dropout ON: random neurons switched off
model.eval() # dropout OFF: the full network makes the prediction
(Forgetting model.eval() before testing is a classic bug: dropout stays on, the same image can get a different answer each time, and accuracy drops.)
A natural question: if half the neurons are off during training, won't the outputs be twice as large when they're all on? PyTorch handles this by scaling the surviving neurons up by 2× during training (1 / (1 − 0.5)), so the numbers have the same size in both modes.
I reran Experiment 3 (100 neurons, 1,000 images, 50 epochs) with one change: nn.Dropout(0.5).
| Without dropout | With dropout 0.5 | |
|---|---|---|
| Train accuracy hits 100% | around epoch 17 | around epoch 40 |
| Best validation loss | 0.402 | 0.372 |
| Validation loss after 50 epochs | 0.519 | 0.417 |
| Validation accuracy after 50 epochs | 87.5% | 88.6% |
Dropout clearly helped:
- Memorizing is slower. Train loss (dashed lines) falls more slowly, and it takes more than twice as many epochs to get every training image right.
- The model stays better on new images. Validation loss gets lower and climbs much less afterwards.
But it didn't make the problem go away. Validation loss still creeps up after epoch 25 or so. With only 1,000 images there's a limit to what any trick can do. Dropout buys time and a bit of accuracy. More data is still the real fix.
Summary
- Always measure loss on data the model doesn't train on. Train loss alone will tell you everything is great.
- Both losses high means underfitting: the model is too simple.
- Both losses low and close means a good fit.
- Train loss keeps falling while validation loss stops or rises means overfitting: the model is memorizing instead of learning.
- Dropout slows memorizing down and helps on new data, but it's no substitute for more data.
All the code is on GitHub: filip505/mnist-overfitting-underfitting. One Python file runs every experiment in this post and draws the charts, in about 10 minutes on a laptop CPU. If you're learning this, run it yourself and change the neuron count, the data size and the number of epochs. Watching the two lines split teaches more than any definition.





Top comments (0)