Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Learning pathDeep Learning for Production: Transformers, Fine-Tuning and Serving
  1. 1
    Dropout, Early Stopping and Batch Norm: Judge Each One by the Validation Curve
  2. 2
    Transfer Learning on Images: A Frozen ResNet-18, a Small Head and an Honest Baseline
  3. 3
    Attention Explained Without the Maths: Query, Key, Value and the Word "it"
  4. 4
    Transformer Building Blocks in PyTorch: Follow the Shapes Through Attention and a Block
  5. 5
    Pretrained Models from Hugging Face: A Sentiment Pipeline and Sentence Embeddings on a CPU
  6. 6
    Loading a Language Model and Running Inference: Download, Load, Tokenize, Generate
  7. 7
    Model Size and Memory: Parameters x Bytes, Quantization, and Where to Run a Model
  8. 8
    Training on a GPU: Mixed Precision, Gradient Accumulation and Checkpoints That Really Resume
  9. 9
    When NOT to Fine-Tune: A Decision Tree of Prompt, RAG, Tools, Then Fine-Tuning
  10. 10
    Full Fine-Tuning vs LoRA vs QLoRA: What Each One Changes and What It Costs
  11. 11
    LoRA Fine-Tune of a Tiny Model: Teach SmolLM2-135M Your House Style on a CPU
  12. 12
    Knowledge Distillation: Teach a Model 100 Times Smaller From a Teacher's Soft Labels
  13. 13
    Serving Open Models: Continuous Batching, vLLM and Cold Starts
  1. Blog
  2. /
  3. Machine Learning
  4. /
  5. Deep Learning

Learning path: Deep Learning for Production: Transformers, Fine-Tuning and Serving · Step 1 of 13

Dropout, Early Stopping and Batch Norm: Judge Each One by the Validation Curve

Three tools that keep a network honest on unseen data, each judged by its validation curve on 150 digit images: early stopping with patience 5, nn.Dropout(0.5), nn.BatchNorm1d, and the batch norm trap that drops a frozen model from 95.8% to 33.6%.

Chaand Sheikh

·27 November 2026Deep Learning

What you will learn

  • Add early stopping with a patience counter and load the best weights back
  • Add nn.Dropout and see why model.train() and model.eval() matter
  • Add nn.BatchNorm1d and read what it does to training and validation loss
  • Avoid the batch norm trap: a frozen encoder that changes in train mode

Before you start

  • The Same Network in PyTorch
  • The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers

Think about coaching a team. One star player gets every pass. On the day she's out, the team falls apart. So in practice you bench players at random, and now nobody can lean on one star. That's dropout. You also watch the practice matches, and when the results stop improving, you end the session. That's early stopping. And before each play, everyone settles into the same steady pace. That's batch norm, more or less.

Three habits, one goal: a network that does well on data it hasn't seen. Training loss always looks good, so we judge each tool by one thing only, its validation curve. The test set stays locked away for the final score.

The problem: training falls, validation turns

The setup: a pretrained ResNet-18 from Hugging Face turns each image into 512 features, and a single nn.Linear layer (the head) sits on top. The data is scikit-learn's load_digits: 1,797 small handwritten digits, resized to 128x128 and split 60/20/20 into 1,078 train, 359 validation and 360 test images. To make overfitting easy to see, the head trains on only 150 of the training images.

Train and validation loss, 150 images, 200 epochs 0 0.5 1 1.5 2 2.5 1 50 100 150 200 epoch loss best 0.626 at epoch 5 ends 0.804 train loss validation loss
The head trained on 150 images for 200 epochs. Train loss falls from 2.48 to about 0.0001. Validation loss bottoms out at 0.626 at epoch 5, climbs to 0.826 by epoch 55 and ends at 0.804. Drawn from the run's own loss history.

Train loss starts at 2.48 and keeps falling, all the way down near 0.0001. Validation loss falls too, to 0.626 at epoch 5. After that it turns around and climbs while train loss is still falling. The model is memorising those 150 images. That gap is what we're fighting, and validation is how we see it.

Early stopping: let validation decide when to quit

Here's the fit function from train.py. Every epoch it trains once and measures the validation loss.

import copy
import torch
from torch import nn


def fit(head, tr, va, epochs=200, patience=None,
        lr=0.01):
    torch.manual_seed(0)
    opt = torch.optim.Adam(head.parameters(), lr=lr)
    loss_fn = nn.CrossEntropyLoss()
    hist, best, best_state, bad = [], 1e9, None, 0
    for ep in range(1, epochs + 1):
        head.train()
        opt.zero_grad()
        loss = loss_fn(head(tr[0]), tr[1])
        loss.backward()
        opt.step()
        with torch.no_grad():
            vl = loss_fn(head(va[0]), va[1]).item()
        hist.append((ep, loss.item(), vl))
        if vl < best:
            best, bad = vl, 0
            best_state = copy.deepcopy(head.state_dict())
        else:
            bad += 1
        if patience and bad >= patience:
            break
    if patience:
        head.load_state_dict(best_state)
    return hist

Three moves make it work:

  • A new best? If vl beats the best so far, reset the counter and copy the weights somewhere safe with copy.deepcopy. At epoch 5, 0.626 lands there.
  • Not better? The counter bad goes up by one.
  • Out of patience? When bad reaches patience, break out of the loop and load the safe weights back.

These are the ten epochs the run actually took with patience=5:

EpochValidation lossCounter
11.3140 (new best)
20.8540 (new best)
30.6970 (new best)
40.6410 (new best)
50.6260 (best, weights saved)
60.6271
70.6362
80.6483
90.6614
100.6755, stop

The model we keep is the one from epoch 5, not the one from epoch 10.

Did stopping help?

h1 = make_head()
log1 = fit(h1, sub, (f[va], y[va]), lr=0.01)
h2 = make_head()
log2 = fit(h2, sub, (f[va], y[va]), lr=0.01, patience=5)
no stopping: epochs 200 best val epoch 5 test acc 0.8194
patience 5: epochs 10 test acc 0.8194

Exactly the same test accuracy, 0.8194. Early stopping bought no accuracy here, and it's worth being straight about that. What it did buy is 10 epochs instead of 200, and a kept validation loss of 0.626 instead of 0.804. It saved time and kept the lower loss. It didn't make the model smarter.

Dropout: bench half the numbers at random

The pretrained ResNet has no dropout layers, so compare_curves.py uses a tiny network on the raw 8x8 pixels (64 inputs) and the same 150 training images. It builds three versions that differ by one line:

import torch
from torch import nn


def net(kind):
    mid = {"plain": [],
           "dropout": [nn.Dropout(0.5)],
           "batch norm": [nn.BatchNorm1d(128)]}[kind]
    return nn.Sequential(nn.Linear(64, 128), *mid,
                         nn.ReLU(), nn.Linear(128, 10))

nn.Dropout(0.5) means that on every training step, about half of the 128 numbers coming out of the first layer are switched off at random, a different half each time. No single unit can become the star.

The training loop switches it on and off:

    for ep in range(1, epochs + 1):
        model.train()
        opt.zero_grad()
        loss = loss_fn(model(x[tr]), y[tr])
        loss.backward()
        opt.step()
        model.eval()
        with torch.no_grad():
            vl = loss_fn(model(x[va]), y[va]).item()
        hist.append((ep, loss.item(), vl))

model.train() turns dropout on. model.eval() turns it off, so validation always sees the whole network. Forget eval() and your validation numbers come from a half-benched team.

plain: best val 0.340 at epoch 26, final val 0.486, test acc 0.9083
dropout: best val 0.303 at epoch 53, final val 0.367, test acc 0.9194

The plain network reaches its best validation loss, 0.340, at epoch 26 and then climbs to 0.486. With dropout, the best is 0.303 at epoch 53, and it ends at 0.367. Test accuracy moves from 0.9083 to 0.9194. That's only 4 more images right out of 360, on one seed, so don't lean on it. The clearer change is the curve: it climbs less.

Batch norm: a steady range

Inside a network, numbers can drift to all sorts of ranges, and that makes learning harder. A batch norm layer rescales them using a mean and a spread, so the next layer always gets a steady range. In our tiny network it's the one line nn.BatchNorm1d(128).

batch norm: best val 0.353 at epoch 24, final val 0.369, test acc 0.9250

Look at training first. At epoch 10, train loss is 0.108 with batch norm against 0.767 without it, so it learns the training set much faster. Validation is less neat. Its best, 0.353, is a touch worse than plain's 0.340. But it stays close to that and ends at 0.369, where plain climbed to 0.486. Test accuracy is 0.9250, 6 images more than plain.

Validation loss: plain, dropout and batch norm 0 0.2 0.4 0.6 0.8 1 1 50 100 150 200 epoch validation loss plain dropout batch norm
Validation loss for the three tiny networks over 200 epochs (y axis cut at 1.0, the first epochs start higher). Plain climbs to 0.486 after its best. Dropout and batch norm stay flatter, ending at 0.367 and 0.369. Drawn from the run's own loss history.

One run, one small dataset. What we can honestly say is that both curves stayed flatter. Neither is a promise of a better test score every time.

The batch norm trap

Batch norm behaves differently in training and in evaluation:

  • In eval mode it uses a stored mean and spread, one fixed reference.
  • In train mode it uses the mean of the current batch, and it nudges the stored values too.

Back to the pretrained ResNet. Here's how model.py loads and uses it:

import torch
from torch import nn
from transformers import ResNetModel

NAME = "microsoft/resnet-18"


def load_encoder():
    enc = ResNetModel.from_pretrained(NAME)
    for p in enc.parameters():
        p.requires_grad = False
    return enc


def embed(enc, x, train_mode=False):
    enc.train(train_mode)
    with torch.no_grad():
        out = enc(pixel_values=x).pooler_output
    return out.flatten(1)

Every parameter has requires_grad = False. The run confirms it:

encoder params: 11176512 trainable: 0

11,176,512 parameters, zero trainable. So nothing can change, right? This time the head is trained on all 1,078 training images. Then we run the same images through the encoder with train_mode=True, in batches of 32:

frozen head test acc: 0.9583
BN stats drift, train mode: 1.3876
same images, max embedding gap: 15.1972
head acc, encoder in train mode: 0.3361

One flag, and accuracy falls from 0.9583 to 0.3361. No error, no warning. The first batch norm layer's stored mean moved by up to 1.39, and the same images now come out with features up to 15.2 apart.

The reason: the stored mean (running_mean) is a buffer, not a parameter. requires_grad = False only freezes parameters, so it never touches it. Freezing a model with batch norm takes two switches: requires_grad = False and eval().

Common mistakes

  • Judging by training loss. It falls for every model. Only the validation curve tells you about unseen data.
  • Stopping without loading the best weights back. Without load_state_dict(best_state) you keep the last epoch, which is already patience epochs past the best.
  • Forgetting model.eval() before validation or prediction. Dropout stays on and batch norm keeps using batch statistics.
  • Thinking requires_grad = False freezes everything. Batch norm's running mean and variance still move in train mode.
  • Reading a 4-image gain as proof. One seed on 360 test images can't separate two methods that close.

Quick recap

ToolWhat it doesWhat it did here
Early stoppingQuits when validation stops improving, loads the best weights backSame 0.8194 accuracy in 10 epochs instead of 200
nn.Dropout(0.5)Switches off about half the units at random in trainingValidation ended at 0.367 instead of 0.486
nn.BatchNorm1dRescales values to a steady rangeTrain loss 0.108 vs 0.767 at epoch 10; validation ended at 0.369
eval()Turns dropout off, makes batch norm use stored statsWithout it, a frozen encoder fell from 0.9583 to 0.3361

Try it yourself

In compare_curves.py, change nn.Dropout(0.5) to nn.Dropout(0.2) and run it again. Does the validation curve climb more or less than with 0.5? Next, see how a frozen pretrained model and a small head become a full method in Transfer Learning on Images.

Built this? Share your solution in the StudyEasy AI Community.

Join free on Skool →
Next →
Transfer Learning on Images: A Frozen ResNet-18, a Small Head and an Honest Baseline
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Related articles
Why Neural Networks: Pixels, One Neuron and Layers

Why pictures need neural networks: a handwritten digit is 784 numbers, one neuron is a weighted sum plus a bias and one small rule, and neurons stack into layers. Worked out on MNIST with NumPy.

The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax

Follow numbers through a tiny 3-2-3 network in NumPy: one matrix product per layer, ReLU inside, softmax at the end, and a count of every weight and bias.

Loss and Backpropagation: How Wrong, and Who Is to Blame

The loss says how wrong the network was; backpropagation says how much each weight is to blame. MSE and cross-entropy, the chain rule by hand on a two-weight chain, then the same gradients from PyTorch autograd.

The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers

How training is organised: shuffle, cut into mini-batches, take one step per batch, repeat per epoch. Real MNIST runs compare three learning rates, SGD against Adam, and show the overfitting signal in the validation loss.

On this page
  • The problem: training falls, validation turns
  • Early stopping: let validation decide when to quit
  • Did stopping help?
  • Dropout: bench half the numbers at random
  • Batch norm: a steady range
  • The batch norm trap
  • Common mistakes
  • Quick recap
  • Try it yourself
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.