Normalize feature maps after convolution
Convolutional neural networks
PyTorch · Class
torch.nn.BatchNorm2d normalizes four-dimensional N×C×H×W inputs independently per channel. It normally tracks running statistics for evaluation and can apply learnable channel-wise scale and bias.
BatchNorm2d normalizes each channel of a four-dimensional tensor across its batch and spatial positions. In training it normally updates per-channel running mean and variance; evaluation then uses those stored estimates, while learnable scale and offset parameters provide the default affine transformation.
class torch.nn.modules.batchnorm.BatchNorm2d(num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True, device=None, dtype=None, *, bias=True)| Name | Type | Description |
|---|---|---|
num_features | int | Number of input channels C in the expected N×C×H×W tensor. |
eps | float | Small value added to the denominator for numerical stability; default 1e-5. |
momentum | float or None | Running-statistics update factor; None selects a cumulative moving average. Default 0.1. |
affine | bool | Whether to learn affine scale and offset parameters. Default True. |
track_running_stats | bool | Whether to retain running mean and variance; default True. |
device | torch.device or None | Optional device for module state initialization. |
dtype | torch.dtype or None | Optional data type for module state initialization. |
bias | bool | Whether to learn an additive bias when affine is enabled. Default True. |
A tensor with the same shape as the input, normalized channel-wise.
import torch
from torch import nn
layer = nn.BatchNorm2d(3)
x = torch.randn(4, 3, 8, 8)
y = layer(x)
print(y.shape) # torch.Size([4, 3, 8, 8])Creates a three-channel spatial batch-normalization layer and applies it to a batch of four 8×8 images.
Convolutional neural networks
Image and video tensors
Inference pipelines
It expects input shaped (N, C, H, W), where num_features must equal C. Statistics are computed independently for each channel over the corresponding N, H, and W values.
Follow-up: What changes in evaluation mode? By default, evaluation uses the running mean and variance accumulated during training; disabling running statistics makes it use batch statistics instead.
During training, the module normally maintains running estimates of each channel's mean and variance. In evaluation mode, those estimates are used to normalize inputs.
Follow-up: How can evaluation use current-batch statistics? Construct the layer with track_running_stats=False, so running estimates are not kept.
eps is added to the denominator to improve numerical stability. momentum controls the running_mean and running_var update, and None selects a cumulative moving average.
Follow-up: What does affine control? When true, the layer has learnable per-channel scale and bias; bias=False suppresses only the additive bias.
torch.nn.BatchNorm1dtorch.nn.BatchNorm3dtorch.nn.LazyBatchNorm2d