BatchNorm with running statistics for inference

BatchNorm normalises each feature across the batch during training and keeps a running average of mean and variance for inference, when batches may be size 1.

Write batchnorm(x, gamma, beta, running_mean, running_var, training, momentum=0.1, eps=1e-5) for x of shape (n, d). Return (y, new_running_mean, new_running_var).
- training: use the batch mean and population variance to normalise; update running = (1 - momentum) * running + momentum * batch_stat (use the population variance for the update too).
- not training: normalise with the running stats and return them unchanged.

Signaturedef batchnorm(x, gamma, beta, running_mean, running_var, training, momentum=0.1, eps=1e-5)

Understand the idea

BatchNorm normalises each feature using the mean and variance of the current batch. At inference you may get a single example, whose variance is zero, so during training BatchNorm also keeps running averages of mean and variance and uses those at test time. Like a shop tracking average daily sales instead of judging from one customer. Worked example, one feature, momentum 0.1, eps tiny: training batch [1, 3] has mean 2 and population variance 1, so y = [-1, 1]. Running mean goes from 0 to 0.9 x 0 + 0.1 x 2 = 0.2. Running var goes from 1 to 0.9 x 1 + 0.1 x 1 = 1.0. At inference, x = 1 gives (1 - 0.2) / sqrt(1.0) = 0.8, and the running stats are returned unchanged. Rule: training uses batch stats, then running = (1 - momentum) running + momentum batch_stat; inference uses running stats; y = (x - mean) / sqrt(var + eps) * gamma + beta. CNNs such as ResNet depend on this.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: training outputbatchnorm(_x, np.ones(2), np.zeros(2), np.zeros(2), np.ones(2), True)[0]
  • Sample 2: running stats updatebatchnorm(_x, np.ones(2), np.zeros(2), np.zeros(2), np.ones(2), True)[1:]
  • Test 3: inference uses running statsbatchnorm([[2.0, 15.0]], np.ones(2), np.zeros(2), np.array([3.0, 20.0]), np.array([4.0, 100.0]), False)[0]