Weight initialisation in Deep Learning well explained _ Day 21

Target and observed variances for six seeded Keras initializer draws of 8192 weights each.
Computed float64 sampling check at shape128×64, seed42; no dataset accuracy or convergence benchmark.

Choose the scale · inspect the signal

Weight initialization:
start with the right questions

Connect fan counts to a distribution, check real initializer outputs, and distinguish a useful starting point from a training guarantee.

Complete original retained · Expanded 17 November 2026
Actual Keras construction and sampling; no convergence benchmark.

Initialization sets the starting signal scale

For a Dense kernel in Keras, fan-in is the number of input features and fan-out is the number of output units. Its stored matrix has shape (fan-in, fan-out). Start by recording that shape, activation, bias choice and distribution; changing any of them changes the experiment. Keras Dense uses row-vector x @ kernel. The original column-vector expression z = W a + b instead uses W corresponding to kernel transpose; do not mix their shapes.

With zero biases and independent zero-mean weights, a simple sum suggests a preactivation second moment proportional to fan-in times weight variance times input second moment. This is a motivating approximation, not a universal law for correlated data, nonlinear networks or trained weights.

z = Σᵢ wᵢxᵢ
E[z²] ≈ fan-in × Var(w) × E[x²]
For symmetric z: E[ReLU(z)²] = ½ E[z²]

ReLU has a positive output mean, so its variance is not the same as its second moment. He scaling compensates for the second-moment change under suitable assumptions. It does not ensure that every gradient remains in a good range or that a model will converge faster. The factor two is motivated by ReLU; a leaky ReLU’s negative slope changes the appropriate gain, while ELU does not share the same piecewise-linear calculation. Treat the original variant list as a starting guide, not a universally optimal setting.

Read the original advice with these qualifications

Activations: tanh is odd and zero-centered; sigmoid is not. The original repeated description of both as symmetric should not be used to assume identical signal statistics. Glorot scaling is a starting choice rather than a cure for saturation.

Distribution and conditions: the normal formulas below are idealized variance descriptions. Keras GlorotNormal, HeNormal and LecunNormal use truncated, rescaled sampling, rather than an unbounded Gaussian. SELU’s self-normalizing reasoning also needs architectural and input assumptions; an initializer alone does not enforce it. LeCun uniform initialization exists, despite the original table’s historical guidance.

Orthogonal orientation: the original W Wᵀ = I expression needs shape and gain conditions. For a tall 128×64 Keras kernel with gain one, WᵀW = I₆₄. For a wide 64×128 kernel, W Wᵀ = I₆₄. These finite matrix checks do not establish stable gradients through arbitrary nonlinear layers. PyTorch Linear stores weights in the opposite (output, input) orientation.

Historical “emerging” heading: orthogonal and fan-based variance methods predate 2024. The original section title remains, but it is not evidence that these are newly invented methods. Its VarianceScaling(scale=1, fan_avg, uniform) code is fan-scaled, not depth-aware; the checked configuration exactly matches GlorotUniform with the same seed and shape.

“Dynamic” example: static inspection shows that its reset method runs during construction and scales weights by 1.5 while the module is in training mode. Its forward method does not perform a new adjustment. Multiplying a random weight by 1.5 multiplies variance by 2.25, not 1.5. Resetting trained weights later would discard learned values rather than adapt them through an ordinary optimizer step.

Execution limit: the retained PyTorch class is syntax checked but not executed because Torch is unavailable. Before adopting it, run it in a supported PyTorch environment and check construction, train/eval and optimizer behavior. No new result here depends on that unavailable execution.

Work the fans before drawing a sample

Take 128 input features and 64 output units. Glorot target variance is 2/192 = 0.0104166667. He target variance is 2/128 = 0.015625. LeCun target variance is 1/128 = 0.0078125. For a zero-centered uniform distribution, variance equals the square of its limit divided by three.

w ∼ U(−a, a):   Var(w) = a²/3
Glorot limit = √(6/192) ≈ 0.1767766953
He limit = √(6/128) ≈ 0.2165063509
LeCun uniform limit = √(3/128) ≈ 0.1530931089

The following observed values are from one fixed seed, shape (128,64), float64 and 8,192 sampled weights per initializer. Population-style sample variance uses ddof=0. Observed moments need not equal theoretical targets exactly; this finite check does not prove a distribution or predict training quality.

InitializerTarget varianceObserved varianceObserved mean
GlorotUniform0.01041666670.01054509100.0010842117
GlorotNormal0.01041666670.01056108460.0009845173
HeUniform0.01562500000.01581763650.0013278827
HeNormal0.01562500000.01584162700.0012057825
LecunNormal0.00781250000.00792081350.0008526170
LecunUniform0.00781250000.00790881910.0009389549
Six initializer target variances beside the observed variances of 8192 float64 Keras weights drawn with seed 42.
Computed target and sampled moments. These bars describe weight draws, not model accuracy or convergence. Open the chart for detail.
Var(1.5w) = 1.5² Var(w) = 2.25 Var(w)
With He target 0.015625: scaled target = 0.03515625

For the two orthogonal test shapes, the appropriate Gram identity had maximum absolute error around 1.1×10−15 in this float64 run. This verifies those sampled matrices, not a network’s future training behavior. Integer-seeded repeat calls produced identical arrays in the recorded environment; reproducibility across different versions or hardware is a separate question.

Complete original lesson

Every original passage, repeated recommendation, six Python listings, table cell and mathematical source follows in order. The separate notes above qualify its claims. All five Keras fragments were exercised with explicit setup; the historical PyTorch listing remains unexecuted. Original malformed global style/document metadata is retained inert, while the mathematics is selectable HTML without a new rendering library.





 

Weight Initialization in Deep Learning: Classic and Emerging Techniques

Understanding the correct initialization of weights in deep learning models is crucial for effective training and convergence. This post explores both classic and advanced weight initialization strategies, providing mathematical insights and practical code examples.


Part 1: Classic Weight Initialization Techniques

1. Glorot (Xavier) Initialization

Glorot Initialization is designed to maintain the variance of activations across layers, particularly effective for activation functions like tanh and sigmoid.

Mathematical Formula:

Uniform Distribution:

W∼U(-√(6)√(fan_in+fan_out),√(6)√(fan_in+fan_out))

Normal Distribution:

W∼N(0,2fan_in+fan_out)

Code Example in Keras:


from tensorflow.keras.layers import Dense
from tensorflow.keras.initializers import GlorotUniform, GlorotNormal

# Using Glorot Uniform
model.add(Dense(64, kernel_initializer=GlorotUniform(), activation='tanh'))

# Using Glorot Normal
model.add(Dense(64, kernel_initializer=GlorotNormal(), activation='tanh'))

2. He Initialization

He Initialization is optimized for ReLU and its variants, ensuring that the gradients remain within a good range across layers.

Mathematical Formula:

Uniform Distribution:

W∼U(-√(6fan_in),√(6fan_in))

Normal Distribution:

W∼N(0,2fan_in)

Code Example in Keras:


from tensorflow.keras.initializers import HeUniform, HeNormal

# Using He Uniform
model.add(Dense(64, kernel_initializer=HeUniform(), activation='relu'))

# Using He Normal
model.add(Dense(64, kernel_initializer=HeNormal(), activation='relu'))

3. LeCun Initialization

LeCun Initialization is used for the SELU activation function, maintaining the self-normalizing property of the network.

Mathematical Formula:

Normal Distribution:

W∼N(0,1fan_in)

Code Example in Keras:


from tensorflow.keras.initializers import LecunNormal

# Using LeCun Normal
model.add(Dense(64, kernel_initializer=LecunNormal(), activation='selu'))

Summary Table: Classic Initialization Methods

Initialization Activation Functions Variance (Normal Distribution) Range (Uniform Distribution)
Glorot (Xavier) tanh, sigmoid, softmax, linear 2fan_in+fan_out [-√(6fan_in+fan_out),√(6fan_in+fan_out)]
He ReLU, Leaky ReLU, ELU 2fan_in [-√(6fan_in),√(6fan_in)]
LeCun SELU 1fan_in Not typically used with uniform distribution

Part 2: Emerging Weight Initialization Techniques in 2024

1. Orthogonal Initialization

Orthogonal Initialization involves initializing the weight matrix as orthogonal, which helps maintain variance and prevents the collapse of the magnitude of activations.

Mathematical Explanation:

WWT =I

Code Example in Keras:


from tensorflow.keras.initializers import Orthogonal

# Using Orthogonal Initialization
model.add(Dense(64, kernel_initializer=Orthogonal(), activation='relu'))

2. Scaled Initialization

Scaled Initialization adjusts the scaling factor based on the depth of the network, ensuring that the variance remains stable across very deep networks.

Code Example in Keras:


from tensorflow.keras.initializers import VarianceScaling

# Example of Scaled Initialization
model.add(Dense(64, kernel_initializer=VarianceScaling(scale=1.0, mode='fan_avg', distribution='uniform'), activation='relu'))

3. Dynamic Weight Initialization

Dynamic Weight Initialization involves adjusting the initialization strategy during training, based on the changing distribution of gradients and activations.

Code Example in PyTorch:


import torch
import torch.nn as nn

class DynamicWeightInitLayer(nn.Module):
    def __init__(self, in_features, out_features):
        super(DynamicWeightInitLayer, self).__init__()
        self.linear = nn.Linear(in_features, out_features)
        self.reset_parameters()

    def reset_parameters(self):
        nn.init.kaiming_uniform_(self.linear.weight, a=0, mode='fan_in', nonlinearity='relu')
        if self.training:
            with torch.no_grad():
                self.linear.weight *= 1.5  # Example of dynamic adjustment

    def forward(self, x):
        return self.linear(x)

# Example usage
layer = DynamicWeightInitLayer(128, 64)

Key Notes:

Incorporating the right weight initialization technique is crucial for the stability and performance of deep learning models. While classic methods like Glorot, He, and LeCun initialization are still highly effective and widely used, newer techniques such as Orthogonal Initialization, Scaled Initialization, and Dynamic Weight Initialization are essential for handling the complexities of modern deep learning architectures.

By understanding the mathematical foundations and having the right code snippets ready, you can apply these techniques to ensure that your neural networks start training on the right foot, leading to better and faster convergence.

 

Now let’s explain math behind it a little more :




Understanding the Mathematics Behind Weight Initialization

What is Weight Initialization and Why is it Important?

Weight initialization is the process of setting the initial values for the weights of a neural network before training begins. The choice of these initial values is crucial because it significantly affects how the network learns, how quickly it converges during training, and how effective the model is in generalizing from the training data to unseen data.

Purpose of Weight Initialization:

  1. Avoiding Vanishing/Exploding Gradients: During backpropagation, gradients are calculated to update the weights. If weights are initialized improperly, gradients can either shrink (vanish) or grow exponentially (explode) as they propagate through layers. This can lead to very slow training (vanishing gradients) or cause the network to become unstable and fail to converge (exploding gradients). Proper initialization mitigates these issues, allowing gradients to remain within a reasonable range, which is crucial for effective learning, especially in deep networks.
  2. Ensuring Efficient Learning: Proper initialization allows the network to start with a reasonable range of activations and gradients. This ensures that the learning process is efficient, enabling the network to converge faster and reducing the likelihood of getting stuck in suboptimal regions of the loss landscape.
  3. Preventing Symmetry: If all weights are initialized to the same value (e.g., all zeros), each neuron in a layer will compute the same output and, therefore, have the same gradient during backpropagation. This symmetry prevents the network from learning different features and reduces it to essentially a single neuron per layer. Random initialization helps break this symmetry, ensuring that different neurons can learn different features.

The Mathematics Behind Weight Initialization

Weight initialization strategies are rooted in the need to manage the variance of activations and gradients across layers in a neural network. Here’s a deeper look at the mathematics that underpins these strategies:

1. Variance and Activation Flow:

Consider a neural network layer where the input to layer l is a(l), the weights are W(l), and the biases are b(l). The output of this layer is given by:

z(l+1) =W(l) a(l) +b(l)

and the activation a(l+1) is:

a(l+1) =φ(z(l+1))

where φ is the activation function (like ReLU, sigmoid, or tanh).

Key Mathematical Goal: The variance of the outputs a(l+1) should be roughly the same as the variance of the inputs a(l) to ensure stable gradients and activations throughout the network. This goal is achieved by appropriately scaling the initial weights.

2. Different Initialization Techniques:

  • Glorot (Xavier) Initialization: Glorot Initialization aims to keep the variance of the outputs a(l+1) equal to the variance of the inputs a(l). This method is particularly effective for symmetric activation functions like tanh and sigmoid.

Mathematics:

The variance of the output z(l+1) depends on both the number of inputs (fan-in) and outputs (fan-out) of the layer:

Var(W(l))=2fan_in+fan_out

This formula ensures that the variance of activations remains stable across layers, helping to prevent vanishing/exploding gradients.

  • He Initialization: He Initialization is designed specifically for ReLU and its variants, which are widely used due to their effectiveness in avoiding saturation issues found in sigmoid/tanh. ReLU outputs are zero for half of the input values, so the initialization must account for this reduction in variance.

Mathematics:

The variance of the output z(l+1) with ReLU activation is adjusted to:

Var(W(l))=2fan_in

This method is more aggressive than Glorot initialization, providing larger initial weights to compensate for the ReLU’s tendency to “kill” half of the activations.

  • LeCun Initialization: LeCun Initialization is tailored for SELU (Scaled Exponential Linear Units) activation functions, which have self-normalizing properties, meaning they automatically normalize the output variance during training.

Mathematics:

For SELU activations, it’s important that the variance of the weights is set so that the output variance remains close to 1 across layers:

Var(W(l))=1fan_in

This initialization helps maintain the network’s self-normalizing property, making it highly effective for deep networks with SELU activations.

Application to Algorithms

Weight initialization strategies are applicable across a wide range of deep learning models, including feedforward neural networks, convolutional neural networks (CNNs), and recurrent neural networks (RNNs). The choice of initialization depends on several factors:

1. Activation Function:

  • ReLU or Leaky ReLU: Use He Initialization. This is optimal because ReLU units tend to “kill” half of their input values, requiring a more aggressive initialization to maintain gradient flow.
  • Tanh or Sigmoid: Use Glorot (Xavier) Initialization. These symmetric functions benefit from a balanced variance approach that Glorot initialization provides.
  • SELU: Use LeCun Initialization. SELU activations are designed for self-normalizing neural networks, and LeCun Initialization preserves this property.

2. Network Depth:

  • Shallow Networks: For networks with fewer layers, most initialization methods work reasonably well.
  • Deep Networks: As networks become deeper, the risk of vanishing/exploding gradients increases. He Initialization or Orthogonal Initialization (especially in RNNs) are more suitable to maintain stable gradient flow.

3. Type of Task:

  • Image Classification with CNNs: He Initialization is often preferred due to the prevalent use of ReLU in convolutional layers.
  • Sequence Modeling with RNNs: Orthogonal Initialization is commonly used to maintain the stability of the activations over many time steps.

How to Choose the Right Initialization:

  • Use Glorot Initialization for networks with tanh, sigmoid, or softmax activation functions.
  • Use He Initialization for networks with ReLU or its variants, especially in deep networks where the risk of vanishing gradients is higher.
  • Use LeCun Initialization for networks with SELU activation, particularly in self-normalizing neural networks (SNNs).
  • Consider Orthogonal Initialization for very deep networks or recurrent networks where preserving the magnitude of the activations is crucial.
  • Dynamic or Scaled Initialization might be necessary for extremely deep networks or when standard techniques fail to maintain gradient stability.

Summary

Weight initialization is a crucial step in designing and training neural networks. The choice of initialization strategy depends on the network architecture, the activation functions used, and the specific challenges posed by the model’s depth and complexity. Proper weight initialization helps start the training process on the right foot, leading to better and faster convergence and ensuring that the neural network can learn effectively.

In summary:

  • Glorot Initialization is ideal for symmetric activation functions like tanh and sigmoid.
  • He Initialization is suited for ReLU and its variants, particularly in deep networks.
  • LeCun Initialization is optimal for SELU activations in self-normalizing networks.
  • Orthogonal Initialization is effective in deep and recurrent networks to preserve variance.
  • Dynamic or Scaled Initialization might be necessary for very deep or complex networks.

Understanding these mathematical foundations and their application ensures that your neural networks can be optimized for performance and stability from the very start of training.


Inspect actual draws before training

The complete added procedure below ran with TensorFlow 2.21.0 and Keras 3.15.1. To reproduce its historical-fragment checks, save the six listings above as day21/original-code-1.py through day21/original-code-6.py. It supplies a fresh Sequential model, an explicit 128-feature Input and Dense import for each of the five Keras fragments. Blocks 1 and 2 add two Dense layers, so their second layer has fan-in 64. These are contextual executions, not standalone complete original programs.

Each original Keras model produced finite shape (3,64) outputs without training. The added sampling checks uniform bounds and finite-sample moments, repeated seeded arrays, the fan_avg equivalence and the appropriate Gram identity for two rectangular shapes. All six original snippets and this procedure pass Python syntax parsing; syntax does not establish Torch execution.

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
from pathlib import Path
import ast, json, math, importlib.util
import numpy as np
import tensorflow as tf
import keras
from tensorflow.keras.layers import Dense

r = Path('day21')
original = []
for index in range(1, 6):
    source = (r / f'original-code-{index}.py').read_text()
    ast.parse(source)
    model = keras.Sequential([keras.Input(shape=(128,))])
    context = {'model': model, 'Dense': Dense}
    exec(compile(source, f'original-code-{index}.py', 'exec'), context)
    output = model(np.ones((3, 128), dtype='float32'), training=False).numpy()
    assert output.shape == (3, 64) and np.isfinite(output).all()
    original.append({'block': index, 'dense_layers': len(model.layers),
                     'output_shape': list(output.shape),
                     'parameters': model.count_params()})
ast.parse((r / 'original-code-6.py').read_text())

fan_in, fan_out = 128, 64
specs = [
    ('GlorotUniform', keras.initializers.GlorotUniform, 2/192, math.sqrt(6/192)),
    ('GlorotNormal', keras.initializers.GlorotNormal, 2/192, None),
    ('HeUniform', keras.initializers.HeUniform, 2/128, math.sqrt(6/128)),
    ('HeNormal', keras.initializers.HeNormal, 2/128, None),
    ('LecunNormal', keras.initializers.LecunNormal, 1/128, None),
    ('LecunUniform', keras.initializers.LecunUniform, 1/128, math.sqrt(3/128)),
]
samples = []
for name, factory, target, limit in specs:
    initializer = factory(seed=42)
    w = initializer((fan_in, fan_out), dtype='float64').numpy()
    repeated = initializer((fan_in, fan_out), dtype='float64').numpy()
    assert np.array_equal(w, repeated)
    if limit is not None:
        assert np.abs(w).max() <= limit
    observed = float(w.var())  # Population convention, ddof=0.
    assert abs(observed/target - 1) < 0.08
    samples.append({'name': name, 'target_variance': target,
                    'sample_variance': observed, 'sample_mean': float(w.mean()),
                    'uniform_limit': limit, 'sample_size': w.size})

g = keras.initializers.GlorotUniform(seed=42)((128,64), dtype='float64').numpy()
v = keras.initializers.VarianceScaling(
    scale=1.0, mode='fan_avg', distribution='uniform', seed=42
)((128,64), dtype='float64').numpy()
assert np.array_equal(g, v)
orthogonal = []
for shape in [(128,64), (64,128)]:
    w = keras.initializers.Orthogonal(seed=42)(shape, dtype='float64').numpy()
    gram = w.T @ w if shape[0] >= shape[1] else w @ w.T
    error = float(np.max(np.abs(gram - np.eye(min(shape)))))
    assert error < 1e-12
    orthogonal.append({'shape': list(shape), 'gram_relation':
        'W.T @ W = I' if shape[0] >= shape[1] else 'W @ W.T = I',
        'max_abs_error': error})
result = {'tensorflow': tf.__version__, 'keras': keras.__version__,
          'original_keras': original, 'samples': samples,
          'variance_scaling_matches_glorot_uniform': True,
          'orthogonal': orthogonal,
          'torch_available': importlib.util.find_spec('torch') is not None,
          'scope': 'Five original Keras fragments with explicit model/input/Dense '
                   'context, forward inference only. Seeded initializer sampling '
                   'and matrix checks, not training or performance benchmarks. '
                   'Original PyTorch block syntax only; Torch runtime unavailable.'}
(r/'runtime-result.json').write_text(json.dumps(result, indent=2))
print(json.dumps(result, indent=2))

These checks establish construction, sampling and matrix arithmetic in this environment. They do not fit data or compare convergence speed, generalization, memory or task accuracy. Independent arithmetic and a separate actual replay agreed with the recorded result. If training is unstable, inspect per-layer activations and gradients, then change one relevant setting and compare a controlled run.

Primary references

Primary sources checked 17 November 2026. Their training results are not reproduced here. The preserved 2024 wording is historical; use current implementation documentation and the recorded environment when adapting its code.

Questions about initialization

Does initialization guarantee stable gradients?

No. Fan-based scaling uses assumptions about inputs, weights and activations. It is a useful starting point; inspect signals and gradients in the actual architecture rather than expecting guaranteed convergence.

Is sigmoid a zero-centered symmetric activation?

No. Sigmoid satisfies sigma(-z) = 1 – sigma(z) and has outputs between zero and one. Tanh is odd and zero-centered; treating their signal behavior as identical is misleading.

Does the original VarianceScaling example adapt to network depth?

No. Its scale of one, fan_avg mode and uniform distribution use the fan average. It matches GlorotUniform for the checked shape and seed; the code does not read depth or training statistics.

Does every rectangular orthogonal matrix satisfy W W transpose = I?

No. With Keras kernel shape (128,64), columns are orthonormal and W transpose W equals I64. With shape (64,128), rows are orthonormal. Gain and tensor orientation must be stated.

Does the original dynamic PyTorch layer adapt during every forward pass?

No. Its reset method is called during construction, where it may multiply the newly initialized weights by 1.5. Forward only calls the linear layer. This is static source inspection; Torch execution was unavailable.

Which examples were actually executed?

All five original Keras fragments ran with explicit untrained model/input/import context and forward inference. The new seeded sampling and matrix checks ran in TensorFlow/Keras. The original PyTorch block was syntax checked but not executed; no training or convergence benchmark was performed.

Leave a reply

Your email address will not be published. Required fields are marked *

You Can Also Learn Deep Learning in 80 Days Inside the iOS App Continue this roadmap in a focused mobile study experience with offline access, flashcards, notes, and progress tracking.
Open on the App Store