AI Logic

Weight Initialization

LeCun Initialization

Updated:

On the left, a graph of the recommended sigmoid f(y) = 1.7159 tanh(2y/3) and the distribution N(0, 1) of the first layer's weighted sum y under LeCun initialization, with the points f(±1) = ±1 marked. On the right, a graph of the output variance as layers are stacked (log-scale vertical axis): LeCun initialization (σ_w² = 1/m) goes from 0.75 to 0.38 at layer 30, σ_w² = 4/m stays at about 1.75, and σ_w² = 1/(4m) shrinks by about 1/3 per layer to about 2.1×10^−15 at layer 30

Background and overview

LeCun initialization is a weight initialization method that draws each unit's weights from a distribution with mean 0 and standard deviation σw=m−1/2\sigma_w = m^{-1/2} (mm is the number of inputs connected to the unit, the fan-in). In terms of variance, it is 1/m1/m. Yann LeCun et al. presented it in the 1998 tutorial paper "Efficient BackProp" as one of the tricks for making backpropagation work well.

The key point of this method is not to set the weight scale in isolation but to align three things: input normalization, the activation function, and weight initialization.

  1. Normalize the inputs to mean 0 and variance 1.
  2. Use a sigmoid symmetric around 0 as the activation function: f(x)=1.7159tanh⁡(23x)f(x) = 1.7159 \tanh\left(\frac{2}{3}x\right).
  3. Draw weights with standard deviation m−1/2m^{-1/2} so that the weighted sum has standard deviation 1.

With this setup, most weighted sums fall in the nearly linear range of the sigmoid (around −1-1 to 11), and the outputs are also on the order of 1. Weights that are too large saturate the sigmoid and shrink the gradient, while weights that are too small make the gradient itself small, so this initialization aims for the middle ground.

The left side of the figure at the top shows the recommended sigmoid and the distribution of the weighted sum under LeCun initialization. The right side shows a calculation of how the output variance changes as layers are stacked, for different weight standard deviations.

Theory (choosing the weight standard deviation)

This section walks through the reasoning in Sections 4.3–4.6 of the paper.

  1. Normalize the inputs (Section 4.3): Over the whole training set, bring the mean of each input variable close to 0 and equalize the variances (covariances CiC_i in the paper). To match the recommended sigmoid, a variance of 1 is said to work well. If possible, also decorrelate the inputs.
  2. Use the recommended sigmoid (Section 4.4): Use the following function. f(x)=1.7159tanh⁡(23x)f(x) = 1.7159 \tanh\left(\frac{2}{3}x\right) The constants are chosen to satisfy three conditions: (a) f(±1)=±1f(\pm 1) = \pm 1, (b) the second derivative is maximal at x=±1x = \pm 1, and (c) the effective gain over the range used is close to 1. Therefore, if the input variance is 1, the output variance is also close to 1.
  3. Write the standard deviation of the weighted sum (Section 4.6): If the inputs yjy_j to unit ii are uncorrelated with variance 1, the standard deviation of the weighted sum is as follows (Eq. (14)). σyi=(∑jwij2)1/2\sigma_{y_i} = \left(\sum_j w_{ij}^2\right)^{1/2}
  4. Choose weights that make the standard deviation 1: The expected sum of the squares of mm weights is mσw2m\sigma_w^2, so making it 1 requires the following (Eqs. (15)(16)). σw=m−1/2(Var[w]=1m)\sigma_w = m^{-1/2} \qquad \left(\mathrm{Var}[w] = \frac{1}{m}\right)

The shape of the distribution is not fixed; the paper gives the uniform distribution as an example. A uniform distribution with standard deviation m−1/2m^{-1/2} spans ±3/m\pm\sqrt{3/m}. For example, for a unit with 100 inputs, the standard deviation is 0.10.1, or the range ±0.173\pm 0.173 for a uniform distribution.

The formula in step 3 is the same starting point as the derivations of He initialization and Xavier initialization. He initialization compensates for ReLU halving the variance and sets it to 2/m2/m, while Xavier initialization also accounts for backpropagation and uses 2/(nin+nout)2/(n_{in}+n_{out}). LeCun initialization corresponds to the case of only the forward pass, with an activation gain assumed to be 1.

Why training goes more smoothly

The reason is that training can start in the sigmoid's "sweet spot". A sigmoid is nearly a straight line near 0 and flattens out as the input grows (saturation).

  • When weights are too large: Many weighted sums land in the flat region, and the slope (derivative) of the sigmoid is nearly 0. Because the slope that multiplies the gradient during backpropagation is small, training slows down.
  • When weights are too small: All weighted sums cluster near 0. The gradient also becomes small, and the paper says that starting with weights that are too small should be avoided because the error surface is very flat near 0.
  • With LeCun initialization: The weighted sums spread with standard deviation 1 and fall into the nearly linear range. The paper explains that in this case (1) the gradients are large enough for learning to proceed, and (2) the network learns the linear part of the mapping first and the harder nonlinear part afterward.

The right side of the figure at the top computes the output variance of each layer, assuming every layer is wide enough that the weighted sums follow a normal distribution (this is not a calculation from the paper). With LeCun initialization (σw2=1/m\sigma_w^2 = 1/m), the output variance is about 0.75 at layer 1 and still about 0.38 at layer 30. Halving the standard deviation (σw2=1/(4m)\sigma_w^2 = 1/(4m)) shrinks it to about 1/3 per layer, vanishing to about 2.1×10−152.1 \times 10^{-15} by layer 30. Doubling the standard deviation (σw2=4/m\sigma_w^2 = 4/m) stops the variance at about 1.75, but most weighted sums are then in the flat region of the sigmoid.

As an analogy, it is like setting a volume knob to the middle: loud enough to hear, but not so loud that the speaker distorts (saturates).

Use with SELU and self-normalizing networks

In the paper, LeCun initialization is presented as a "trick" without numerical experiments on initialization. Today, its name comes up most often as the initialization for self-normalizing networks (SNNs) that use SELU.

SELU is an activation function designed so that each layer's output naturally approaches mean 0 and variance 1 as layers are stacked, and this property assumes a weight variance of 1/n1/n (nn is the number of inputs). The documentation of PyTorch's nn.SELU also says that when initializing with kaiming_normal_, nonlinearity="linear" should be used rather than nonlinearity="selu"; this amounts to a weight variance of 1/n1/n, that is, LeCun initialization.

Practical caveats

PyTorch has no function named something like lecun_normal_. nn.init.kaiming_normal_(w, mode="fan_in", nonlinearity="linear") gives a normal distribution with standard deviation 1/m1/\sqrt{m}. If nonlinearity is omitted, the default "leaky_relu" (a=0, i.e., the same gain 2\sqrt{2} as ReLU) is used, resulting in He initialization with variance 2/m2/m, so always specify "linear".

Keep the following points in mind as well.

  • It only makes sense with all three aligned: The paper assumes two things: normalized inputs and the recommended sigmoid. Without input normalization, the standard deviation of the first layer's weighted sum is not 1.
  • It does not suit ReLU: ReLU sets negative inputs to 0, so with variance 1/m1/m the variance roughly halves at each layer. Use He initialization for ReLU and its relatives.
  • It does not consider backpropagation: Since mm uses only the number of inputs (fan-in), it is a method that preserves variance in the forward pass. When layer widths vary widely and the scale of backpropagated gradients also matters, Xavier initialization is a candidate too.
  • Do not get the uniform range wrong: nn.init.uniform_(w, -1/sqrt(m), 1/sqrt(m)) gives a standard deviation of 1/3m1/\sqrt{3m}, smaller than LeCun initialization. When drawing from a uniform distribution, the range is ±3/m\pm\sqrt{3/m} (kaiming_uniform_(w, nonlinearity="linear") uses this range).

Comparison with other initializations

The table lines up LeCun initialization with initializations it is often compared with, from the same angles (mm and ninn_{in} are the number of inputs, and noutn_{out} the number of outputs).

InitializationWeight varianceWhat it preservesIntended activation functionIn PyTorch
LeCun initialization1/m1/mForward-pass varianceFunctions with gain close to 1, such as the recommended sigmoid and SELUkaiming_normal_(w, nonlinearity="linear")
Xavier initialization2/(nin+nout)2/(n_{in}+n_{out})Both forward and backward (a compromise)Functions nearly linear around 0, such as Tanhxavier_uniform_, xavier_normal_
He initialization2/nin2/n_{in}Forward-pass variance (compensating for ReLU)ReLU and its relativeskaiming_normal_(w, nonlinearity="relu")
Orthogonal initializationOrthogonal matrix (all singular values 1)Signal magnitude in every directionLinear, or Tanh etc. with an adjusted gainorthogonal_

When input and output widths are equal, LeCun and Xavier initialization have the same variance 1/n1/n. He initialization is exactly twice the variance of LeCun initialization.

Rough guidelines for choosing:

  • Use LeCun initialization with SELU: The self-normalizing property assumes a variance of 1/n1/n.
  • Use Xavier initialization for Tanh-type functions with varying widths, and He initialization for ReLU-type functions: These are tuned to account for the activation gain and backward-pass variance.

PyTorch example

Show code
python
import torch
import torch.nn as nn


# recommended sigmoid from Section 4.4 of the paper: f(x) = 1.7159 tanh(2x/3)
class ScaledTanh(nn.Module):
    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return 1.7159 * torch.tanh(2.0 / 3.0 * x)


# LeCun initialization: standard deviation 1/sqrt(fan_in) (Eq. (16) in the paper)
def init_lecun(module: nn.Module) -> None:
    if isinstance(module, (nn.Linear, nn.Conv2d)):
        # always specify nonlinearity="linear" (omitting it gives He initialization)
        nn.init.kaiming_normal_(module.weight, mode="fan_in", nonlinearity="linear")
        if module.bias is not None:
            nn.init.zeros_(module.bias)


model = nn.Sequential(
    nn.Linear(100, 256), ScaledTanh(),
    nn.Linear(256, 256), ScaledTanh(),
    nn.Linear(256, 10),
)
model.apply(init_lecun)

# normalize the inputs to mean 0 and variance 1 (Section 4.3 of the paper)
x = torch.randn(1000, 100) * 5.0 + 3.0
x = (x - x.mean(dim=0)) / x.std(dim=0)

with torch.no_grad():
    y = model[0](x)                      # weighted sum of layer 1
    print(f"std of weighted sum {y.std().item():.2f} (about 1)")
    print(f"std of sigmoid output {model[1](y).std().item():.2f}")

# for a uniform distribution, the range is ±sqrt(3 / fan_in)
w = torch.empty(256, 100)
nn.init.kaiming_uniform_(w, nonlinearity="linear")
print(f"uniform max {w.abs().max().item():.3f}, theoretical range {(3 / 100) ** 0.5:.3f}")

# self-normalizing networks using SELU use the same initialization
snn = nn.Sequential(nn.Linear(100, 256), nn.SELU(), nn.Linear(256, 10))
snn.apply(init_lecun)

FAQ

Q. Is LeCun initialization drawn from a normal or a uniform distribution?
A.

The paper fixes only the standard deviation and gives the uniform distribution as an example. A normal distribution with standard deviation 1/√m and a uniform distribution over ±√(3/m) both have the same variance, 1/m.

Q. Can LeCun initialization be used with plain tanh?
A.

Yes, but it differs slightly from the paper's assumptions. The constants of the recommended sigmoid 1.7159 tanh(2x/3) are chosen so that the output variance is close to 1 for inputs with variance 1. With plain tanh the outputs are smaller, so the output variance tends to shrink as layers are stacked.

Q. How should biases be initialized?
A.

The paper only specifies the standard deviation of the weights. In general they are set to 0. This also fits the paper's approach of normalizing inputs to mean 0 and using a sigmoid symmetric around 0.

References

  1. Y. LeCun, L. Bottou, G. B. Orr, and K.-R. Müller, "Efficient BackProp," in Neural Networks: Tricks of the Trade, LNCS 1524, Springer, 1998.
  2. PyTorch Documentation, "torch.nn.init."
  3. PyTorch Documentation, "torch.nn.SELU."