Level 3 In-Depth AI · Deep Learning
Activation Functions
The small nonlinear function each neuron applies after its weighted sum. Without it a deep network collapses into a straight line; with the right one it trains fast. Meet sigmoid, tanh, ReLU, GELU, SiLU and softmax, and learn which to use where.
- Level
- ●●●●● Easy
- Reading
- 13 min
- To learn it well
- 45 minutes to read, an hour to practise
- Builds on
- 14 concepts →
- Quiz
- 5 questions ↓
Read first
Neural NetworksThe full path from zero — 14 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Activation Functions
Read them roughly in this order. See it on the concept map →
Why it matters
Every neuron in a neural network does two things: it computes a weighted sum of its inputs, and then it passes that sum through a small fixed function. That function is the activation function. It looks like a detail, but it decides whether a network can learn anything interesting at all, and how fast.
Choosing it well was one of the turning points of deep learning. For decades networks used the smooth S-shaped sigmoid, and deep ones barely trained. Switching to the humble ReLU, which just replaces negative numbers by zero, was one of the changes that let AlexNet win the 2012 ImageNet competition and set off the deep-learning boom. Today's Transformers use GELU or SwiGLU inside every block, and every classifier and language model ends with a softmax that turns raw scores into probabilities.
The intuition
A weighted sum is a linear operation. Double the input and you double the output. Add two inputs and the outputs add. Linear functions are easy to work with, but on their own they can only describe straight lines, flat planes and their higher-dimensional cousins. And a chain of linear functions is still linear: a hundred layers of weighted sums collapse into one (the Neural Networks chapter shows the algebra).
An activation function puts a bend into each neuron. Think of it as a hinge or a dimmer switch. A ReLU neuron says "stay silent until the signal passes zero, then pass it through". With many neurons, each bending at a different place and in a different direction, the network can piece together curves of any shape, the way you can trace a circle with enough short straight segments. That is why activation functions are also called nonlinearities.
The slope matters as much as the shape. Training works by sending gradients backwards through every neuron, and each neuron multiplies the gradient passing through it by the slope of its activation function. A slope near zero blocks the signal. A slope of one lets it through unchanged. Much of the history of activation functions is a search for shapes that bend enough to be useful while keeping their slopes healthy.
Key idea The activation function is the nonlinearity that gives depth its power. Its slope also gates the gradient during training. Use ReLU-family functions (ReLU, GELU, SiLU) in hidden layers, and softmax or sigmoid only at the output to produce probabilities.
How it works
Write for a neuron's weighted sum plus bias, . The neuron's output is , where is the activation function. Here are the important ones, each with values at so you can check them by hand.
Sigmoid
The number is the base of natural logarithms. For large positive , is tiny and approaches 1. For large negative , is huge and approaches 0. At it is exactly 0.5.
Values: 0.119, 0.269, 0.500, 0.731, 0.881.
The sigmoid squeezes any number into the range 0 to 1, so it is natural for a probability. That's why Logistic Regression uses it. Its slope has a neat form, , which is at most 0.25 (at ) and falls fast: 0.105 at , 0.0066 at .
When a neuron's input is far from zero and its slope is nearly flat, we say it is saturated. A saturated neuron passes almost no gradient back. Worse, since the slope is never more than 0.25, a gradient passing back through 10 sigmoid layers is multiplied by at most . That is the heart of the vanishing gradient problem, and the main reason sigmoid is no longer used in hidden layers.
Tanh
Values: −0.964, −0.762, 0.000, 0.762, 0.964.
The hyperbolic tangent, tanh, is a stretched sigmoid that runs from −1 to 1 and is centred on zero (in fact ). Zero-centred outputs make the next layer's job easier, and the maximum slope is 1 instead of 0.25. It still saturates at both ends. Tanh survives inside LSTMs and in places where an output must be bounded between −1 and 1.
ReLU
Values: 0, 0, 0, 1, 2.
The rectified linear unit passes positive numbers through unchanged and replaces negative ones with zero. It looks almost too simple to work, yet it has three big advantages:
- No saturation for positive inputs. The slope is exactly 1 for any , so gradients flow through many layers without shrinking.
- Cheap. A comparison, no exponentials.
- Sparse. For typical inputs about half the neurons output exactly zero, so each input activates only part of the network.
Its slope is 0 for . At exactly it has no defined slope, and libraries simply use 0.
Leaky ReLU
With the common , the values are −0.02, −0.01, 0, 1, 2. Leaky ReLU gives negative inputs a small slope instead of none, so a neuron can never go completely silent (see dead neurons below).
GELU
Values: −0.046, −0.159, 0.000, 0.841, 1.954.
("phi") is the probability that a standard normal (Gaussian) random number is less than . It rises smoothly from 0 to 1, like a sigmoid. So the Gaussian Error Linear Unit multiplies the input by a smooth "how positive is it?" gate. It behaves like ReLU for large , but bends smoothly near zero and dips slightly below zero for small negative inputs. GELU is the activation in BERT and the GPT-2 and GPT-3 family of models.
SiLU (Swish)
Values: −0.238, −0.269, 0.000, 0.731, 1.762.
The sigmoid linear unit, also called Swish, uses the sigmoid as its gate instead of . It has nearly the same shape as GELU and is cheaper to compute. It is common in modern vision networks and, as part of SwiGLU, in many recent language models.
SwiGLU is a slightly bigger idea: a gated layer. Instead of one weight matrix followed by an activation, it uses two weight matrices on the same input, applies SiLU to one result, and multiplies the two element by element: , where means "multiply matching entries". One branch decides how much of the other to let through. As of late 2026, SwiGLU is the standard MLP block in open language models such as the Llama family.
Softmax: the output layer's activation
All the functions above act on each number separately. Softmax is different. It takes a whole vector of scores, called logits, one per class, and turns them into probabilities that are all positive and add up to 1:
In words: raise to the power of each score, which makes every number positive, then divide each by the total so they add up to 1. The subscript picks one class, and the sum runs over all classes.
A worked example. A classifier outputs logits for cat, dog and fox.
- Exponentiate: , , .
- Add them: .
- Divide: , , .
The model is 65.9% sure it's a cat. Notice that the gap between cat and dog in logits was only 1.0, but in probability it became almost 3 to 1, because . Softmax exaggerates differences: it is a soft version of "pick the maximum", which is where the name comes from. The same function turns a language model's scores over its whole vocabulary into next-word probabilities, and appears inside every Attention layer.
For two classes, softmax reduces to the sigmoid. That's why a yes/no classifier can use one output neuron with a sigmoid instead.
Dead neurons
ReLU's zero slope for negative inputs has a dark side. Suppose a large gradient step pushes a neuron's bias far negative. Now its weighted sum is negative for every training example, so it always outputs 0 and always has slope 0. No gradient ever reaches its weights again, so nothing can fix it. It is a dead neuron: still in the network, using memory, contributing nothing.
A few dead neurons are harmless. But with a learning rate that's too high, a large fraction of a network can die early in training. Leaky ReLU, GELU and SiLU all have a nonzero slope for negative inputs, so their neurons can always recover. Careful initialisation and moderate learning rates also help.
Which to use where
| Where | Use | Why |
|---|---|---|
| Hidden layers, default | ReLU | Simple, fast, works well. Start here. |
| Hidden layers in Transformers | GELU, or SwiGLU | Smooth, slightly better results at scale. |
| Hidden layers if many neurons die | Leaky ReLU, GELU or SiLU | Nonzero slope for negative inputs. |
| Output, one number (regression) | none | The output can be any value. |
| Output, yes/no or several independent labels | sigmoid | One probability per label. |
| Output, exactly one of classes | softmax | Probabilities that add up to 1. |
| Gates inside LSTMs | sigmoid and tanh | Need values bounded in 0–1 and −1 to 1. |
In code
All six functions and softmax in NumPy, checked against PyTorch:
import numpy as np
from math import erf, sqrt
def sigmoid(z): return 1 / (1 + np.exp(-z))
def tanh(z): return np.tanh(z)
def relu(z): return np.maximum(0, z)
def leaky(z): return np.where(z > 0, z, 0.01 * z)
def gelu(z): return z * 0.5 * (1 + np.vectorize(erf)(z / sqrt(2)))
def silu(z): return z * sigmoid(z)
def softmax(z):
e = np.exp(z - z.max()) # subtract the max for numerical safety
return e / e.sum()
z = np.array([-2.0, -1.0, 0.0, 1.0, 2.0])
for f in [sigmoid, tanh, relu, leaky, gelu, silu]:
print(f"{f.__name__:8s}", np.round(f(z), 3))
print("softmax ", np.round(softmax(np.array([2.0, 1.0, 0.1])), 3))
import torch
import torch.nn.functional as F
t = torch.tensor(z)
print(torch.allclose(F.gelu(t), torch.tensor(gelu(z))), torch.allclose(F.silu(t), torch.tensor(silu(z))))
# sigmoid [0.119 0.269 0.5 0.731 0.881]
# tanh [-0.964 -0.762 0. 0.762 0.964]
# relu [0. 0. 0. 1. 2.]
# leaky [-0.02 -0.01 0. 1. 2. ]
# gelu [-0.046 -0.159 0. 0.841 1.954]
# silu [-0.238 -0.269 0. 0.731 1.762]
# softmax [0.659 0.242 0.099]
# True True
Subtracting the largest score before exponentiating doesn't change softmax's answer (it cancels in the division) but stops overflowing for large logits.
Now a demonstration of dead neurons. We take a layer of 1,000 neurons, push all biases down by 2 as a bad update might, and count how many neurons receive no gradient at all:
import torch
from torch import nn
import torch.nn.functional as F
torch.manual_seed(0)
layer = nn.Linear(10, 1000) # 1,000 hidden neurons
x = torch.randn(512, 10) # 512 random inputs
for shift in [0.0, 2.0]:
with torch.no_grad():
layer.bias -= shift # simulate a bad update that pushes biases down
z = layer(x)
for name, act in [("relu", F.relu), ("gelu", F.gelu)]:
layer.zero_grad()
act(z).sum().backward(retain_graph=True)
no_grad = (layer.bias.grad.abs() < 1e-6).float().mean()
print(f"bias shift -{shift} {name}: neurons with zero gradient {no_grad:.1%}")
# bias shift -0.0 relu: neurons with zero gradient 0.0%
# bias shift -0.0 gelu: neurons with zero gradient 0.0%
# bias shift -2.0 relu: neurons with zero gradient 77.8%
# bias shift -2.0 gelu: neurons with zero gradient 0.0%
After the shift, 77.8% of the ReLU neurons are dead for all 512 inputs. The GELU neurons all still get some gradient and can recover.
In PyTorch you use activations as layers (nn.ReLU(), nn.GELU(), nn.SiLU(), nn.Softmax(dim=-1)) or as functions (F.relu, F.gelu, F.silu, F.softmax).
Common pitfalls
- Sigmoid or tanh in deep hidden layers. Gradients shrink layer by layer and early layers stop learning. Use ReLU or GELU instead.
- Softmax before
CrossEntropyLoss. PyTorch'snn.CrossEntropyLossandF.cross_entropyexpect raw logits and apply a (numerically safer) log-softmax themselves. Adding your own softmax first silently hurts training. - Softmax over the wrong axis. For a batch of shape (batch, classes), softmax must run over the class axis,
dim=-1. Overdim=0each class is normalised across the batch, which is meaningless but raises no error. - Softmax when labels aren't exclusive. If an image can be both "outdoor" and "dog", the classes don't compete. Use one sigmoid per label instead.
- Ignoring dead neurons. If training stalls early with a high learning rate, check what fraction of ReLU outputs are zero for every example in a batch.
Watch out Computing softmax naively as
np.exp(z) / np.exp(z).sum()overflows toinf / inf = nanonce any logit passes about 710 in 64-bit floats (and about 89 in 32-bit). Always subtract the maximum first, or use the library's built-in softmax and log-softmax.
Where it leads
- Vanishing and Exploding Gradients: saturating activations were the main cause, and ReLU part of the cure.
- Weight Initialization: the right size of random starting weights depends on the activation. Xavier initialisation suits tanh, He initialisation suits ReLU.
- Why Neural Networks Work: with any of these nonlinearities, a wide enough network can approximate any continuous function.
- Entropy, Cross-Entropy and KL Divergence: softmax outputs are compared with true labels using cross-entropy.
- The Transformer and Attention: softmax turns attention scores into weights, and GELU or SwiGLU sits in every feed-forward block.
A bit of history
The sigmoid came with the Backpropagation revival of the 1980s, because it is a smooth stand-in for the perceptron's step and has a convenient derivative. Yann LeCun and others recommended tanh for its zero-centred outputs in the late 1980s and 1990s.
Rectifiers appeared in neuroscience-inspired models long before they caught on. Vinod Nair and Geoffrey Hinton used ReLUs in 2010, and Xavier Glorot, Antoine Bordes and Yoshua Bengio showed in 2011 that deep rectifier networks train well without special pre-training. In 2012 AlexNet used ReLUs; its authors reported that a small convolutional network with ReLUs reached a target training error on the CIFAR-10 dataset about six times faster than the same network with tanh. ReLU became the default almost overnight.
Dan Hendrycks and Kevin Gimpel proposed GELU in 2016, and it was adopted by BERT and GPT. In 2017 Prajit Ramachandran, Barret Zoph and Quoc Le used an automated search to find Swish (), essentially the same function Stefan Elfwing and colleagues had proposed as SiLU earlier that year. Noam Shazeer showed in 2020 that gated variants such as SwiGLU improve Transformers, and they spread to most large language models.
Try it
- Compute softmax of multiplied by 10, that is . What happens to the probabilities? Then try dividing by 10. (This scaling factor is called temperature. See Decoding: Temperature, Top-k and Top-p.)
- Show that for two classes, .
- In the PyTorch digits network from Neural Networks, swap
nn.Sigmoid()fornn.ReLU()and thennn.GELU(). Compare test accuracy after 100 steps.Hint for 2: divide the top and bottom of by .
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Stanford CS231n: Deep Learning for Computer Vision
Famous course notes on neural nets, backprop, CNNs and training, written very clearly.
Dive into Deep Learning
An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.
Understanding Deep Learning
A modern, beautifully illustrated textbook covering everything from basics to Transformers and diffusion, with notebooks.
Deep Sparse Rectifier Neural Networks
Showed that deep networks of rectified linear units (ReLUs) train well and produce sparse activations, helping make ReLU the default.
Gaussian Error Linear Units (GELUs)
Introduces GELU, the smooth ReLU-like activation later used in BERT and GPT models.
Searching for Activation Functions
Uses automated search to find Swish (x · sigmoid(βx)), the activation also known as SiLU.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/dl/activation-functions.md