Apply batch norm to conv feature maps per channel

Why it matters Every BatchNorm2d layer in ResNet-style CNNs pools statistics exactly this way.

In a CNN, batch norm computes one mean and variance per channel, pooled over the batch AND all spatial positions.

Write batchnorm2d(x, gamma, beta, eps=1e-5). x is (N, C, H, W); gamma and beta are (C,). For each channel, compute the mean and the biased variance over axes (0, 2, 3), normalise, then return gamma * x_hat + beta with the same shape as x.

Signaturedef batchnorm2d(x, gamma, beta, eps=1e-5)

Example

x of shape (2, 1, 1, 2) with values [[[[1, 3]]], [[[5, 7]]]], gamma = [1], beta = [0] gives about [[[[-1.3416, -0.4472]]], [[[0.4472, 1.3416]]]].

Understand the idea

A conv channel detects one kind of pattern everywhere in the image, so all its positions share one scale. Batch norm for images therefore treats every pixel of every image in the batch as one big sample for that channel. Picture grading all students in all classrooms on one curve per subject.

Tiny example: one channel holding 1, 3 in image 1 and 5, 7 in image 2. Mean 4, variance (9 + 1 + 1 + 9) / 4 = 5, std 2.236. So 1 becomes -1.342 and 7 becomes 1.342.

Rule: mean_c, var_c over (N, H, W); y = gamma_c * (x - mean_c) / sqrt(var_c + eps) + beta_c.

ResNet, EfficientNet and most CNN backbones put this after each convolution.

Shapes and data flow

x (N,C,H,W) -> mean, var (1,C,1,1) -> y (N,C,H,W)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplebatchnorm2d(np.array([[[[1.0, 3.0]]], [[[5.0, 7.0]]]]), [1.0], [0.0])
  • Sample 2: two channelsbatchnorm2d(X, [1.0, 2.0], [0.0, -1.0])
  • Test 3: constant channelbatchnorm2d(np.ones((2, 1, 2, 2)), [3.0], [0.5])