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.
def 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.