PyTorch torch.nn.BatchNorm2d function
PyTorch torch.nn Reference Manual
torch.nn.BatchNorm2d is the module in PyTorch for two-dimensional batch normalization.
Batch normalization speeds up training and stabilizes convergence by normalizing the inputs to a layer, and is one of the most widely used techniques in modern deep neural networks.
Function definition
torch.nn.BatchNorm2d(num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
Parameter Description:
num_features(int): Number of input channels C.eps(float): A value added to the denominator for numerical stability. Defaults to 1e-5.momentum(float): Used to compute the running mean and variance. Defaults to 0.1.affine(bool): Whether to use learnable affine parameters (gamma and beta). Defaults to True.track_running_stats(bool): Whether to track running statistics. Defaults to True.
property through the following steps:
weight(Tensor): The learnable scaling parameter gamma, with shape (num_features,).bias(Tensor): The learnable offset parameter beta, with shape (num_features,).running_mean(Tensor): The running mean, not updated during training.running_var(Tensor): The running variance, not updated during training.
Mathematical principle
Batch normalization standardizes each channel independently:
y = (x - E[x]) / sqrt(Var[x] + eps) * gamma + beta
where gamma and beta are learnable parameters that allow the network to restore its expressive power.
Usage examples
Example 1: Basic usage
Use batch normalization after a convolutional layer:
Example
import
torch
import
torch.
nn
as
nn
Create a batch normalization layer: 32 channels
bn
=
nn.
BatchNorm2d
(
num_features
=
32
)
Print parameters
(
"gamma (weight):"
,
bn.
weight
.
shape
)
(
"beta (bias):"
,
bn.
bias
.
shape
)
(
"running_mean:"
,
bn.
running_mean
.
shape
)
(
"running_var:"
,
bn.
running_var
.
shape
)
Create input: batch=4, channels=32, height=16, width=16
input_tensor
=
torch.
randn
(
4
,
32
,
16
,
16
)
Forward propagation
output
=
bn
(
input_tensor
)
(
"nInput mean (per channel):"
,
input_tensor.
mean
(
dim
=
(
0
,
2
,
3
)
)
[
:
5
]
.
tolist
(
)
)
(
"Output mean (per channel):"
,
output.
mean
(
dim
=
(
0
,
2
,
3
)
)
[
:
5
]
.
tolist
(
)
)
(
"nInput shape:"
,
input_tensor.
shape
)
(
"Output shape:"
,
output.
shape
)
The output is:
gamma (weight): torch.Size([32])
beta (bias): torch.Size([32])
running_mean: torch.Size([32])
running_var: torch.Size([32])
输入均值 (按通道): tensor([ 0.0234, 0.0456, -0.0123, -0.0345, 0.0567])
输出均值 (按通道): tensor([ 0., 0., 0., 0., 0.])
输入形状: torch.Size([4, 32, 16, 16])
输出形状: torch.Size([4, 32, 16, 16])
During training, the output is normalized to mean 0 and variance 1 (followed by the gamma and beta transformation).
Example 2: Training vs. evaluation mode
Batch normalization behaves differently during training and evaluation:
Example
import
torch
import
torch.
nn
as
nn
bn
=
nn.
BatchNorm2d
(
num_features
=
16
)
Training mode
bn.
train
(
)
(
"Training mode - requires grad:"
,
bn.
weight
.
requires_grad
)
Simulate training
for
_
in
range
(
10
)
:
x
=
torch.
randn
(
8
,
16
,
8
,
8
)
output
=
bn
(
x
)
(
"First 5 of running_mean after training:"
,
bn.
running_mean
[
:
5
]
.
tolist
(
)
)
Evaluation mode
bn.
eval
(
)
(
"nEvaluation mode - requires grad:"
,
bn.
weight
.
requires_grad
)
Use running stats during evaluation
x
=
torch.
randn
(
4
,
16
,
8
,
8
)
output
=
bn
(
x
)
(
"Output shape during evaluation:"
,
output.
shape
)
Example 3: Complete CNN example
A typical CNN structure with batch normalization:
Example
import
torch
import
torch.
nn
as
nn
class
BNConvNet
(
nn.
Module
)
:
def
init
(
self
,
num_classes
=
10
)
:
super
(
BNConvNet
,
self
)
.
init
(
)
Convolution + batch normalization + activation + pooling
self
.
block1
=
nn.
Sequential
(
nn.
Conv2d
(
3
,
32
,
kernel_size
=
3
,
padding
=
1
)
,
nn.
BatchNorm2d
(
32
)
,
nn.
ReLU
(
)
,
nn.
MaxPool2d
(
2
,
2
)
32 -> 16
)
self
.
block2
=
nn.
Sequential
(
nn.
Conv2d
(
32
,
64
,
kernel_size
=
3
,
padding
=
1
)
,
nn.
BatchNorm2d
(
64
)
,
nn.
ReLU
(
)
,
nn.
MaxPool2d
(
2
,
2
)
16 -> 8
)
Global average pooling
self
.
gap
=
nn.
AdaptiveAvgPool2d
(
1
)
self
.
classifier
=
nn.
Linear
(
64
,
num_classes
)
def
forward
(
self
,
x
)
:
x
=
self
.
block1
(
x
)
x
=
self
.
block2
(
x
)
x
=
self
.
gap
(
x
)
x
=
x.
view
(
x.
size
(
0
)
,
1
)
x
=
self
.
classifier
(
x
)
return
x
model
=
BNConvNet
(
)
input_image
=
torch.
randn
(
2
,
3
,
32
,
32
)
output
=
model
(
input_image
)
(
"Input shape:"
,
input_image.
shape
)
(
"Output shape:"
,
output.
shape
)
Print the parameters of the first BN layer
(
"nGamma of the first BN layer:"
,
model.
block1
[
1
]
.
weight
[
:
5
]
.
tolist
(
)
)
(
"Beta of the first BN layer:"
,
model.
block1
[
1
]
.
bias
[
:
5
]
.
tolist
(
)
)
Example 4: Without affine parameters
Disable learnable parameters:
Example
import
torch
import
torch.
nn
as
nn
Batch normalization without learnable parameters
bn_no_affine
=
nn.
BatchNorm2d
(
16
,
affine
=
False
)
(
"Has weight:"
,
bn_no_affine.
weight
is
not
None
)
(
"Has bias:"
,
bn_no_affine.
bias
is
not
None
)
Standardization is still performed
x
=
torch.
randn
(
4
,
16
,
8
,
8
)
output
=
bn_no_affine
(
x
)
(
"nOutput shape:"
,
output.
shape
)
Common questions
Q1: Should batch normalization be placed before or after ReLU?
Both approaches work. The original paper places it after the convolution and before the activation; in practice it is also often placed after the activation.
Q2: What to do when performance is poor with a small batch size?
- Use
GroupNormreplaces - Use
LayerNorm - Increase the batch size
- Adjust the momentum parameter
Q3: Why switch to eval mode during evaluation?
Batch statistics are used during training, and running statistics during evaluation. Forgetting to switch leads to inconsistent outputs.
Use Cases
nn.BatchNorm2d Main application scenarios include:
- Accelerating training: Allows larger learning rates
- Stabilizing convergence: Reduces internal covariate shift
- Regularization: Provides a slight regularization effect
- Image classification: Used by nearly all modern CNNs
Note: Batch normalization requires a sufficient batch size during training; small batches may lead to unstable statistics.