Compute Xavier and He initialisation scales for dense and conv weights
A network trains well only if activations neither explode nor vanish layer after layer. Xavier and He initialisation pick the spread of the random weights from the layer's fan-in and fan-out. Conv layers count every kernel position, which is the part people forget.
Write init_scale(shape, scheme). shape is a tuple: (out, in) for a dense weight, or (out, in, k1, k2, ...) for a conv weight. Let r = product of shape[2:] (1 for dense). fan_in = in * r, fan_out = out * r.
Return a float:
- "xavier_uniform": the bound a of U(-a, a), a = sqrt(6 / (fan_in + fan_out))
- "xavier_normal": std = sqrt(2 / (fan_in + fan_out))
- "he_uniform": bound a = sqrt(6 / fan_in)
- "he_normal": std = sqrt(2 / fan_in)
def init_scale(shape, scheme)Example
init_scale((4, 2), "he_normal") is 1.0.
Understand the idea
If initial weights are too big, activations blow up layer by layer; too small, and they fade away. Xavier and He initialisation choose the spread of random weights from how many inputs feed each unit (fan_in) and how many units each input feeds (fan_out). For conv weights every kernel position counts as an input, so the receptive field size multiplies both fans. Worked example: conv shape (16, 8, 3, 3). r = 3 * 3 = 9, fan_in = 8 * 9 = 72, fan_out = 16 * 9 = 144. He normal std = sqrt(2 / 72) = sqrt(1 / 36) = 0.1667. Xavier uniform bound = sqrt(6 / (72 + 144)) = sqrt(6 / 216) = 0.1667 too. For a dense (4, 2) weight, He normal std = sqrt(2 / 2) = 1. Rules: Xavier uniform sqrt(6 / (fan_in + fan_out)), Xavier normal sqrt(2 / (fan_in + fan_out)), He uniform sqrt(6 / fan_in), He normal sqrt(2 / fan_in). He suits ReLU networks; Xavier suits tanh or linear layers. Every deep learning framework applies these by default.