◆ AI All-in-One

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
↗ Plan a path here

Read first

Backpropagation

This leads to

—
The full path from zero — 16 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. The Chain Rule
  9. Supervised, Unsupervised and Reinforcement Learning
  10. Gradient Descent
  11. Supervised Learning
  12. Linear Regression
  13. The Perceptron
  14. Logistic Regression
  15. Neural Networks
  16. Backpropagation
  17. 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".

Too small std 0.01 signals shrink to 0 −1 0 1 spread 0.22 layer 1 −1 0 1 spread 0.00056 layer 5 −1 0 1 spread 3.3e-07 layer 10 Xavier std √(1/n) = 0.044 spread stays healthy −1 0 1 spread 0.63 −1 0 1 spread 0.32 −1 0 1 spread 0.23 Too large std 0.2 neurons stuck at ±1 −1 0 1 spread 0.91 −1 0 1 spread 0.9 −1 0 1 spread 0.9 Histograms of tanh activations in a 10-layer network, 512 neurons per layer (n = 512 inputs to each layer)
Fig. 1 Histograms of activations in a 10-layer tanh network for three starting sizes. With weights that are too small, the activations collapse towards zero by layer 5. With Xavier initialisation they keep a healthy spread. With weights that are too large, almost every neuron is pinned at −1 or +1, where tanh is flat and passes no gradient.

Key idea Initialise weights randomly, to break symmetry, with variance about 1/n1/n (Xavier, for tanh and linear layers) or 2/n2/n (He, for ReLU), where nn 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.

All weights equal 0.5 0.5 0.5 0.5 x₁ x₂ h₁ h₂ ŷ h₁ = h₂ always both hidden neurons compute the same thing, get the same gradient, and stay clones forever Random weights 0.8 −0.4 −1.3 0.9 x₁ x₂ h₁ h₂ ŷ each hidden neuron starts different, so each learns a different feature
Fig. 2 Left: with all weights equal, the two hidden neurons are exact copies of each other and stay that way. Right: random starting weights make the neurons different, so each can learn its own feature.

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 z=w1x1+w2x2+⋯+wnxnz = w_1 x_1 + w_2 x_2 + \dots + w_n x_n. The number of inputs nn 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

Var(z)=n⋅Var(w)⋅Var(x)\text{Var}(z) = n \cdot \text{Var}(w) \cdot \text{Var}(x)

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 n⋅Var(w)n \cdot \text{Var}(w). For a layer with n=512n = 512 inputs:

  • With weights of standard deviation 1, the factor is 512×1=512512 \times 1 = 512. After just 3 layers the variance has grown by 5123≈134512^3 \approx 134 million.
  • With standard deviation 0.01, the factor is 512×0.0001=0.0512512 \times 0.0001 = 0.0512. Each layer shrinks the variance about 20-fold. After 10 layers it is down by about 101310^{13}.
  • With Var(w)=1/512\text{Var}(w) = 1/512, the factor is exactly 1. The variance stays put.

That last choice is the whole idea: set Var(w)=1/nin\text{Var}(w) = 1/n_{\text{in}}, 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 nout⋅Var(w)n_{\text{out}} \cdot \text{Var}(w), where the fan-out noutn_{\text{out}} is the number of neurons in the layer. When nin≠noutn_{\text{in}} \ne n_{\text{out}} you can't satisfy both exactly, so Xavier Glorot and Yoshua Bengio (2010) proposed the compromise

Var(w)=2nin+nout\text{Var}(w) = \frac{2}{n_{\text{in}} + n_{\text{out}}}

That's Xavier initialisation (also called Glorot). For a square layer it equals 1/n1/n. It can be drawn from a normal distribution with that variance, or from a uniform distribution between −a-a and aa with a=6/(nin+nout)a = \sqrt{6/(n_{\text{in}} + n_{\text{out}})} (a uniform distribution on ±a\pm a has variance a2/3a^2/3, 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 1/512=0.044\sqrt{1/512} = 0.044.

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 ReLU(z)2\text{ReLU}(z)^2 is half the average of z2z^2. To make up for it, double the variance:

Var(w)=2nin\text{Var}(w) = \frac{2}{n_{\text{in}}}

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 2/512=0.0625\sqrt{2/512} = 0.0625.

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 8.0×10−98.0 \times 10^{-9} 9×10−419 \times 10^{-41}
Xavier, Var=1/n\text{Var} = 1/n 0.585 0.028 3.1×10−83.1 \times 10^{-8}
He, Var=2/n\text{Var} = 2/n 0.827 0.923 0.680

Xavier with ReLU loses half the variance at each layer, so its spread falls by about 2\sqrt{2} 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 ±1/nin\pm 1/\sqrt{n_{\text{in}}} by default, which gives a standard deviation of 1/3nin1/\sqrt{3 n_{\text{in}}}: 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 NN blocks the variance of the sum can grow with NN. GPT-2 scaled the initial weights of each residual block's output layer by 1/N1/\sqrt{N} 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 2\sqrt{2} 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 KK classes, the loss at step 0 should be about ln⁡K\ln K (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 ln⁡10≈2.30\ln 10 \approx 2.30, 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

A bit of history

Early practitioners knew that small random weights worked better than zeros. Yann LeCun and colleagues recommended scaling weights by 1/nin1/\sqrt{n_{\text{in}}} 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

  1. In the NumPy experiment, try ReLU with standard deviation 4/n\sqrt{4/n} (twice He's variance). How large is the spread at layer 50?
  2. In the symmetry experiment, start the hidden weights at random values but set all output weights W2 to 0.5. Does the network still learn XOR? Why does the symmetry break anyway?
  3. 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.

Check your understanding

4 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Every weight in a hidden layer starts at 0.5. After 5,000 training steps, what do the hidden neurons look like?

  2. A layer has 512 inputs and its weights have standard deviation 1. By what factor does it multiply the variance of the signal?

  3. You use Xavier initialisation in a 50-layer plain ReLU network and find the activations shrinking towards zero. What is the fix?

  4. You write a custom 512 × 512 layer with weights from torch.randn(512, 512) and no scaling. What is the problem?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Paper

Delving Deep into Rectifiers

He et al. · 2015 · Advanced · Free

He initialisation for ReLU networks, and the first model to beat human-level ImageNet accuracy.

Book

Dive into Deep Learning

Zhang, Lipton, Li & Smola · Intermediate · Free

An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.

Docs

torch.nn.init

PyTorch · Intermediate · Free

Reference for PyTorch's initialisation functions: Xavier, Kaiming (He), orthogonal, normal, uniform and more, with the formulas each uses.

Interactive

Initializing neural networks

DeepLearning.AI · Beginner · Free

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