Batch Norm: Standardize, Then Scale and Shift

Neural NetworksMedium+20 XP+15

Batch Norm: Standardize, Then Scale and Shift

As a network trains, every layer's weights shift — so the distribution each layer receives keeps moving under it. Batch norm pins that distribution in place: standardize each feature across the batch, then let the network learn its own scale and shift back.

For each feature j, across the batch:

1normalized = (x - mean[j]) / sqrt(variance[j] + epsilon)
2output = gamma[j] * normalized + beta[j]

Task: write batch_norm(batch, gamma, beta, epsilon) where batch is a list of samples (each a list of features). Return the same shape, rounded to 4 decimal places.

  • Statistics are computed per feature, down the batch — not across the features of one sample.
  • Use the population variance (divide by n).
  • epsilon goes inside the square root.

gamma and beta exist because forcing every layer to zero mean and unit variance would be a real loss of expressiveness. Learning them back means the network can undo the normalization exactly when that helps — it just no longer has to.

mean
6.90
spread
1.11

Subtract the batch mean, divide by the batch spread. Mean 0, spread 1 — every time, at every layer.

Examples

batch = [[1.0, 2.0], [3.0, 4.0]]
gamma = [1.0, 1.0]
beta = [0.0, 0.0]
epsilon = 1e-05
returns [[-1.0, -1.0], [1.0, 1.0]]
batch = [[1.0], [2.0], [3.0]]
gamma = [2.0]
beta = [1.0]
epsilon = 1e-05
returns [[-1.4495], [1.0], [3.4495]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run