Python / Python Deep Learning and Neural Networks Interview Questions
What are the differences between Batch Norm, Layer Norm, Group Norm, and Instance Norm?
All normalisation variants compute mean and variance and apply the same transformation (x-μ)/√(σ²+ε) — they differ only in which dimensions the mean and variance are computed over. This seemingly small difference has large practical consequences depending on the architecture and batch size.
| Method | Normalises over | Best for | Key limitation |
|---|---|---|---|
| BatchNorm | Batch + spatial dims per channel | CNNs, large batch MLP | Breaks with batch_size=1; train/eval difference |
| LayerNorm | All features per sample | Transformers, NLP, RNNs | Slower than BN on large spatial dims |
| InstanceNorm | Spatial dims per channel per sample | Style transfer, GAN | Loses channel statistics |
| GroupNorm | Spatial dims per group of channels per sample | Object detection, small batch | Requires choosing n_groups |
import torch
import torch.nn as nn
# BatchNorm1d: normalise over batch for FC layers
# Input: (N, C) or (N, C, L)
bn = nn.BatchNorm1d(num_features=128)
# LayerNorm: normalise over feature dim(s) — no dependency on batch
# Input: (*, normalized_shape) — last dims are normalised
ln = nn.LayerNorm(normalized_shape=128) # used in transformers
ln_2d = nn.LayerNorm([128, 8, 8]) # can normalise spatial too
# GroupNorm: split channels into groups, normalise per group per sample
# Input: (N, C, *) — C must be divisible by num_groups
gn = nn.GroupNorm(num_groups=8, num_channels=128)
# InstanceNorm: each sample, each channel independently
inst = nn.InstanceNorm2d(num_features=128)
# Example: why LayerNorm is used in transformers
d_model = 512
x = torch.randn(4, 20, d_model) # (batch, seq_len, d_model)
# BatchNorm would normalise over batch and seq_len per feature dim —
# unstable at inference when batch=1 (as in autoregressive generation)
# LayerNorm normalises over d_model for each (batch, seq) position independently
print(ln(x).shape) # (4, 20, 512) — each position normalised independently
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
