Sign in

PReLU

Parametric Rectified Linear Unit

A leaky ReLU whose negative slope is a trainable parameter, learned by gradient descent with the rest of the network.

Overview

Leaky ReLU asks you to pick the negative slope by hand. PReLU lets the network pick it. The slope α\alpha starts at a small value, 0.25 in the original paper, and is updated by backpropagation like any weight. If negative inputs carry useful information, the slope grows. If they do not, it shrinks toward zero and the unit behaves like ReLU. There can be one slope shared by everything or one slope per channel.

A short history

Kaiming He, Xiangyu Zhang, Shaoqing Ren and Jian Sun introduced PReLU in the 2015 paper 'Delving Deep into Rectifiers'. Instead of fixing the negative slope as leaky ReLU does, they made it a parameter learned by backpropagation. The same paper introduced the weight initialisation now named after He, and reported the first ImageNet classification result to pass the estimated human error rate.

How it works

  1. Create the slopes: an array alpha with num_parameters entries, all set to init.
  2. In forward, return xx where x>0x > 0 and αx\alpha x elsewhere. With per-channel slopes, each channel along channel_axis uses its own α\alpha.
  3. In backward, return the gradient for the input: the upstream gradient times 1 where x>0x > 0 and times α\alpha elsewhere.
  4. Also in backward, store the gradient for α\alpha in grad_alpha: the sum of upstream gradient times xx over the negative inputs of each channel.
  5. Call step(lr) to move α\alpha against its gradient.

Watch out for

  • Applying weight decay to α\alpha pulls it toward zero and turns the unit back into ReLU. The slopes are usually excluded from weight decay.
  • Nothing keeps α\alpha between 0 and 1. It can go negative or above 1, and then the function is no longer monotonic or no longer a leak.
  • With per-channel slopes the input must have exactly num_parameters entries on channel_axis. The template raises a ValueError when it does not.
  • On small datasets the extra parameters can overfit. A fixed leaky slope is the safer choice there.

Use cases

When to use it

Convolutional networks where the right negative slope differs by layer or channel and you would rather learn it than tune it. It adds at most one parameter per channel.

In industry

Face recognition
Face embedding networks in the ArcFace family use PReLU after their convolutional layers.
Image super-resolution
Super-resolution networks such as SRGAN use PReLU in the generator, where a learned negative slope helps keep fine detail.
Speech enhancement
Convolutional models that remove noise from recorded speech commonly use PReLU between their convolution layers.

Choosing it: what must hold

  • Enough training data that a few extra learned parameters will not overfit.
  • An optimiser setup where the slope parameters are excluded from weight decay, so they are not pulled toward zero.
  • A convolutional or feed-forward network in which the best negative slope may differ by layer or channel.

When to choose something else

IfUse instead
The dataset is small or you want fewer things to learnLeaky ReLU with a fixed slope
Dead units are not a problemReLU
You want a smooth negative side with no extra parametersELU

Math foundations

  1. The activation

    PReLU⁡(x)=max⁡(0,x)+α min⁡(0,x)\operatorname{PReLU}(x) = \max(0, x) + \alpha\,\min(0, x)

    The positive part passes unchanged and the negative part is scaled by α\alpha. With α\alpha fixed at 0.01 this is Leaky ReLU, with α=0\alpha = 0 it is ReLU.

  2. Slope with respect to the input

    ∂ PReLU⁡(x)∂x={1,x>0α,x≤0\frac{\partial\,\operatorname{PReLU}(x)}{\partial x} = \begin{cases} 1, & x > 0 \\ \alpha, & x \le 0 \end{cases}

    The factor that carries the gradient back to earlier layers. It is what backward returns, times the upstream gradient.

  3. Slope with respect to the parameter

    ∂ PReLU⁡(x)∂α=min⁡(0,x)\frac{\partial\,\operatorname{PReLU}(x)}{\partial \alpha} = \min(0, x)

    Only negative inputs depend on α\alpha, and they depend on it in proportion to how negative they are. Positive inputs contribute nothing.

  4. Gradient of the loss for the slope

    ∂L∂α=∑iδi min⁡(0,xi)\frac{\partial \mathcal{L}}{\partial \alpha} = \sum_{i} \delta_i\,\min(0, x_i)

    The chain rule summed over every input that shares this slope. This is the value stored in grad_alpha.

  5. The update

    α←α−η ∂L∂α\alpha \leftarrow \alpha - \eta\,\frac{\partial \mathcal{L}}{\partial \alpha}

    Plain gradient descent, as in the template's step. Frameworks apply their own optimiser to α\alpha in the same way.

Symbols

x,xix, x_i
an input to the activation
α\alpha
the learned negative slope; the array alpha, started at init
δi\delta_i
the gradient of the loss with respect to output i, grad_output
L\mathcal{L}
the loss being minimised
η\eta
the learning rate, lr

Worked by hand

One shared slope α=0.25\alpha = 0.25, inputs x=(−2,3)x = (-2, 3), upstream gradient δ=(1,1)\delta = (1, 1), learning rate η=0.1\eta = 0.1.

PReLU⁡(−2)=0.25×(−2)=−0.5,PReLU⁡(3)=3\operatorname{PReLU}(-2) = 0.25 \times (-2) = -0.5, \qquad \operatorname{PReLU}(3) = 3
∂L∂x=(0.25,  1)\frac{\partial \mathcal{L}}{\partial x} = (0.25,\; 1)
∂L∂α=1×(−2)+1×0=−2\frac{\partial \mathcal{L}}{\partial \alpha} = 1 \times (-2) + 1 \times 0 = -2
α←0.25−0.1×(−2)=0.45\alpha \leftarrow 0.25 - 0.1 \times (-2) = 0.45

The slope rises from 0.25 to 0.45. A positive upstream gradient on a negative input says the loss falls if that output moves down, and a larger slope does that.

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 PReLU
from config import PReLUConfig

act = PReLU(PReLUConfig(num_parameters=1, init=0.25))
x = np.array([-2.0, 0.0, 3.0])
y = act.forward(x)                    # [-0.5, 0.0, 3.0]
dx = act.backward(x, np.ones(3))      # [0.25, 0.25, 1.0]
print(act.grad_alpha)                 # [-2.0]: gradient for the learned slope
act.step(lr=0.1)                      # alpha is now 0.45
Read the implementation (63 lines)
"""PReLU: parametric ReLU, f(x) = x for x > 0 and alpha * x for x <= 0, with a learned alpha.

NumPy only. `forward` computes the activation. `backward` returns the gradient with respect to the input and stores
the gradient with respect to alpha in `grad_alpha`.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import PReLUConfig
except ImportError:  # run from the template's own folder
    from config import PReLUConfig

class PReLU:
    """f(x) = max(0, x) + alpha * min(0, x), with `alpha` a trainable array of shape (num_parameters,)."""

    def __init__(self, config: PReLUConfig | None = None) -> None:
        self.config = config or PReLUConfig()
        self.alpha = np.full(self.config.num_parameters, float(self.config.init))
        self.grad_alpha = np.zeros_like(self.alpha)

    def _channel_shape(self, x: np.ndarray) -> tuple:
        """Shape that lets `alpha` broadcast against x: all ones, except the channel axis."""
        if self.config.num_parameters == 1:
            return (1,) * x.ndim
        axis = self.config.channel_axis
        if x.ndim == 0 or not -x.ndim <= axis < x.ndim or x.shape[axis] != self.config.num_parameters:
            raise ValueError(f"input of shape {x.shape} does not have {self.config.num_parameters} channels on "
                             f"axis {axis}")
        shape = [1] * x.ndim
        shape[axis] = self.config.num_parameters
        return tuple(shape)

    def forward(self, x: np.ndarray) -> np.ndarray:
        """Apply the activation. x: any shape (with the channel axis when slopes are per channel). Same shape out."""
        x = np.asarray(x, dtype=float)
        alpha = self.alpha.reshape(self._channel_shape(x))
        return np.where(x > 0, x, alpha * x)

    def backward(self, x: np.ndarray, grad_output: np.ndarray | None = None) -> np.ndarray:
        """Gradient with respect to x; also fills `self.grad_alpha`.

        x: the input given to `forward`. grad_output: d loss / d output, same shape as x (ones when omitted).
        Returns d loss / d x, same shape as x. `grad_alpha` gets d loss / d alpha, shape (num_parameters,):
        the sum of grad_output * x over the negative inputs of each channel.
        """
        x = np.asarray(x, dtype=float)
        g = np.ones_like(x) if grad_output is None else np.asarray(grad_output, dtype=float)
        shape = self._channel_shape(x)
        per_element = g * np.minimum(x, 0.0)  # d output / d alpha is x where x <= 0, else 0
        if self.config.num_parameters == 1:
            self.grad_alpha = np.array([per_element.sum()])
        else:
            other_axes = tuple(i for i, n in enumerate(shape) if n == 1)
            self.grad_alpha = per_element.sum(axis=other_axes)
        return g * np.where(x > 0, 1.0, self.alpha.reshape(shape))

    def step(self, lr: float) -> None:
        """One plain gradient-descent update of alpha with the gradient stored by the last `backward`."""
        self.alpha = self.alpha - lr * self.grad_alpha

    __call__ = forward
Repository
gitlab.com/designsbyduhart/solomon-templates/activation-prelu
Needs
Python 3.10 and NumPy
Tests
7, run with python3 -m unittest -v

Practice

Build PReLU(PReLUConfig(num_parameters=3, init=0.25, channel_axis=1)) and feed an array of shape (2, 3, 4). Call backward with ones, read grad_alpha, and confirm each entry equals the sum of the negative inputs in that channel. Then call step(0.1) and inspect alpha.

Check on learning

  1. After training, one layer's slope is near 0 and another's is near 1. What does each value tell you about how that layer uses negative inputs?
    A way to think about it

    A slope of 0 is ReLU: negatives are discarded. A slope of 1 is the identity: the layer is acting linearly. Think about which depth each is likely to appear at.

  2. Why does weight decay on α\alpha work against the reason for using PReLU at all?
    A way to think about it

    Weight decay adds a pull toward zero. Ask what PReLU becomes at α=0\alpha = 0 and whether the data or the regulariser chose that.

  3. The gradient for α\alpha sums over every negative input in the channel. What happens to its size as the feature map grows, and what does that imply for the learning rate?
    A way to think about it

    A sum over more elements is larger. Compare how a per-weight gradient and this pooled gradient scale with spatial size.

  4. Would you use one shared slope or one per channel in a network with 512 channels and a small dataset?
    A way to think about it

    Count the added parameters in each case and weigh them against the dataset size. More freedom is only useful if the data can pin it down.