AI Logic

Activation Functions

ReLU

Updated:

Graph of ReLU. For x ≤ 0 the output is 0, for positive x the output equals x, with a kink at the origin

What is ReLU?

ReLU is an activation function that outputs the input unchanged when it is positive and outputs 0 when it is 0 or below. It is cheap to compute and lets networks train well even as they get deeper, so it is the standard first choice when you are unsure which activation function to use. The name stands for Rectified Linear Unit: like electrical rectification (letting current flow in only one direction), it passes only positive values.

ReLU(x)=max⁡(0, x)={x(x>0)0(x≤0)\mathrm{ReLU}(x) = \max(0,\, x) = \begin{cases} x & (x > 0) \\ 0 & (x \le 0) \end{cases}

The output range is 0≤ReLU(x)<∞0 \le \mathrm{ReLU}(x) < \infty. Concrete values look like this:

Input xx−2−0.501.53
Output ReLU(x)\mathrm{ReLU}(x)0001.53
Slope (derivative)000 *11

* The derivative is mathematically undefined at x=0x = 0. Both the original paper (Nair and Hinton, 2010) and frameworks such as PyTorch treat the slope for x≤0x \le 0 as 0.

Why is it so widely used?

There are three reasons ReLU is so widely used.

  1. Gradients rarely shrink: For positive inputs the slope is always 1, so gradients do not shrink layer by layer as backpropagation moves back through the network. The sigmoid function has a maximum slope of only 0.25, so gradients shrink as layers are stacked and training tends to stall (the vanishing gradient problem).
  2. Cheap to compute: It only returns the larger of the input and 0, with no exponential to evaluate.
  3. Many outputs are 0: Because all negative inputs become 0, only a subset of units is active at a time. This sparse representation has been shown to help learning (Glorot et al., 2011).

In practice, in experiments by Krizhevsky et al. (2012) on CIFAR-10, a four-layer convolutional network with ReLU reached the same training error (25%) about six times faster than with Tanh. Many representative convolutional networks, such as ResNet and DenseNet, also use ReLU in their hidden layers.

Practical considerations

Because the slope is 0 for negative inputs, watch out for the following.

Dying ReLU (units stop working): If the input to a unit is negative for every data point, both its output and its slope are always 0. Its weights stop being updated, and the unit no longer takes part in learning. This is more likely when the learning rate is too large or the initial weights are poorly chosen (the dying ReLU problem). Stanford's CS231n lecture notes state that with too high a learning rate, as much as 40% of a network's units can die.

Remedies include:

  • Lower the learning rate: This prevents large updates from pushing units to the negative side.
  • Use an initialization designed for ReLU: He initialization (He et al., 2015) sets the weight variance so that the output scale of each layer is preserved with ReLU (weight initialization).
  • Switch to a function that keeps a slope on the negative side: Use Leaky ReLU or PReLU.

ReLU is meant for hidden layers. Choose the output layer according to the task: Softmax is typical for classification, and no activation (passing the input through) is typical for regression. Because ReLU cannot output negative values, it cannot be used to predict quantities that can be negative.

Comparison with other activation functions and how to choose

The table compares ReLU with commonly compared activation functions from the same viewpoints.

FunctionHandling of negative inputsComputational costTypical use
ReLUSet to 0 (slope also 0)LowestHidden layers of convolutional networks and fully connected layers
Leaky ReLUKeeps a small slope (e.g., 0.01)LowWhen you want to avoid dying ReLU
PReLUSlope is learnedLow (adds learnable parameters)Image recognition (He et al., 2015)
GELUShrinks smoothly near 0Somewhat higherTransformer (BERT, GPT, etc.)
Sigmoid function / TanhSaturates for large inputs; slope approaches 0High (uses exponentials)Output layers producing probabilities, RNN gates

Rough guidelines for choosing:

  • When in doubt, start with ReLU: It is cheap and gives sufficient accuracy on many tasks.
  • If dying ReLU occurs, try Leaky ReLU or PReLU: A slope remains on the negative side, so units keep working.
  • Use GELU when building a Transformer: Matching the original model makes it easier to compare against published settings and results.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F

# Example input and output (same values as the table above)
x = torch.tensor([-2.0, -0.5, 0.0, 1.5, 3.0])
print(F.relu(x))  # tensor([0.0000, 0.0000, 0.0000, 1.5000, 3.0000])


# A small fully connected network with ReLU in the hidden layer
class MLP(nn.Module):
    def __init__(self, in_features: int, hidden: int, out_features: int):
        super().__init__()
        self.fc1 = nn.Linear(in_features, hidden)
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(hidden, out_features)
        # Initialization designed for ReLU (He initialization)
        nn.init.kaiming_normal_(self.fc1.weight, nonlinearity="relu")

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.fc2(self.relu(self.fc1(x)))


model = MLP(in_features=784, hidden=256, out_features=10)
print(model(torch.randn(32, 784)).shape)  # torch.Size([32, 10])

FAQ

Q. What is the derivative at x = 0?
A.

It is mathematically undefined. Frameworks such as PyTorch treat it as 0. Inputs are rarely exactly 0, so this has almost no effect on training.

Q. How can I tell whether dying ReLU is happening?
A.

During training, record the fraction of each unit's outputs that are 0. If the number of units whose output is 0 for every data point keeps growing, suspect dying ReLU.

Q. Should I use ReLU or Leaky ReLU?
A.

Start with ReLU, and try Leaky ReLU if dying ReLU occurs or accuracy plateaus. The difference depends on the task, so compare both under the same conditions before deciding.

References

  1. V. Nair and G. E. Hinton, "Rectified Linear Units Improve Restricted Boltzmann Machines," ICML, 2010.
  2. X. Glorot, A. Bordes, and Y. Bengio, "Deep Sparse Rectifier Neural Networks," AISTATS, 2011.
  3. A. Krizhevsky, I. Sutskever, and G. E. Hinton, "ImageNet Classification with Deep Convolutional Neural Networks," NIPS, 2012.
  4. A. L. Maas, A. Y. Hannun, and A. Y. Ng, "Rectifier Nonlinearities Improve Neural Network Acoustic Models," ICML Workshop on Deep Learning for Audio, Speech and Language Processing, 2013.
  5. K. He, X. Zhang, S. Ren, and J. Sun, "Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification," ICCV, 2015.
  6. D. Hendrycks and K. Gimpel, "Gaussian Error Linear Units (GELUs)," arXiv:1606.08415, 2016.
  7. L. Lu, Y. Shin, Y. Su, and G. E. Karniadakis, "Dying ReLU and Initialization: Theory and Numerical Examples," arXiv:1903.06733, 2019.
  8. PyTorch Documentation, "torch.nn.ReLU."
  9. Stanford CS231n, "Convolutional Neural Networks for Visual Recognition: Neural Networks Part 1 (Commonly used activation functions)."