Overview
Leaky ReLU asks you to pick the negative slope by hand. PReLU lets the network pick it. The slope 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
- Create the slopes: an array
alphawithnum_parametersentries, all set toinit. - In
forward, return where and elsewhere. With per-channel slopes, each channel alongchannel_axisuses its own . - In
backward, return the gradient for the input: the upstream gradient times 1 where and times elsewhere. - Also in
backward, store the gradient for ingrad_alpha: the sum of upstream gradient times over the negative inputs of each channel. - Call
step(lr)to move against its gradient.
Watch out for
- Applying weight decay to pulls it toward zero and turns the unit back into ReLU. The slopes are usually excluded from weight decay.
- Nothing keeps 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_parametersentries onchannel_axis. The template raises aValueErrorwhen 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
| If | Use instead |
|---|---|
| The dataset is small or you want fewer things to learn | Leaky ReLU with a fixed slope |
| Dead units are not a problem | ReLU |
| You want a smooth negative side with no extra parameters | ELU |
Math foundations
The activation
The positive part passes unchanged and the negative part is scaled by . With fixed at 0.01 this is Leaky ReLU, with it is ReLU.
Slope with respect to the input
The factor that carries the gradient back to earlier layers. It is what
backwardreturns, times the upstream gradient.Slope with respect to the parameter
Only negative inputs depend on , and they depend on it in proportion to how negative they are. Positive inputs contribute nothing.
Gradient of the loss for the slope
The chain rule summed over every input that shares this slope. This is the value stored in
grad_alpha.The update
Plain gradient descent, as in the template's
step. Frameworks apply their own optimiser to in the same way.
Symbols
- an input to the activation
- the learned negative slope; the array
alpha, started atinit - the gradient of the loss with respect to output i,
grad_output - the loss being minimised
- the learning rate,
lr
Worked by hand
One shared slope , inputs , upstream gradient , learning rate .
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.45Read 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
- 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.
- Why does weight decay on 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 and whether the data or the regulariser chose that.
- The gradient for 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.
- 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.