Batch Normalization in Deep Learning

|
14 min read
|
30 views
Batch Normalisation_ Stable Learning Flow

Batch Normalization (BatchNorm, BN) is a neural network layer that normalizes activations using mini-batch statistics at training time and, in standard implementation, runs statistics at inference time. Then it multiplies the normalized activation by learnable scale parameter and adds learnable shift parameter .

Practically it looks like this:

BatchNorm controls scale and distribution of the intermediate activations while leaving the network freedom to find the optimal scale and offset. It makes BatchNorm suitable for use in a lot of deep learning architectures, especially for traditional convolutional neural networks. However, it is not an automatic choice of normalization technique for any given model.

This tutorial will take you from BatchNorm mechanism, explained via formula, to its implementation in code, from numerical example to comparison with other normalization techniques and even how you can find out if BatchNorm helps your model.

What Will I Learn?

Quick Summary

  • Batch Normalization normalizes neural-network intermediate activations.
  • In training mode, BatchNorm usually computes statistics based on the current mini-batch.
  • In inference mode, the most widespread approach is using running statistics that were gathered during training.
  • The parameter (\gamma) controls the scaling effect, while the parameter (\beta) controls the shifting effect.
  • The parameter (\epsilon) is used for numerical stability.
  • BatchNorm makes optimization easier by facilitating the use of higher learning rates and decreasing the sensitivity to the initialization point.
  • It can be difficult to compute batch-dependent statistics in case of very small effective batch size or synchronization requirements of training mode.
  • Batch Normalization is distinct from the input normalization technique since the latter one applies to the pre-processing of the model’s input, whereas the former one works within the network.
  • The selection depends on the architecture, tensor shapes, batch setting, and training specifics.

What Is Batch Normalization?

The Batch Normalization operation involves using the statistical measures computed from a mini-batch to normalize the activations and then scaling and shifting the result.

The formula used for BatchNorm on the batch (x_1,…,x_m) is as follows:

[
\mu_B=\frac{1}{m}\sum_{i=1}^{m}x_i
]

and:

[
\sigma_B^2=
\frac{1}{m}
\sum_{i=1}^{m}(x_i-\mu_B)^2
]

It then normalizes each value:

[
\hat{x}_i=
\frac{x_i-\mu_B}
{\sqrt{\sigma_B^2+\epsilon}}
]

and applies the learned transformation:

[
y_i=\gamma\hat{x}_i+\beta
]

Where:

SymbolMeaning
(x_i)Input activation
(\mu_B)Batch mean
(\sigma_B^2)Batch variance
(\epsilon)Small numerical-stability constant
(\hat{x}_i)Normalized activation
(\gamma)Learnable scale
(\beta)Learnable shift
(y_i)Output activation

This process was first discussed in the paper on BatchNorm and was used during training of neural networks with the results of better optimization, including using larger learning rates in the experiments.

Batch Normalization vs Input Normalization

These two ideas can be confused easily. Input normalization takes place before the processing by the model occurs. BatchNorm occurs in the middle of the neural network.

Example: Rescaling of the image pixels, ranging from 0 to 255 to the range 0 to 1, is input pre-processing.

An example of a layer is: nn.BatchNorm2d(64), which normalizes feature-map activations produced inside the network.

AspectInput normalizationBatch Normalization
LocationInput/preprocessing stageInside the neural network
DataOriginal inputIntermediate activations
StatisticsUsually fixed from training dataBatch statistics during training
Learnable scale/shiftNot inherentlyTypically yes
Training/inference distinctionUsually fixedUsually different
PurposePut input features on a useful scaleNormalize internal activations

Why this distinction matters: if someone tells you to “normalize the data” and you implement BatchNorm, you have not necessarily done the same thing.

Why Do We Use Batch Normalization?

BatchNorm was proposed for the purpose of easing deep-network optimization. According to the original authors, the motivation behind BatchNorm is associated with internal covariate shift and they also reported that BatchNorm allowed the use of higher learning rates and lowered sensitivity to initialization.

A contemporary explanation should be less naive than stating:

“BatchNorm works because it totally solves internal covariate shifts.”

That statement is too strong. A safer description is:

BatchNorm modifies the optimization space and activation distributions such that training becomes easier when applied to appropriate architectures.

Some potential effects of BatchNorm include:

  • more manageable activation scales,
  • optimization friendliness across a broad range of architectures,
  • tolerance for relatively high learning rates,
  • a slight regularization effect through batch statistics, and
  • less sensitivity to certain initialization conditions.

Note that all of these depend on architecture and training process. BatchNorm does not guarantee good performance.

How Does Batch Normalization Work?

Use the following five steps model:

Activations → Batch mean calculation → Batch variance calculation → Normalization → γ and β application → Next layer

What is critical about BatchNorm is that it does not just drop the initial distribution of activations. It normalizes the activation and gives back to the model two learned parameters to restore scale and offset.

Step 1: Calculate the Batch Mean

Suppose the activation values are:

[
[2,4,6,8]
]

The mean is:

[
\mu_B=\frac{2+4+6+8}{4}=5
]

Step 2: Calculate the Batch Variance

For this simplified example:

[
\sigma_B^2=
\frac{(2-5)^2+(4-5)^2+(6-5)^2+(8-5)^2}{4}
]

Therefore:

[
\sigma_B^2=
\frac{9+1+1+9}{4}=5
]

[
\sigma_B^2=
\frac{(2-5)^2+(4-5)^2+(6-5)^2+(8-5)^2}{4}
]

Therefore:

[
\sigma_B^2=
\frac{9+1+1+9}{4}=5
]

Step 3: Normalize the Values

Ignoring the tiny (\epsilon) temporarily:

[
\hat{x}=\frac{x-5}{\sqrt{5}}
]

The resulting values are approximately:

Original valueNormalized value
2-1.342
4-0.447
60.447
81.342

The transformed values are centered around zero and have approximately unit variance.

Step 4: Apply Gamma and Beta

Now suppose:

[
\gamma=2
]

and:

[
\beta=1
]

Then:

[
y=2\hat{x}+1
]

The network can therefore learn a useful scale and offset after normalization.

Why not simply stop after normalization?

Since imposing that all activations be exactly at the same standardized distribution may limit the representation unnecessarily, the trainable (\gamma) and (\beta) bring back that flexibility.

What Do Gamma, Beta, and Epsilon Mean?

Gamma (\gamma)

Gamma is the trainable scaling factor. Gamma is the controlling factor that dictates the scaling of the activation function output.

Beta (\beta)

The beta is the learnable offset parameter. This determines the offset value used post-normalization.

Epsilon (\epsilon)

Epsilon is a small constant added to the variance before taking the square root:

[
\sqrt{\sigma_B^2+\epsilon}
]

Its purpose is numerical stability.

Framework defaults are not necessarily identical. Current PyTorch documentation specifies eps=1e-5 for BatchNorm1d, while Keras 3 documents epsilon=0.001 for BatchNormalization.

Practical guideline: when transferring a model from one framework to another, compare the default values for BatchNorm, rather than assume that similarly named arguments will have similar default values.

Where Is BatchNorm Used?

BatchNorm can be used in convolutional and fully-connected neural nets.

Typical CNN architecture could be as follows:

Convolution

      ↓

BatchNorm

      ↓

Activation

Example:

Conv2d → BatchNorm2d → ReLU

Typical fully-connected architecture could use:

Linear → BatchNorm1d → ReLU

But ordering may depend on the specific architecture.

BatchNorm in CNNs: What Gets Normalized?

For a convolutional layer, a tensor may have the shape:

[
(N,C,H,W)
]

where:

  • (N) = batch size,
  • (C) = channels,
  • (H) = height,
  • (W) = width.

For BatchNorm2d, is described by PyTorch with respect to the channel dimension, where the statistics are computed across the corresponding batch/space dimensions per channel.

This implies that the technically correct statement is not:

“BatchNorm normalizes each image.”

Instead:

The BatchNorm2d operation applies normalization to convolutions through statistics specific to each channel of the batch and space.

This difference matters when discussing the batch size, shapes of tensors, and other normalization techniques.

Training vs Inference: The Critical BatchNorm Difference

This is the implementation detail most likely to cause confusion.

During Training

Batch normalization typically:

  1. computes statistics from the current mini-batch,
  2. normalizes the current activations,
  3. uses (\gamma) and (\beta),
  4. and updates the running statistics.

Conceptually:

Current mini-batch

       ↓

Batch mean + variance

       ↓

Normalize

       ↓

γ × x̂ + β

       ↓

Next layer

       +

       ↓

Update running statistics

PyTorch mentions running estimation of BatchNorm and mentions that such estimations are used at test time by default.

Similarly, Keras mentions that the training and inference are handled differently: during training, the current batch statistics are used, whereas during inference, moving statistics are used with training=False.

During Inference

During inference, common implementations use the running mean and variance accumulated during training.

New input

    ↓

Running mean + running variance

    ↓

Normalize

    ↓

γ × x̂ + β

    ↓

Prediction

This makes inference independent of the statistics of the particular prediction batch.

Why does this matter?

Think of the case where you train using 64 batches, but test using one data point at a time.

The model is not allowed to use the same running statistics when testing since there may be no such thing as an inference batch.

Enter running statistics.

PyTorch Batch Normalization Example

For a fully connected network:

import torch.nn as nn

model = nn.Sequential(
    nn.Linear(128, 64),
    nn.BatchNorm1d(64),
    nn.ReLU(),
    nn.Linear(64, 10)
)
For a convolutional block:
import torch.nn as nn

block = nn.Sequential(
    nn.Conv2d(3, 64, kernel_size=3, padding=1),
    nn.BatchNorm2d(64),
    nn.ReLU()
)

PyTorch provides different BatchNorm modules for different tensor configurations, including BatchNorm1d, BatchNorm2d, and BatchNorm3d.

PyTorch Training and Evaluation

During training:
model.train()
During evaluation:
model.eval()

with torch.no_grad():
    output = model(x)

This matters because PyTorch modules such as BatchNorm and Dropout change behavior between training and evaluation.

Verification checklist

When debugging a PyTorch BatchNorm model, check:

  • Is model.train() being used during training?
  • Is model.eval() being used during validation/inference?
  • Does the BatchNorm layer expect the actual number of features/channels being supplied?
  • Are running statistics being tracked as expected?
  • Is the effective batch size appropriate?
  • Is distributed training involved?

Keras Batch Normalization Example

Keras provides BatchNormalization directly:

from keras import layers

model = keras.Sequential([
    layers.Dense(64),
    layers.BatchNormalization(),
    layers.ReLU(),
    layers.Dense(10)
])
For a CNN:
model = keras.Sequential([
    layers.Conv2D(64, 3, padding="same"),
    layers.BatchNormalization(),
    layers.ReLU(),
    layers.MaxPooling2D()
])

Keras 3 documents epsilon, momentum, center, and scale as BatchNormalization configuration parameters, with defaults including epsilon=0.001, momentum=0.99, center=True, and scale=True.

BatchNorm Momentum: A Framework Detail You Should Not Assume

One subtle but important issue is the meaning of the momentum parameter.

Keras documents its moving-statistics update as:

[
moving_mean =
moving_mean \times momentum
+
batch_mean \times (1-momentum)
]

with an analogous update for moving variance. PyTorch uses a different update convention for its BatchNorm momentum parameter.

Therefore:

Do not assume that momentum=0.9 means the same thing in PyTorch and Keras.

When transferring a model between frameworks, verify the framework-specific definition.

BatchNorm vs LayerNorm vs GroupNorm vs InstanceNorm

Normalization methods differ primarily in which dimensions they use to calculate their statistics.

MethodMain statistical basisCommon contexts
BatchNormBatch/channel-related statisticsCNNs and conventional deep networks
LayerNormFeatures within each exampleTransformers and sequence models
GroupNormGroups of channels within each exampleVision models with small batches
InstanceNormEach sample/channelSome image-generation and style-transfer workloads

Instead of the batch-wise approach used by BatchNorm, LayerNorm is an approach where each data example is normalized across the set feature dimensions.

Similarly, InstanceNorm calculates statistics for each instance separately, unlike BatchNorm.

The practical decision

Don’t ask:

“What is the best method for normalization?”

Instead, ask:

“What normalization works best for this architecture, tensor shape, batch size, and training scenario?”

This is a much better engineering question to ask.

What Happens When the Batch Is Very Small?

The reason why BatchNorm depends on batch statistics is that the technique is applied during training.

This does not mean that “BatchNorm is not applicable for small batches”.

There are many factors that may influence the result, including:

  • architecture,
  • data,
  • batch size,
  • implementation,
  • training parameters,
  • distributed system,
  • and the quality of the output statistics.

In case batch statistics have a negative impact on performance, you should try another normalization technique.

BatchNorm and Distributed Training

The distributed training scenario brings about another factor:

There may be some data on a particular machine that represents only part of the actual batch. PyTorch has the SyncBatchNorm utility for synchronized BatchNorm statistics in the supported distributed training configurations.

The Keras library offers the synchronized version of its BatchNormalization layer in supported TensorFlow distributed configurations. The key question is whether: The BatchNorm statistics have been computed from the actual population of the intended examples?

BatchNorm vs Dropout

BatchNorm and Dropout are not interchangeable.

BatchNorm

BatchNorm:

  • normalizes activations,
  • alters optimization dynamics,
  • keeps running statistics in most popular implementations,
  • and can add regularization through batch statistics.

Dropout

The dropout layer drops out the activations probabilistically based on its probability parameter.

In theory:

BatchNorm:  activation → normalize  → scale & shift

Dropout: activation → random masking  → rescale

The original BatchNorm paper describes cases where BatchNorm can help do away with Dropout in their experiments. This does not mean there is a hard rule stating that BatchNorm needs to substitute for Dropout in every model. Consider them different architectural design decisions and validate the two together through experimentation.

Common Batch Norm Mistakes

Confusing BatchNorm with input normalization

BatchNorm is an internal mechanism of a neural network. Input normalization is not the same as BatchNorm.

Forgetting evaluation mode

In PyTorch, failing to use:

model.eval()

can cause evaluation behavior to differ from what you intended.

Ignoring effective batch size

BatchNorm relies on batch statistics while training. Extremely small batches require special consideration.

Assuming framework defaults are identical

PyTorch and Keras use different documented defaults for parameters such as epsilon and different conventions for momentum.

Treating the original motivation as the complete modern explanation

While it was an original motivation to reduce internal covariate shift, that is not the whole story about how BatchNorm works.

Assuming BatchNorm automatically improves every model

Normalization is an architectural decision. Test its performance on your particular task.

How to Troubleshoot BatchNorm

Use this sequence rather than changing several variables at once.

Step 1: Verify training/evaluation mode

For PyTorch:
model.train()
for training and:
model.eval()
for evaluation.

Step 2: Check the effective batch size

Record:

  • batch size per device,
  • number of devices,
  • if statistics are synchronized,
  • if the batch size changes,
  • and if there is gradient accumulation.

Step 3: Inspect running statistics

When there are any issues while testing your models, check BatchNorm’s running mean and variance in PyTorch.

Step 4: Compare controlled experiments

Maintain the following as consistently as possible:

  • dataset,
  • optimizer,
  • learning-rate schedule,
  • training time,
  • evaluation method,
  • random seed,
  • architecture except for the modification to the normalization layer.

Then compare BatchNorm with the baseline.

Step 5: Test an alternative normalization method

If the problem is batch dependency, consider an alternate approach like Layer Normalization or Group Normalization.

How to Verify Whether BatchNorm Is Helping

Don’t judge BatchNorm according to how well it:

“Look at the training loss?”

Look at what it does for your model.

MetricBaselineWith BatchNorm
Initial training lossMeasureMeasure
Epochs to target validation metricMeasureMeasure
Final training lossMeasureMeasure
Final validation lossMeasureMeasure
Validation metricMeasureMeasure
Stability across runsMeasureMeasure
Inference behaviorMeasureMeasure

An effective conclusion is clear:

Use of BatchNorm decreased the number of epochs required to achieve the target validation loss in the given training setup.

An ineffective conclusion is:

The use of BatchNorm improves the model.

The former is a conclusion based on a measurement. The latter omits both metric and experimental setup.

A Practical BatchNorm Decision Framework

Use this six-step process before adding or removing BatchNorm.

Step 1 — Identify the architecture

Identify if the model used is mainly:

  • convolutional,
  • completely connected,
  • recurrent,
  • transformer,
  • generative,
  • or any other model.

Step 2 — Identify the effective batch

Identify the number of instances that really contribute to the BatchNorm statistics.

Step 3 — Inspect the training environment

Check:

  • single device training,
  • multiple device training,
  • distributed training,
  • synchronized statistics,
  • gradient accumulation,
  • different batch sizes.

Step 4 — Verify inference behavior

Ensure that the framework implements the intended behavior of the running statistics when evaluated.

Step 5 — Compare alternatives if necessary

When batch dependence is not appropriate, try a normalization procedure with a different statistical foundation.

Step 6 — Measure the outcome

Compare validation accuracy, convergence, stability, and inferencing properties through an experiment.

The Explanation in One Example

Suppose a network produces:

[2, 4, 6, 8]

BatchNorm:

  1. calculates the batch mean (5),
  2. calculates the batch variance (5),
  3. standardizes the values,
  4. applies learned (\gamma) and (\beta),
  5. and, during training, updates running statistics for later evaluation.

The key relationship is:

[
\boxed{
y=
\gamma
\frac{x-\mu_B}
{\sqrt{\sigma_B^2+\epsilon}}
+\beta
}
]

The equation tells you what BatchNorm calculates. The training/inference distinction tells you which statistics it uses. The batch-size consideration tells you when those statistics may become unreliable. The framework implementation tells you how those rules behave in actual code. That is the complete mental model.

What Changes Over Time?

The definition of BatchNorm in mathematics is relatively stable. But frameworks’ default definitions are not.

If this article remains a technical source of information, check out:

  • PyTorch BatchNorm APIs,
  • Keras BatchNormalization APIs,
  • default epsilon,
  • momentum semantics,
  • distributed BatchNorm behavior,
  • new normalization layers,
  • framework training/evaluation behavior,
  • and code examples.

Do not update the article just because a calendar year ended. Instead, update the article when the behavior or the API has changed in the framework, or when there is new documentation. When using code samples, make sure that they are checked with the latest framework documentation.

Frequently Asked Questions

Q1. What is Batch Normalization in deep learning?

Ans. Batch Normalization refers to the process of normalizing activations based on batch statistics and applying learnable scale and shift transformations in neural networks. This operation uses running statistics for evaluation.

Q2. What is the BatchNorm formula?

Ans. The standard transformation is:
[
\hat{x}=
\frac{x-\mu_B}
{\sqrt{\sigma_B^2+\epsilon}}
]
followed by:
[
y=\gamma\hat{x}+\beta
]

Q3. Why is BatchNorm used?

Ans. BatchNorm may facilitate optimization for appropriate network architectures. According to the paper on BatchNorm, it allowed higher learning rates and made initialization less sensitive.

Q4. What are gamma and beta?

Ans. (\gamma) is the learnable scale parameter. (\beta) is the learnable shift parameter.

Q5. What is epsilon in BatchNorm?

Ans. The Epsilon value is a very small constant that gets added to the variance prior to division.

Q6. Does BatchNorm use the same statistics during training and inference?

Ans. Usually not. The training stage employs batch statistics, whereas inference utilizes running statistics.

Q7. Is BatchNorm the same as input normalization?

Ans. No. Normalization of inputs is pre-processing. BatchNorm runs within the neural network on activations.

Q8. Does BatchNorm always improve model performance?

Ans. False. Its performance is dependent upon architecture, data, batch processing, and training.

Q9. What happens with very small batches?

Ans. Batch statistics can be noisy. It is unclear whether this makes BatchNorm inappropriate for certain models and training procedures.

Q10. Should BatchNorm come before or after ReLU?

Ans. A common pattern is: Convolution/Linear → BatchNorm → ReLU but architecture-specific designs can use different ordering.

Q11. Is BatchNorm a regularization technique?

Ans. The BatchNorm method does have some regularizing impact; however, its main role lies in normalization, and its optimization properties should not be limited to this.

Q12. Which is better: BatchNorm or LayerNorm?

Ans. Neither one can be said to be universally better than the other since they work differently due to different statistical calculations.

Final Takeaway

Batch Normalization should be seen more as a normalized learning technique within the neural network, rather than any data preprocessing technique.

The main operation performed by Batch Normalization is:

[
y=
\gamma
\frac{x-\mu_B}
{\sqrt{\sigma_B^2+\epsilon}}
+\beta
]

To use it correctly, understand four relationships:

  1. Activation → batch statistics → normalized activation
  2. Normalized activation → (\gamma,\beta) → learned representation
  3. Training batch statistics → running statistics → inference
  4. Batch regime → statistical reliability → architectural choice

When you see unusual behavior of your BatchNorm model, you should first investigate the following aspects: the mode of your network (training/evaluation), batch size, running means and variances, distribution, framework defaults, and other normalizations before going ahead and changing the architecture.

The point is not to use BatchNorm because it is popular. The point is to use the normalization method that you can understand and validate for your particular network.

Shalki Aggarwal is a Software Engineer II at Microsoft and an AI & Data Science expert specializing in Generative AI, Agentic AI, Python, LangChain, LangGraph, CrewAI, Deep Agents, and Loop Engineering. She is also a corporate trainer for leading organizations including L&T, Bharat Petroleum, Luminous, Denso, and Toshiba Midea, helping teams apply AI and emerging technologies to real-world business challenges.