Overview
ReLU returns zero for every negative input. Its slope there is zero too, so a unit that only sees negative inputs gets no learning signal and can stay dead. Leaky ReLU changes one thing: negative inputs are multiplied by a small constant such as 0.01. The output is then slightly negative, and the slope is that small constant. The unit still responds weakly to negative inputs, and the weak response is enough for gradient descent to move it back.
A short history
Andrew Maas, Awni Hannun and Andrew Ng introduced the leaky ReLU in 2013 in a paper on acoustic models for speech recognition. A plain ReLU has zero gradient for negative inputs, so a unit that falls into that region for every example stops learning. Giving the negative side a small fixed slope keeps a gradient flowing everywhere at almost no extra cost.
How it works
- Take the input that a layer has computed for one unit.
- If , return unchanged.
- If , return , where is the config's
negative_slope. - During training, multiply the incoming gradient by 1 where and by elsewhere. At the template uses the negative-side slope.
Watch out for
- The slope is a fixed hyperparameter. A value that is too small behaves like ReLU, and a value near 1 makes the unit almost linear, which removes the nonlinearity the network needs.
- The output is no longer bounded below, so code that assumes non-negative activations after ReLU will be wrong.
- The curve still has a corner at zero. If you need a smooth slope there, use ELU, GELU or SiLU.
Use cases
When to use it
Networks where plain ReLU leaves many units permanently at zero, and in GAN discriminators, where a slope of 0.2 is a common choice.
In industry
- Image generation
- GAN discriminators, following the DCGAN design, use leaky ReLU so that gradients reach the generator even for inputs the discriminator rejects.
- Object detection
- The Darknet backbones of the early YOLO detectors use leaky ReLU with a slope of 0.1 in their convolutional layers.
- Audio synthesis
- Neural vocoders that turn spectrograms into waveforms, such as HiFi-GAN, use leaky ReLU throughout the generator and discriminators.
Choosing it: what must hold
- A network where dead units are a real risk: high learning rates, sparse gradients or an adversarial training setup.
- A negative slope chosen in advance, commonly 0.01 to 0.2, that you are willing to tune as a hyperparameter.
- No need for exact zeros in the activations, since the output is never fully switched off.
When to choose something else
| If | Use instead |
|---|---|
| Dead units are not a problem and you want the cheapest option | ReLU |
| You would prefer the network to learn the negative slope | PReLU |
| You want a smooth curve on the negative side | ELU or SiLU |
Math foundations
The activation
Two straight lines that meet at the origin. Setting gives ReLU and gives the identity.
The same thing in one line
For between 0 and 1 the larger of the two lines is always the right piece. This form is how the function is often written and computed.
Its slope
The factor backpropagation multiplies by. It is never zero when , which is the whole point of the leak.
Symbols
- the input to the activation (one unit's pre-activation)
- the slope for negative inputs;
negative_slopein the config, default 0.01
Worked by hand
Apply Leaky ReLU with to the inputs and .
The negative input gives with slope 0.01. ReLU would give 0 with slope 0, so no gradient would pass.
Visual example
Loading the example.
Try this
- Move across the curve and read the output and the slope together.
- Find where the slope is close to zero: a unit there has stopped learning.
Code sample
import numpy as np
from impl import LeakyReLU
from config import LeakyReLUConfig
act = LeakyReLU(LeakyReLUConfig(negative_slope=0.01))
y = act.forward(np.array([-2.0, 0.0, 3.0])) # [-0.02, 0.0, 3.0]
dy = act.backward(np.array([-2.0, 0.0, 3.0])) # [0.01, 0.01, 1.0]Read the implementation (34 lines)
"""Leaky ReLU: f(x) = x for x > 0 and negative_slope * x for x <= 0.
NumPy only. `forward` computes the activation, `backward` the gradient with respect to the input.
"""
from __future__ import annotations
import numpy as np
try:
from .config import LeakyReLUConfig
except ImportError: # run from the template's own folder
from config import LeakyReLUConfig
class LeakyReLU:
"""f(x) = x for x > 0, negative_slope * x for x <= 0."""
def __init__(self, config: LeakyReLUConfig | None = None) -> None:
self.config = config or LeakyReLUConfig()
def forward(self, x: np.ndarray) -> np.ndarray:
"""Apply the activation element by element. x: any shape. Returns the same shape."""
x = np.asarray(x, dtype=float)
return np.where(x > 0, x, self.config.negative_slope * x)
def backward(self, x: np.ndarray, grad_output: np.ndarray | None = None) -> np.ndarray:
"""d f / d x at x, times `grad_output` when given (the chain rule step of backpropagation).
At x = 0, where the function has a kink, the negative-side slope is used.
"""
x = np.asarray(x, dtype=float)
local = np.where(x > 0, 1.0, self.config.negative_slope)
return local if grad_output is None else local * np.asarray(grad_output, dtype=float)
__call__ = forward- Repository
- gitlab.com/designsbyduhart/solomon-templates/activation-leaky-relu
- Needs
- Python 3.10 and NumPy
- Tests
- 7, run with
python3 -m unittest -v
Practice
Build LeakyReLU(LeakyReLUConfig(negative_slope=0.01)) and run forward and backward on 11 points from -5 to 5. Repeat with negative_slope set to 0 and to 1, and say which familiar function each one reproduces.
Check on learning
- A unit's inputs are all negative. With a slope of 0.01 its gradient is 100 times smaller than on the positive side. Is the unit effectively dead anyway?
A way to think about it
Small is not zero. Estimate how many steps it takes to cross back to positive inputs at that reduced rate, and compare with never.
- Why is a stack of layers with no more powerful than a single linear layer?
A way to think about it
With the activation is the identity. Compose two linear maps and see what kind of map you get.
- GAN discriminators often use a slope of 0.2 rather than 0.01. What does the discriminator pass back to the generator, and why would a larger leak help?
A way to think about it
The generator learns only from gradients that flow back through the discriminator. Think about what a nearly flat region does to that signal.
- How would you decide between a fixed slope and a learned one, as in PReLU?
A way to think about it
Weigh the cost: one more parameter to fit and a risk of overfitting on small data, against removing a hyperparameter you would otherwise tune by hand.