🤖 AI/ML

Batch Normalization

Batch Normalization

A technique that normalizes the inputs of each layer to stabilize training. Speeds up training and helps prevent overfitting.

📖 Detailed Explanation

Batch Normalization (BatchNorm) is a technique published in 2015 by Sergey Ioffe and Christian Szegedy that normalizes the inputs of each layer in a neural network to stabilize and accelerate training. After setting the mean to 0 and the variance to 1 per mini-batch, it applies scaling and shifting with learnable parameters (gamma, beta).

Before BatchNorm appeared, training deep neural networks was difficult due to the Internal Covariate Shift problem. This is a phenomenon in which the input distribution of each layer keeps changing during training, making the weights unstable, and BatchNorm resolved this, enabling the use of higher learning rates and faster convergence.

The core formula of BatchNorm is x_normalized = (x - mean) / sqrt(variance + epsilon), and the final output is y = gamma * x_normalized + beta. During training, batch statistics are used, and during inference, the running mean/variance accumulated during training are used.

In practice, BatchNorm is used as the standard in most computer vision models, such as CNN, ResNet, and EfficientNet. However, when the batch size is small (< 16), or in RNN/Transformer, Layer Normalization or Group Normalization is used instead. Even as of 2024, it is an essential component in image classification, object detection, and more.

💻 Code Example

# PyTorch에서 배치 정규화 사용 예제
import torch
import torch.nn as nn

class ConvBlockWithBatchNorm(nn.Module):
    """
    Conv -> BatchNorm -> ReLU 패턴의 기본 블록
    대부분의 CNN 아키텍처에서 표준으로 사용됩니다.
    """
    def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1):
        super().__init__()
        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, bias=False)
        # bias=False: BatchNorm의 beta가 bias 역할을 하므로 불필요
        self.bn = nn.BatchNorm2d(out_channels)
        self.relu = nn.ReLU(inplace=True)

    def forward(self, x):
        x = self.conv(x)
        x = self.bn(x)
        x = self.relu(x)
        return x

# ResNet 스타일 Residual Block with BatchNorm
class ResidualBlock(nn.Module):
    def __init__(self, channels):
        super().__init__()
        self.conv1 = nn.Conv2d(channels, channels, 3, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(channels)
        self.conv2 = nn.Conv2d(channels, channels, 3, padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(channels)
        self.relu = nn.ReLU(inplace=True)

    def forward(self, x):
        residual = x
        out = self.relu(self.bn1(self.conv1(x)))
        out = self.bn2(self.conv2(out))
        out += residual  # Skip connection
        return self.relu(out)

# 모델 생성 및 학습/추론 모드 전환
model = ResidualBlock(64)

# 학습 모드: 배치 통계 사용 + running stats 업데이트
model.train()
x_train = torch.randn(32, 64, 56, 56)  # batch=32
output_train = model(x_train)

# 추론 모드: running mean/variance 사용
model.eval()
with torch.no_grad():
    x_test = torch.randn(1, 64, 56, 56)  # 단일 이미지도 OK
    output_test = model(x_test)

print(f"학습 출력 shape: {output_train.shape}")
print(f"추론 출력 shape: {output_test.shape}")

🗣️ Say It Like This in Practice

💬 In a Meeting
"If training is unstable, check whether the BatchNorm layer is properly included. Adding BatchNorm after Conv can raise the learning rate by up to 10 times, which greatly improves convergence speed. However, you must call model.eval() during inference."
💬 In an Interview
"BatchNorm was proposed to solve the Internal Covariate Shift problem. After normalizing with the mean and variance of the mini-batch, a linear transformation is applied with the gamma and beta parameters. The key is to use batch statistics during training and running statistics during inference."
💬 In a Technical Discussion
"If the batch size is small, at 8 or below, it's better to use GroupNorm instead of BatchNorm. In situations where you can't use a large batch due to GPU memory constraints, BatchNorm's statistics become unstable and performance drops. And LayerNorm is the standard in Transformers."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Missing model.eval() during inference

If you do not call model.eval() during inference, batch statistics are used, which makes predictions unstable in single-image inference. The problem is especially serious when the batch size is 1.

❌
Using it with small batch sizes

If you use BatchNorm when the batch size is 4 or below, the batch statistics become unstable and performance degrades significantly. When there are memory constraints, such as in medical imaging or high-resolution images, use GroupNorm or LayerNorm.

✅
Correct approach: choose the normalization that fits the situation

Use BatchNorm with CNN + a sufficient batch size (16+), LayerNorm with RNN/Transformer, and GroupNorm with small batches. Set bias=False for Conv layers to remove redundant parameters.

🔗 Related Terms

📚 Learn More