Monday , November 30 2026
Dropout and batch normalization explained with tested NumPy code, inverted dropout, inference behaviour, LayerNorm vs BatchNorm and Keras/PyTorch usage.

Dropout and Batch Normalization in Deep Learning

Updated: 29 November 2026Level: IntermediateReading time: about 9 minutesNumPy · tested

Dropout and batch normalization are two layers found in almost every modern network. Dropout fights overfitting; batch normalization makes training faster and more stable.

What You Will Learn

  • How (inverted) dropout works
  • Why dropout is switched off at inference
  • How batch normalization normalises activations
  • Layer normalization for transformers
  • Where to place these layers

Prerequisites

Backpropagation.

Dropout in NumPy

Example
import numpy as np
rng = np.random.default_rng(0)
a = np.ones((1, 10))                        # activations of 10 neurons
p = 0.5                                     # drop probability
mask = (rng.random(a.shape) > p) / (1 - p)  # keep with prob 0.5, scale survivors by 2
print(a * mask, (a * mask).mean())

big = np.ones((1, 100000))
m = (rng.random(big.shape) > p) / (1 - p)
print(round((big * m).mean(), 3))
Output
[[2. 0. 0. 0. 2. 2. 2. 2. 2. 2.]] 1.4
0.998

Explanation: During training, each neuron is randomly switched off with probability p. Survivors are scaled by 1/(1−p) (“inverted dropout”) so the expected output stays the same – with 100,000 neurons the mean is 0.998 ≈ 1. Because neurons cannot rely on specific partners, the network learns redundant, robust features – like training many thinner networks and averaging them.

Note: Dropout is active only in training. Keras handles this automatically; in PyTorch call model.train() before training and model.eval() before validation or inference.

Batch Normalization in NumPy

Example
x = rng.normal(50, 10, (6, 3))            # batch of 6 samples, 3 features
print(x.mean(0).round(2), x.std(0).round(2))
mu, var = x.mean(0), x.var(0)
x_hat = (x - mu) / np.sqrt(var + 1e-5)     # normalise per feature
gamma, beta = np.ones(3), np.zeros(3)      # learnable scale and shift
out = gamma * x_hat + beta
print(out.mean(0).round(3), out.std(0).round(3))
Output
[53.19 53.79 49.32] [9.73 9.49 9.75]
[-0. -0. -0.] [1. 1. 1.]

Explanation: BatchNorm normalises each feature over the batch to mean 0 and std 1, then learns γ and β so the network can still shift and scale if needed. During inference it uses running averages of mean and variance collected in training. Benefits: higher usable learning rates, faster convergence, less sensitivity to initialisation and a mild regularising effect.

BatchNorm vs LayerNorm

Batch Normalization Layer Normalization
Normalises over The batch, per feature All features, per sample
Depends on batch size Yes (poor with tiny batches) No
Typical use CNNs Transformers, RNNs – see transformers

In Keras and PyTorch

Framework syntax (not run here)
# Keras
from tensorflow import keras
model = keras.Sequential([
    keras.layers.Dense(128), keras.layers.BatchNormalization(), keras.layers.Activation("relu"),
    keras.layers.Dropout(0.3),
    keras.layers.Dense(10, activation="softmax")])

# PyTorch
import torch.nn as nn
net = nn.Sequential(nn.Linear(64, 128), nn.BatchNorm1d(128), nn.ReLU(),
                    nn.Dropout(0.3), nn.Linear(128, 10))
Tip Detail
Dropout rate 0.1–0.3 for most layers, up to 0.5 for large dense layers
Placement Dropout after activations of dense layers; less common inside conv blocks
BatchNorm placement Usually Linear/Conv → BatchNorm → activation
Large CNNs Often use BatchNorm + data augmentation instead of heavy dropout

Series

Deep learning series: Intro to DL · ANN · Activation Functions · Loss Functions · Backpropagation · Optimizers · Dropout & BatchNorm · CNN · RNN · LSTM & GRU · Transfer Learning · Autoencoders · GANs · PyTorch vs TensorFlow

Interview Questions

Q: How does dropout reduce overfitting?
It randomly disables neurons during training, preventing co-adaptation and acting like an ensemble of sub-networks.

Q: Why scale by 1/(1−p)?
To keep the expected activation the same in training and inference (inverted dropout).

Q: What does batch normalization do?
Normalises layer inputs per mini-batch and learns scale/shift, stabilising and speeding up training.

Practice Exercises

  1. Show that without the 1/(1−p) scaling the mean drops to about 0.5.
  2. Train a Keras MLP on MNIST with and without dropout and compare validation accuracy.

Summary

Dropout randomly drops neurons in training to regularise; batch normalization normalises activations per batch for faster, stable training; layer normalization is the batch-independent version used in transformers.

Next: Introduction to CNN

About Machine Learning

Check Also

LSTM and GRU Explained (NumPy LSTM Cell + Keras Example)

LSTM and GRU explained: vanishing gradients, cell state and gates, an LSTM step in NumPy, GRU comparison, parameter counts and a Keras sentiment model.