Sign in

Leaky ReLU

Leaky Rectified Linear Unit

A ReLU whose negative side has a small fixed slope instead of being flat, so no unit is ever fully switched off.

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

  1. Take the input xx that a layer has computed for one unit.
  2. If x>0x > 0, return xx unchanged.
  3. If x≤0x \le 0, return a xa\,x, where aa is the config's negative_slope.
  4. During training, multiply the incoming gradient by 1 where x>0x > 0 and by aa elsewhere. At x=0x = 0 the template uses the negative-side slope.

Watch out for

  • The slope aa 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

IfUse instead
Dead units are not a problem and you want the cheapest optionReLU
You would prefer the network to learn the negative slopePReLU
You want a smooth curve on the negative sideELU or SiLU

Math foundations

  1. The activation

    LeakyReLU⁡(x)={x,x>0a x,x≤0\operatorname{LeakyReLU}(x) = \begin{cases} x, & x > 0 \\ a\,x, & x \le 0 \end{cases}

    Two straight lines that meet at the origin. Setting a=0a = 0 gives ReLU and a=1a = 1 gives the identity.

  2. The same thing in one line

    LeakyReLU⁡(x)=max⁡(x,  a x)(0≤a≤1)\operatorname{LeakyReLU}(x) = \max(x,\; a\,x) \qquad (0 \le a \le 1)

    For aa 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.

  3. Its slope

    ddxLeakyReLU⁡(x)={1,x>0a,x≤0\frac{d}{dx}\operatorname{LeakyReLU}(x) = \begin{cases} 1, & x > 0 \\ a, & x \le 0 \end{cases}

    The factor backpropagation multiplies by. It is never zero when a>0a > 0, which is the whole point of the leak.

Symbols

xx
the input to the activation (one unit's pre-activation)
aa
the slope for negative inputs; negative_slope in the config, default 0.01

Worked by hand

Apply Leaky ReLU with a=0.01a = 0.01 to the inputs −3-3 and 22.

LeakyReLU⁡(−3)=0.01×(−3)=−0.03\operatorname{LeakyReLU}(-3) = 0.01 \times (-3) = -0.03
LeakyReLU⁡(2)=2\operatorname{LeakyReLU}(2) = 2
slopes: 0.01 at x=−3,1 at x=2\text{slopes: } 0.01 \text{ at } x = -3, \quad 1 \text{ at } x = 2

The negative input gives −0.03-0.03 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

  1. 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.

  2. Why is a stack of layers with a=1a = 1 no more powerful than a single linear layer?
    A way to think about it

    With a=1a = 1 the activation is the identity. Compose two linear maps and see what kind of map you get.

  3. 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.

  4. 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.