Evaluate Your Model and Spot Overfitting
Your network from the last lesson reached a good accuracy. But a model that scores well on data it has already seen can still fail on new data. In this lesson you will split off a validation set, watch two loss curves side by side, and learn to spot overfitting before it fools you.
Keep the Colab notebook from lesson 3 open. The code here reuses its model, loss_fn, train_data, test_data and device.
What You'll Learn
- Why you need three sets of data: training, validation and test
- How to make a validation split with
random_split - What
model.train()andmodel.eval()do - How to read training and validation loss curves
- Four simple ways to fight overfitting, including early stopping
Three Sets, Three Jobs
| Set | Used for | How often |
|---|---|---|
| Training | The model learns from it | Every step |
| Validation | You check progress and make choices (epochs, learning rate, layer sizes) | After every epoch |
| Test | One final, honest score | Once, at the end |
Why not use the test set to make choices? Because every choice you make by looking at a score leaks a little information about that data into your model. After enough tweaks, your test score is no longer a fair picture of new data. The validation set takes that hit, so the test set stays clean.
If you want the theory in more depth, the Machine Learning Fundamentals with Python course covers train/test splits and cross-validation with scikit-learn.
Make a Validation Split
Fashion-MNIST gives you 60,000 training images and 10,000 test images. Take 10,000 from the training set for validation:
import torch
from torch.utils.data import DataLoader, random_split
generator = torch.Generator().manual_seed(42) # same split every run
train_set, val_set = random_split(train_data, [50_000, 10_000], generator=generator)
train_loader = DataLoader(train_set, batch_size=64, shuffle=True)
val_loader = DataLoader(val_set, batch_size=256)
test_loader = DataLoader(test_data, batch_size=256)
print(len(train_set), len(val_set), len(test_data)) # 50000 10000 10000
Only the training loader shuffles. Shuffling helps learning but does not change a score, so there is no need for it on validation or test data.
train() and eval() Modes
Some layers act differently while learning and while being checked. Dropout, which you will meet below, turns off random neurons only during training. So PyTorch has two modes:
model.train()before training stepsmodel.eval()before you measure anything
Pair model.eval() with torch.no_grad(). That stops PyTorch from tracking gradients you will never use, which saves memory and time.
Two Helper Functions
Paste these into a new cell. The first trains for one epoch. The second measures loss and accuracy on any loader without changing the model.
def train_one_epoch(model, loader, loss_fn, optimizer):
model.train()
total_loss = 0.0
for X, y in loader:
X, y = X.to(device), y.to(device)
loss = loss_fn(model(X), y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
total_loss += loss.item() * len(X)
return total_loss / len(loader.dataset)
def evaluate(model, loader, loss_fn):
model.eval()
total_loss, correct = 0.0, 0
with torch.no_grad():
for X, y in loader:
X, y = X.to(device), y.to(device)
logits = model(X)
total_loss += loss_fn(logits, y).item() * len(X)
correct += (logits.argmax(dim=1) == y).sum().item()
n = len(loader.dataset)
return total_loss / n, correct / n
logits.argmax(dim=1) picks the class with the highest score for each image. Comparing it with the true labels and counting the matches gives accuracy.
Watch the Two Curves
Now build a fresh model (so it starts from zero) and train for 15 epochs. Record both losses every epoch:
model = FashionNet().to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
history = []
for epoch in range(15):
train_loss = train_one_epoch(model, train_loader, loss_fn, optimizer)
val_loss, val_acc = evaluate(model, val_loader, loss_fn)
history.append((train_loss, val_loss))
print(f"epoch {epoch+1:2d} train {train_loss:.3f} val {val_loss:.3f} val acc {val_acc:.1%}")
Then plot them:
import matplotlib.pyplot as plt
plt.plot([h[0] for h in history], label="training loss")
plt.plot([h[1] for h in history], label="validation loss")
plt.xlabel("epoch")
plt.ylabel("loss")
plt.legend()
plt.show()
Your numbers will differ a little, but the shape is usually the same. Training loss keeps going down. Validation loss goes down for the first several epochs, then flattens, then starts to creep up.
Reading the Curves
| What you see | What it means |
|---|---|
| Both losses high and flat | Underfitting. The model is too small or has not trained long enough. |
| Both going down together | Healthy. Keep training. |
| Training down, validation flat or rising | Overfitting. The model is memorizing the training images instead of learning patterns that carry over. |
The best model is the one at the lowest point of the validation curve, not the one at the last epoch.
Try It: Find the Best Epoch
This small example runs here in your browser. It uses loss numbers like the ones you might see in Colab and finds where to stop. The patience rule stops training after a set number of epochs with no improvement. This is called early stopping.
Watch the gap column. A growing gap between validation and training loss is the clearest sign of overfitting.
Four Ways to Fight Overfitting
1. Early stopping. Keep a copy of the weights whenever validation loss hits a new low, and load that copy at the end. Here it is with a fresh model:
import copy
model = FashionNet().to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
best_val, best_state = float("inf"), None
for epoch in range(15):
train_one_epoch(model, train_loader, loss_fn, optimizer)
val_loss, val_acc = evaluate(model, val_loader, loss_fn)
if val_loss < best_val:
best_val = val_loss
best_state = copy.deepcopy(model.state_dict())
model.load_state_dict(best_state)
2. Dropout. Add nn.Dropout(0.2) after a hidden layer. During training it turns off 20% of that layer's outputs at random, so the network cannot depend on any single neuron:
nn.Linear(28*28, 256), nn.ReLU(), nn.Dropout(0.2),
3. Weight decay. Ask the optimizer to keep weights small, which pushes the model toward simpler patterns:
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=1e-2)
4. More data or data augmentation. More varied examples make memorizing harder. For images, small random flips and shifts create "new" training images for free. You will see this in the next lesson.
The Final Test Score
When you are done making choices, check the test set once:
test_loss, test_acc = evaluate(model, test_loader, loss_fn)
print(f"Test accuracy: {test_acc:.1%}")
A simple fully connected network usually lands somewhere around 88% to 90% on Fashion-MNIST. If your test score is far below your validation score, something leaked or the split is off. Check your code before you trust either number.
Accuracy Is Not the Whole Story
Accuracy tells you how often the model is right overall. It does not tell you which classes it mixes up. On Fashion-MNIST, shirts, T-shirts and pullovers often get confused because they look alike at 28 by 28 pixels. Printing accuracy per class shows this quickly:
classes = test_data.classes
correct = torch.zeros(10)
total = torch.zeros(10)
model.eval()
with torch.no_grad():
for X, y in test_loader:
preds = model(X.to(device)).argmax(dim=1).cpu()
for label, pred in zip(y, preds):
total[label] += 1
correct[label] += int(label == pred)
for i, name in enumerate(classes):
print(f"{name:12s} {correct[i] / total[i]:.1%}")
Key Takeaways
- Use training data to learn, validation data to make choices, and test data once at the end.
- Call
model.train()before training andmodel.eval()withtorch.no_grad()before measuring. - Overfitting shows up as training loss falling while validation loss flattens or rises.
- Fight it with early stopping, dropout, weight decay, and more or augmented data.
- Look at per-class accuracy to see which classes your model confuses.
Quiz
Up next · Lesson 5 of 6
CNNs and Transfer Learning
6 min read
4 of 6 lessons done

Ask Byte about this lesson
A private chat about this lesson. Byte has read the whole lesson, answers in seconds, and shows the section each answer comes from. Ask follow-ups in any language.
Questions & Answers
Public questions about this lesson. The AI Tutor answers right away in your language, the FreeAcademy team checks answers, and every learner can read them.

