Level 3 In-Depth AI · Deep Learning
Weight Initialization
Before training starts, every weight needs a value. Make them all equal and the neurons can never become different; make them too small or too large and signals fade or explode through the layers. Xavier and He initialisation pick the size that keeps signals steady.
- Level
- ●●●●● Intermediate
- Reading
- 13 min
- To learn it well
- 45 minutes to read, an hour to practise
- Builds on
- 16 concepts →
- Quiz
- 4 questions ↓
Read first
BackpropagationThis leads to
—The full path from zero — 16 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Backpropagation
- Weight Initialization
Read them roughly in this order. See it on the concept map →
Why it matters
Training a neural network starts from some set of weights and improves them step by step. It's natural to assume that the starting point hardly matters, since training will move away from it anyway. For shallow networks that is roughly true. For deep ones it is badly wrong.
Start every weight at the same value and the network can never learn more than one feature per layer, however long you train. Start with weights that are a little too small and, 20 layers later, the signal has faded to nothing; a little too large and it has exploded. Both break Backpropagation before training has properly begun (see Vanishing and Exploding Gradients).
Weight initialization is the choice of those starting values. The fix is a short formula, now built into every deep-learning library, and it was one of the key ingredients that made very deep networks trainable in the early 2010s. Knowing it lets you understand what nn.Linear does behind the scenes, and why a custom layer that ignores it can quietly ruin a model.
The intuition
Two separate problems have to be solved.
Break the symmetry. Imagine a team of identical twins, all given the same instructions and the same feedback. They will always do exactly the same thing, and the team is no better than one person. Neurons in a layer are the same. If they start with the same weights, they compute the same output, receive the same gradient and make the same update, forever. Random starting values make each neuron different from the start, so each can specialise.
Get the scale right. Think of a long chain of amplifiers, each feeding the next. If each one turns the volume down slightly, the music fades to silence by the end of the chain. If each turns it up slightly, it ends as a deafening screech. Only if each amplifier keeps the volume about the same does the music arrive intact. Each layer of a network is an amplifier for the signal going forward and for the gradient coming back. Initialisation sets every amplifier to "unity gain".
Key idea Initialise weights randomly, to break symmetry, with variance about (Xavier, for tanh and linear layers) or (He, for ReLU), where is the number of inputs to the layer. That keeps the size of signals and gradients roughly constant from layer to layer.
How it works
Symmetry breaking
Take a layer with two hidden neurons that start with identical weights. They receive the same inputs, so they compute the same output. The weights connecting them to the next layer are also equal, so Backpropagation sends them the same gradient. They get the same update and remain identical. The same holds at the next step, and every step after. Training can't separate them.
Here's a real run. A network with 4 hidden neurons is trained on XOR (from Neural Networks) for 5,000 steps. With every weight starting at 0.5, the four hidden neurons end with identical weights of 7.053, and the loss is stuck at 0.481, because four clones are as good as one neuron and one neuron can't solve XOR. With random starting weights, the hidden neurons end up completely different from one another and the loss reaches 0.002.
This is why weights must be random. Biases, on the other hand, are usually started at zero. Once the weights differ, the neurons are already distinct.
Why scale matters: a variance calculation
Now for the size. A neuron computes the weighted sum . The number of inputs is called its fan-in. Suppose the inputs and weights are independent random numbers with mean zero. A basic fact of statistics says that variances of independent terms add, and the variance of a product of two independent zero-mean numbers is the product of their variances. So
Variance measures the spread of a set of numbers: the average squared distance from the mean. The spread you'd see on a histogram is its square root, the standard deviation.
Each layer therefore multiplies the variance of the signal by . For a layer with inputs:
- With weights of standard deviation 1, the factor is . After just 3 layers the variance has grown by million.
- With standard deviation 0.01, the factor is . Each layer shrinks the variance about 20-fold. After 10 layers it is down by about .
- With , the factor is exactly 1. The variance stays put.
That last choice is the whole idea: set , so each layer has unity gain. This is called variance preservation.
Xavier (Glorot) initialisation
The backward pass has the same problem in reverse. There, each layer multiplies the gradient's variance by , where the fan-out is the number of neurons in the layer. When you can't satisfy both exactly, so Xavier Glorot and Yoshua Bengio (2010) proposed the compromise
That's Xavier initialisation (also called Glorot). For a square layer it equals . It can be drawn from a normal distribution with that variance, or from a uniform distribution between and with (a uniform distribution on has variance , which gives the same variance).
Xavier assumes the activation function behaves roughly like the identity near zero. That fits tanh, and sigmoid with some adjustment. For a 512 × 512 layer, the standard deviation is .
He (Kaiming) initialisation
ReLU breaks Xavier's assumption. It sets every negative input to zero, which on average throws away half of the signal's power: the average of is half the average of . To make up for it, double the variance:
That's He initialisation (also called Kaiming, after Kaiming He, who proposed it with colleagues in 2015). For our 512-input layer the standard deviation is .
You can see the difference by pushing random data through 50 ReLU layers of width 512 and measuring the spread (standard deviation) of the activations:
| Initialisation | Spread at layer 1 | Layer 10 | Layer 50 |
|---|---|---|---|
| std 0.01 | 0.132 | ||
| Xavier, | 0.585 | 0.028 | |
| He, | 0.827 | 0.923 | 0.680 |
Xavier with ReLU loses half the variance at each layer, so its spread falls by about per layer. That's slow but relentless: after 50 layers it's down by a factor of about 20 million. He initialisation holds steady.
For tanh, Xavier keeps the spread reasonable (0.628 at layer 1, 0.228 at layer 10, 0.101 at layer 50). It still shrinks slowly, because tanh's slope is below 1 everywhere except at zero, so each layer loses a little.
What libraries do
Every layer in a modern library comes with an initialisation built in. In PyTorch, nn.Linear and nn.Conv2d draw weights uniformly from by default, which gives a standard deviation of : 0.026 for 512 inputs. That's smaller than both Xavier and He. It works well in networks that contain normalisation layers, which reset the scale anyway, but on a deep plain ReLU stack it makes signals shrink, as the Vanishing and Exploding Gradients experiment showed. You can choose explicitly with torch.nn.init.
Large models add a few refinements:
- Scaled residual branches. In a network with residual connections, each block adds its output to a running sum. With blocks the variance of the sum can grow with . GPT-2 scaled the initial weights of each residual block's output layer by to compensate. Some ResNet recipes start the last normalisation scale in each block at zero, so every block initially does nothing and the network starts out as a shallow one.
- Small fixed scales. Many Transformer codebases simply use a normal distribution with standard deviation 0.02 for most weights, a choice inherited from GPT-2.
- Orthogonal initialisation sets a square weight matrix to a random rotation, which preserves the length of every vector exactly. It is sometimes used for recurrent networks.
- Pretrained weights. The best initialisation of all is often a network already trained on a related task. That's Transfer Learning, and Fine-Tuning large language models is the same idea.
Initialisation and normalisation
Normalisation layers rescale activations inside the network at every step, so they make networks far less sensitive to initialisation. With BatchNorm or LayerNorm in every block, even mediocre initialisation usually trains. That doesn't make initialisation irrelevant: the symmetry still has to be broken, residual sums still grow, and the very first steps still depend on the starting scale.
In code
How the spread of activations evolves through 50 layers for different starting sizes, in NumPy:
import numpy as np
rng = np.random.default_rng(0)
x = rng.normal(size=(1000, 512)) # 1,000 inputs with 512 features each
def spread(act, std_fn, depth=50, width=512):
h, out = x, {}
for layer in range(1, depth + 1):
W = rng.normal(0, std_fn(width), size=(width, width))
h = act(h @ W)
if layer in (1, 10, 50):
out[layer] = h.std()
return out
relu = lambda z: np.maximum(0, z)
for name, act, std_fn in [("relu, std 0.01 ", relu, lambda n: 0.01),
("relu, Xavier 1/n ", relu, lambda n: np.sqrt(1 / n)),
("relu, He 2/n ", relu, lambda n: np.sqrt(2 / n)),
("tanh, std 0.01 ", np.tanh, lambda n: 0.01),
("tanh, Xavier 1/n ", np.tanh, lambda n: np.sqrt(1 / n)),
("tanh, std 0.2 ", np.tanh, lambda n: 0.2)]:
s = spread(act, std_fn)
print(f"{name} spread at layer 1: {s[1]:.3g} 10: {s[10]:.3g} 50: {s[50]:.3g}")
# relu, std 0.01 spread at layer 1: 0.132 10: 7.97e-09 50: 9e-41
# relu, Xavier 1/n spread at layer 1: 0.585 10: 0.0278 50: 3.05e-08
# relu, He 2/n spread at layer 1: 0.827 10: 0.923 50: 0.68
# tanh, std 0.01 spread at layer 1: 0.216 10: 3.31e-07 50: 5.3e-33
# tanh, Xavier 1/n spread at layer 1: 0.628 10: 0.228 50: 0.101
# tanh, std 0.2 spread at layer 1: 0.909 10: 0.899 50: 0.9
The last line looks healthy but isn't: a spread of 0.9 for tanh, whose outputs lie between −1 and 1, means almost every neuron is pinned near ±1, in the flat region where gradients vanish.
The symmetry experiment:
import numpy as np
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=float)
y = np.array([[0], [1], [1], [0]], dtype=float) # XOR
sigmoid = lambda z: 1 / (1 + np.exp(-z))
def train(W1, W2, steps=5000, lr=1.0):
b1, b2 = np.zeros(W1.shape[1]), np.zeros(1)
for _ in range(steps):
H = sigmoid(X @ W1 + b1); p = sigmoid(H @ W2 + b2)
dZ2 = (p - y) / 4; dZ1 = (dZ2 @ W2.T) * H * (1 - H)
W2 -= lr * H.T @ dZ2; b2 -= lr * dZ2.sum(0)
W1 -= lr * X.T @ dZ1; b1 -= lr * dZ1.sum(0)
loss = -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))
return loss, W1
same = train(np.full((2, 4), 0.5), np.full((4, 1), 0.5)) # every weight equal
rand = train(np.random.default_rng(0).normal(0, 1, (2, 4)),
np.random.default_rng(1).normal(0, 1, (4, 1))) # random weights
print(f"all weights 0.5: loss {same[0]:.3f}\n hidden weights (one column per neuron):\n{same[1].round(3)}")
print(f"random weights: loss {rand[0]:.3f}\n hidden weights:\n{rand[1].round(3)}")
# all weights 0.5: loss 0.481
# hidden weights (one column per neuron):
# [[7.053 7.053 7.053 7.053]
# [7.053 7.053 7.053 7.053]]
# random weights: loss 0.002
# hidden weights:
# [[ 1.544 -7.533 5.818 -5.323]
# [ 0.308 4.705 5.962 7.794]]
Choosing an initialisation explicitly in PyTorch:
import torch
from torch import nn
torch.manual_seed(0)
layer = nn.Linear(512, 512)
print(f"PyTorch default std {layer.weight.std():.4f}") # uniform in ±1/sqrt(512)
nn.init.xavier_normal_(layer.weight)
print(f"Xavier normal std {layer.weight.std():.4f}") # sqrt(2 / (512 + 512))
nn.init.kaiming_normal_(layer.weight, nonlinearity="relu")
print(f"He (Kaiming) std {layer.weight.std():.4f}") # sqrt(2 / 512)
nn.init.zeros_(layer.bias)
# PyTorch default std 0.0255
# Xavier normal std 0.0442
# He (Kaiming) std 0.0624
To apply one scheme to a whole model, write a function that initialises one module and pass it to model.apply(fn).
Common pitfalls
- Zero or constant weights. Every neuron in the layer stays identical. Biases may start at zero; weights may not.
- Mismatching scheme and activation. Xavier with ReLU shrinks the signal by about per layer, and He with tanh tends to push neurons into saturation. Match He to ReLU-family activations and Xavier to tanh, sigmoid and linear layers.
- Hand-written layers with
torch.randn.torch.randn(512, 512)has standard deviation 1, which is 16 to 22 times too big for a 512-input layer. Always scale it, for example by(2 / fan_in) ** 0.5. - Re-initialising pretrained weights by accident. Calling
model.apply(init_fn)after loading a checkpoint throws away everything the model learned. - Ignoring the output layer. A large initial output layer produces confident, wrong predictions and a huge first loss. For a classifier with classes, the loss at step 0 should be about (2.30 for 10 classes). If it's much higher, the output layer starts too large.
Watch out Check the very first loss before training. For a 10-class classifier it should be close to , the loss of a model that assigns equal probability to every class. A first loss of 20 or 50 means the initial outputs are far too large, and the first steps will be spent undoing that.
Where it leads
- Vanishing and Exploding Gradients: the problem initialisation addresses, alongside ReLU, normalisation and residuals.
- Normalization Layers: BatchNorm and LayerNorm: normalisation layers make networks much less sensitive to the starting scale.
- Residual Connections: why residual branches need their own scaling.
- Transfer Learning and Fine-Tuning: starting from trained weights instead of random ones.
- Training Neural Networks in Practice: checking the initial loss is part of the standard sanity checks.
A bit of history
Early practitioners knew that small random weights worked better than zeros. Yann LeCun and colleagues recommended scaling weights by in their 1998 guide "Efficient BackProp", a choice sometimes called LeCun initialisation. In 2010, Xavier Glorot and Yoshua Bengio studied how activations and gradients behave layer by layer in deep networks, showed why the common sigmoid-plus-small-weights setups failed, and derived the initialisation named after Glorot.
In 2015, Kaiming He, Xiangyu Zhang, Shaoqing Ren and Jian Sun extended the analysis to ReLU (and a learnable variant called PReLU), and trained a 30-layer plain network from scratch with it. The same team introduced residual networks later that year. Andrew Saxe and colleagues analysed orthogonal initialisation in 2013. Since then, normalisation layers and residual connections have made networks more forgiving, but the variance-preserving idea remains the default in every library.
Try it
- In the NumPy experiment, try ReLU with standard deviation (twice He's variance). How large is the spread at layer 50?
- In the symmetry experiment, start the hidden weights at random values but set all output weights
W2to 0.5. Does the network still learn XOR? Why does the symmetry break anyway?- Build a 10-class classifier with
nn.Linear(64, 10)and compute the loss on random inputs before training. Is it close to 2.30? Multiply the layer's weights by 50 and check again.Hint for 2: symmetry is broken as soon as the hidden neurons compute different values. Different hidden activations give different gradients to the output weights.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Understanding the difficulty of training deep feedforward neural networks
Diagnosed why deep nets trained badly, and introduced Xavier/Glorot initialisation.
Delving Deep into Rectifiers
He initialisation for ReLU networks, and the first model to beat human-level ImageNet accuracy.
Dive into Deep Learning
An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.
Stanford CS231n: Deep Learning for Computer Vision
Famous course notes on neural nets, backprop, CNNs and training, written very clearly.
torch.nn.init
Reference for PyTorch's initialisation functions: Xavier, Kaiming (He), orthogonal, normal, uniform and more, with the formulas each uses.
Initializing neural networks
An interactive explainer where you pick an initialisation and watch activations and gradients vanish, explode or stay healthy as a network trains.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/dl/weight-initialization.md