v9.1.1
Menu

Batch Normalization Forward Pass

hardPRONeural NetworksDeep LearningCV: Deep Learning

Implement the forward pass of batch normalization using PyTorch tensors.

Batch normalization normalizes activations across the batch dimension:

x^i=xi−μBσB2+ϵ\hat{x}_i = \frac{x_i - \mu_B}{\sqrt{\sigma_B^2 + \epsilon}} yi=γx^i+βy_i = \gamma \hat{x}_i + \beta

Where:

  • μB=1m∑i=1mxi\mu_B = \frac{1}{m}\sum_{i=1}^{m} x_i (batch mean)
  • σB2=1m∑i=1m(xi−μB)2\sigma_B^2 = \frac{1}{m}\sum_{i=1}^{m} (x_i - \mu_B)^2 (batch variance)
  • γ,β\gamma, \beta are learnable parameters
  • ϵ\epsilon is for numerical stability

In this simplified version, inference mode (training=False) also normalizes with the current batch's mean and variance; no running statistics need to be stored.

Return a float tensor with the same shape as x, with every value rounded to the nearest integer.

Example

Input
x = [[1, 2], [3, 4], [5, 6]]  # batch=3, features=2
gamma = [1, 1]
beta = [0, 0]
training = True
Output
[[-1.0, -1.0], [0.0, 0.0], [1.0, 1.0]]
Reasoning
  • Inputs: x is a batch of m=3m = 3 samples with 2 features each, so each column is one feature measured across the batch. gamma = [1, 1] and beta = [0, 0] are the per-feature scale and shift; training is True.
  • Feature 1 (first column) holds 1,3,51, 3, 5: μB=3\mu_B = 3 and σB2=(−2)2+02+223=83≈2.667\sigma_B^2 = \frac{(-2)^2 + 0^2 + 2^2}{3} = \frac{8}{3} \approx 2.667, so σB2+ϵ≈1.633\sqrt{\sigma_B^2 + \epsilon} \approx 1.633.
  • Normalizing gives 1−31.633≈−1.2247\frac{1-3}{1.633} \approx -1.2247, 3−31.633=0\frac{3-3}{1.633} = 0 and 5−31.633≈1.2247\frac{5-3}{1.633} \approx 1.2247.
  • Feature 2 holds 2,4,62, 4, 6: every value is 1 higher, so μB=4\mu_B = 4, the variance is still 83\frac{8}{3}, and the normalized column is identical. Notice that batch norm erases a constant per-feature offset.
  • With γ=1\gamma = 1 and β=0\beta = 0, yi=x^iy_i = \hat{x}_i. Rounding each value to the nearest integer turns ±1.2247\pm 1.2247 into ±1\pm 1, giving [[-1.0, -1.0], [0.0, 0.0], [1.0, 1.0]]: a 3×23 \times 2 float tensor, the same shape as x, with each column centred on 0.

Constraints

  • x: Input tensor of shape (batch_size, features)
  • gamma, beta: Learnable parameters (features,)
  • training: Boolean for train vs inference mode
  • Return: Normalized output tensor

Learn this in

More from CV: Deep Learning

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.