Why does a neural network put a small extra function after every layer, and why does the choice of that function decide how well a deep network trains? Without it, two layers are one matrix and ten are still one (P1.B6, P4.3). Put between two layers and the single matrix can no longer stand in for the network: gives with the matrices of P1.B6, not .
That small step is an activation function. This lesson covers the common choices, what each does to the slope that training depends on, and how to choose.
What an activation function is
A neuron (P4.1) computes a weighted sum of its inputs plus a bias, . Call the pre-activation. The neuron then passes through a fixed function and outputs , its activation. For a whole layer, with the weights in a matrix and the biases in :
The function is applied to each entry on its own: . It has no weights to learn (one variant in this lesson has a learned slope, noted where it comes up), and the same is usually used for all the hidden units of a layer. The whole story of this lesson is the choice of .
Why a nonlinearity at all
The matrix example above is the general fact. A linear layer applies , and a second one gives , which is one matrix and one bias . Ten layers are still one (P1.B6). Hidden layers with a nonlinear between the matrices do not collapse, and P4.3 shows how such layers bend the plane until a hard task becomes separable. A network with only the linear steps could not even learn XOR (P4.2).
Two requirements follow, and the rest of the lesson keeps coming back to them:
- It must not be linear. Any straight-line would let the layers collapse again.
- It needs a useful slope. Training moves each weight by the slope of the loss with respect to it (P1.C5), and the chain rule (P1.C3) multiplies in for every activation the signal passes. Where is 0 or tiny, the signal is cut.
Hidden layers and the output layer
A network has hidden layers (between input and output) and an output layer. Hidden activations are chosen to make training work. The output activation is chosen to match what the answer must look like, and a later section treats it. Everything before that section is about hidden units.
The step: the first idea, and why it fails
The perceptron of P4.1 used the step (or threshold) function: output 1 if and 0 otherwise. Its range is . It gives a clean yes or no, and it is where the idea of a neuron “firing” comes from.
Its slope is the trouble. For the curve is flat, so the slope is 0, and at it jumps, so there is no slope (P1.C1). A small nudge to a weight changes a little and the output not at all, so the loss does not change and the gradient is 0. Gradient descent has no direction to follow. The perceptron rule of P4.2 trains a single threshold unit by a different update that does not use a gradient, and it does not extend directly to hidden layers. That is why networks trained by backpropagation use a smooth curve in its place, such as the sigmoid, which is the step with its jump rounded off (P1.A5).
Sigmoid and tanh: saturating curves
P1.A5 built both. In short: has range , equals at , and has range and equals at . The two are one curve scaled and shifted: . This lesson adds their slopes.
Slopes. From P1.C2, and . The largest slope is at :
- , so everywhere;
- , so everywhere.
(Differentiating gives , which agrees: .)
Saturation. For large the curves are flat: and . A unit in that region passes almost no gradient back. This is saturation, and it matters twice. A saturated unit is stuck, because changing its weights barely changes its output. And the slopes multiply along a path of layers (P1.C3):
- ten sigmoid layers each at their best slope give at most (the bound P1.A5 and P1.C3 quote, with the weights ignored);
- tanh does better near 0, with a best slope of 1, but it still saturates.
The effect is vanishing gradients. P4.16 treats it in full, and a widget below shows it.
Zero-centred or not. The sigmoid’s outputs are all positive. The next layer’s weights then see only positive inputs , and the gradient for weight is (gradient at the unit) . All of a unit’s incoming weights get gradients with the same sign, so in one step they all increase or all decrease together, which makes for a zig-zag path to the best weights. This is one reason often given for preferring tanh, whose outputs are centred on 0, in hidden layers (P1.A5). Other tools reduce the problem too, such as normalization (P4.19).
Cost. Both need an exponential per entry, which is slower than the comparison ReLU needs. In a large layer, the matrix product usually costs much more than the activation.
ReLU: the workhorse
The rectified linear unit is : negative inputs become 0, and positive inputs pass unchanged (P1.A1). Its range is .
Its slope is 0 for and 1 for . For a unit that is on, the signal passes back unchanged by the activation, with no extra factor of (P1.C3). A unit that is off blocks the signal. Backprop (P4.8) treats it as a gate: gradient times 1 or times 0.
The corner. At exactly the curve has a corner, so there is no true slope (P1.C5). Software picks a convention. PyTorch’s ReLU gives slope 0 at (the code below confirms it), and P4.8 uses the same. Once a unit has a nonzero bias and real-valued inputs, is rarely exactly 0, so the choice seldom matters in training.
Not linear, only piecewise linear. ReLU is made of two straight pieces, yet it is not a straight line, and that bend is what the opening example used. Where it is flat on the left, it is exactly 0. If were a standard Gaussian number, half of the outputs would be exactly 0, because (P1.D2). Many exact zeros is called sparse activation.
The cost: dead units. A unit whose is negative for every input in the training data has slope 0 everywhere that matters. It outputs 0, gets zero gradient, and its weights stop changing, so it can stay off. This is a dead ReLU. A tiny example: a unit with and sees inputs , and . Then , and , and the outputs are all 0. Whatever gradient arrives from above is multiplied by 0, so and . Nothing in the gradient pushes back up. How a unit gets there varies (a large update step, a poor start, or a shift in the data), and how often it happens depends on the learning rate, the initialization (P4.12) and the data. It is a known risk, not a certainty. The code below runs this example.
Leaky ReLU, PReLU and ELU: keep some slope on the left
Leaky ReLU replaces the flat left half with a small slope (often ): for and otherwise. The slope is or , and is not 0 when , so a unit that is off still gets a small gradient. In the dead-unit example above, with a gradient of arriving for each of the three inputs, a ReLU unit gets and a Leaky ReLU unit with gets , a small push to turn back on (the code below confirms it). The idea was used for acoustic models by Maas, Hannun and Ng (2013). PReLU (He et al., 2015) makes a learned parameter, trained by gradient descent like a weight.
ELU (Clevert, Unterthiner and Hochreiter, 2015) is for and for , with in this lesson. For negative it curves smoothly down towards , so it saturates on the left. With its slope is 1 on both sides of 0, so it has no corner. It is in the widget but is not covered further.
Softplus: a smooth ReLU
Softplus is . It has no corner, is always positive, and is close to for very negative and close to for large positive . Its value at 0 is (not 0, so it is a little above ReLU). Its slope is : the sigmoid is the slope of the softplus. (P1.C8 uses it as a smooth ReLU.) Because for every , its slope is below 1 everywhere, so it is a poorer carrier of gradients than ReLU. It is often used when a smooth positive output is needed, more than as a hidden activation.
GELU and SiLU: smooth, self-gated
Both multiply the input by a smooth gate that runs from 0 to 1:
is the cumulative distribution function of a standard Gaussian (P1.D2), the probability that a standard Gaussian number is at most . So GELU is “ times the probability that a Gaussian number lands below it”. For , and . SiLU uses the sigmoid as its gate: and . For large positive the gate is near 1 and the output is near , like ReLU. For large negative the gate is near 0 and the output is near 0.
Their slopes are , with the Gaussian density, and . Three things set them apart from ReLU:
- Smooth. No corner anywhere, so there is no convention to pick.
- Not monotonic. They dip below 0 and come back. GELU has its lowest value, about , near . SiLU has its lowest value, about , near . To the left of the dip the slope is negative.
- Slope can exceed 1. The largest slope is about for GELU (near ) and about for SiLU (near ).
Names. The two curves are close but different. Hendrycks and Gimpel (2016) introduced GELU, , and also discussed , which they called the SiLU (sigmoid linear unit). Elfwing, Uchibe and Doya (first posted in 2017) used the same function as a sigmoid-weighted linear unit for reinforcement learning. Ramachandran, Zoph and Le (2017) found it again by an automated search and called it Swish, defined with a parameter as ; with it is the SiLU. PyTorch calls the version SiLU, and the names are often used for the same curve.
Go deeper The tanh form of GELU, and a cheaper stand-in
Computing needs the error function , since . An approximation that uses only is
with given by
It is given in the GELU paper and is available in PyTorch as approximate="tanh". Running the check on a fine grid from to shows the two differ by at most about . At the exact value is and the approximation is . The same paper also notes as a rougher approximation, and that one is off by up to about on the same grid. Which version a trained model used matters if you want to reproduce its numbers exactly.
A table of numbers to check by hand
Every entry below was computed with code and rounded to three decimals. In the first three tables each cell shows the value and then the slope, as /; the last two tables give them in separate columns. Check one with your own calculator, for example and .
The sigmoid and tanh:
| tanh | ||
|---|---|---|
| −2 | 0.119/0.105 | −0.964/0.071 |
| −0.5 | 0.378/0.235 | −0.462/0.786 |
| 0 | 0.500/0.250 | 0.000/1.000 |
| 0.5 | 0.622/0.235 | 0.462/0.786 |
| 2 | 0.881/0.105 | 0.964/0.071 |
ReLU and Leaky ReLU (). At the slopes shown are the PyTorch values (0 for ReLU, for Leaky ReLU):
| ReLU | Leaky | |
|---|---|---|
| −2 | 0.000/0.000 | −0.020/0.010 |
| −0.5 | 0.000/0.000 | −0.005/0.010 |
| 0 | 0.000/0.000 | 0.000/0.010 |
| 0.5 | 0.500/1.000 | 0.500/1.000 |
| 2 | 2.000/1.000 | 2.000/1.000 |
Softplus and ELU ():
| Softplus | ELU | |
|---|---|---|
| −2 | 0.127/0.119 | −0.865/0.135 |
| −0.5 | 0.474/0.378 | −0.393/0.607 |
| 0 | 0.693/0.500 | 0.000/1.000 |
| 0.5 | 0.974/0.622 | 0.500/1.000 |
| 2 | 2.127/0.881 | 2.000/1.000 |
GELU:
| GELU | GELU′ | |
|---|---|---|
| −2 | −0.046 | −0.085 |
| −0.5 | −0.154 | 0.133 |
| 0 | 0.000 | 0.500 |
| 0.5 | 0.346 | 0.867 |
| 2 | 1.954 | 1.085 |
and SiLU:
| SiLU | SiLU′ | |
|---|---|---|
| −2 | −0.238 | −0.091 |
| −0.5 | −0.189 | 0.260 |
| 0 | 0.000 | 0.500 |
| 0.5 | 0.311 | 0.740 |
| 2 | 1.762 | 1.091 |
Things to notice: the sigmoid and tanh slopes fall off on both sides; ReLU and Leaky ReLU slopes are 1 from on; the softplus slope is the sigmoid column; the GELU and SiLU slopes are negative at and above 1 at .
See the curves and their slopes
In the widget, blue is the function and orange is its slope. Choose up to three activations, and move to read and for each.
Things to try:
- Choose Sigmoid and tanh. The orange peaks at are and , and both slopes are close to 0 at : saturation.
- Choose ReLU. Move across 0: the orange slope jumps from 0 to 1, and the blue curve has a corner.
- Choose GELU and SiLU. Both dip below 0 for moderate negative and their orange curves rise above 1 before settling at 1.
- Choose Step. The blue curve jumps at 0, and the orange slope is 0 on both sides, lying along the axis. Nothing for gradient descent to use.
A summary of the properties
| Activation | Range | Largest slope; flat where |
|---|---|---|
| Step | 0; flat | |
| Sigmoid | ; both tails | |
| tanh | 1; both tails | |
| ReLU | 1; | |
| Leaky ReLU | all reals | 1; none ( on the left) |
| Softplus | below 1; left tail | |
| ELU | 1; left tail | |
| GELU | about 1.13; left tail | |
| SiLU | about 1.10; left tail |
“Tail” means large , where the curve is nearly flat; “left” is large negative . The sigmoid and tanh have both. Their largest slope is at .
What the choice does to a network
Two experiments on the same made-up data show the effects. The data are 80 points in the plane: 40 in a disc around the origin (circles) and 40 in a ring around that disc (squares). A straight line cannot separate them.
The network has two hidden layers of 8 units with the chosen activation and a sigmoid output unit. Plain gradient descent (learning rate 1) trains it from the same starting weights, whatever activation you choose. Drag the slider to see the boundary (where the network’s probability is 0.5), the loss and how many of the 80 points are on the right side. Under the plane, the bars show a second experiment: a deeper stack of 6 hidden layers of 8 units, before any training, and the size of the gradient of the loss in each of its 7 layers (layer 1 is next to the input).
What the fixed start and fixed data give (running the same code in NumPy reproduces every number):
- Step. The loss stays near after 500 steps and only 45 of the 80 points are correct. The hidden layers get a gradient of exactly 0, so only the output weights move, on top of fixed random step features. 45 of 80 is 56 percent, near the 50 percent of guessing.
- Sigmoid. The loss is after 500 steps and 72 points are correct. It is still falling, but its loss is still after 200 steps, when every activation except the step is below . The slow start of the sigmoid in the small network is not itself measured as a vanishing gradient; the deeper stack shows the mechanism. In the deeper stack, the gradient in the output layer is about 47,000 times the gradient in layer 1, and the first layers receive almost nothing.
- tanh, ReLU, Leaky ReLU, ELU, GELU, SiLU. All reach 80 of 80 points correct by 100 steps, with a loss under . In the deeper stack the output-layer gradient is between 0.9 and 2.3 times the layer-1 gradient (tanh 0.9, ReLU 1.5, Leaky 1.6, SiLU 1.9, ELU 2.1, GELU 2.3).
- Softplus. It also ends with 80 of 80 correct, but its loss is at step 50, above its starting loss of , and the deeper stack shows a ratio of about 540. Its slope is , below 1 everywhere, so slopes multiply down a path as for the sigmoid, though less severely.
These numbers belong to one start, one learning rate (1) and one kind of starting weights (Glorot-uniform). A different scale of starting weights changes the picture a lot, which is the subject of P4.12, and the matter of long chains of slopes is the subject of P4.16. The robust lesson is the direction: slopes well below 1 shrink the gradient with depth, and slopes of 0 remove it.
Output activations are a different choice
The last layer’s activation follows the form of the answer, not the training behaviour of the hidden layers:
- A real number (regression, P3.A2): no activation, or the identity. A sigmoid output would limit the answer to .
- One probability (binary classification): a sigmoid, as in logistic regression (P3.A7). The loss is then binary cross-entropy (P4.6). This is what the tiny network above uses.
- Several classes: softmax (P3.A8), which turns a vector of scores into probabilities that add to 1.
- A positive number: a softplus or an exponential is often used.
Softmax is not an elementwise activation. Every other function here takes and returns from that one number. Softmax gives , so each output depends on all the scores. Changing one entry changes every output. It is an output-layer tool and is not used as a hidden activation in the sense of this lesson.
Which one should I use?
Practice, not a theorem:
- ReLU is a common default for the hidden layers of MLPs and convolutional networks. It is simple and trains well, with He initialization (P4.12).
- Leaky ReLU or ELU are options to try when many ReLU units are dead.
- GELU and SiLU are common in transformers and in many recent models (P7.7). Some recent decoder models use a gated feed-forward layer built from SiLU, called SwiGLU (P10.C1).
- Sigmoid and tanh are mostly kept for places where a bounded number is needed: probabilities at the output, and the gates and cell values in a recurrent cell such as the LSTM (P6.7).
- Step is the original perceptron activation (P4.1). It still appears as a final yes or no threshold on a probability, but not as a hidden activation trained by gradient descent.
Differences between ReLU, GELU and SiLU are often smaller than those from the learning rate, the initialization and the normalization, and published comparisons depend on the task. When you copy an architecture, copy its activation too.
Depth: three ways to see it
Intuition
Think of each activation as a gate at the exit of a neuron. The step is a door that is shut or open. The sigmoid opens smoothly, but its tails barely react. ReLU is a one-way valve: it passes positive values unchanged and blocks the rest. Leaky ReLU is a valve with a pinhole. GELU and SiLU open gradually near 0, with a slight dip on the negative side. Training works by feeling how each gate responds to a small change, so a gate that does not respond (slope 0) gives training nothing to feel.
Math
For a layer, and entry by entry. In backprop (P4.8), if is the gradient arriving at , then the gradient at is .
Through sigmoid layers the slope factors alone multiply to at most , and . The weights also enter every factor (P1.C3).
Code
import torch
import torch.nn.functional as F
z = torch.tensor([-2.0, -0.5, 0.0, 0.5, 2.0], requires_grad=True)
for name, fn in [("ReLU", torch.relu), ("GELU", F.gelu), ("SiLU", F.silu)]:
z.grad = None
fn(z).sum().backward() # sum, so z.grad holds f'(z)
print(name, z.grad.numpy().round(3))Output from a local run with PyTorch 2.9.1:
ReLU [0. 0. 0. 1. 1.]
GELU [-0.085 0.133 0.5 0.867 1.085]
SiLU [-0.091 0.26 0.5 0.74 1.091]The ReLU slope at is 0, the convention above. In a model you would use torch.nn.ReLU(), torch.nn.LeakyReLU(0.01), torch.nn.GELU() or torch.nn.SiLU().
Try it in Python
The first cell compares the slopes of five activations with a numerical slope, and the second runs the dead-unit example. Both use NumPy only.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Common mistakes
Quiz
Check your understanding
A network has ten layers, each computing with no activation between them. What can it represent?
Two linear layers multiply into one matrix, and so do ten, so the number of parameters is a distraction: the function is still a single linear map plus a bias. The result does not depend on how many layers there are, so two layers is not a special case, and large weights do not change a linear map into a nonlinear one.
Why can a network of step-function hidden units not be trained with gradient descent?
A small change to a weight changes z a little and the step output not at all, so the gradient is 0 and there is nothing to follow. The step is defined for every input, its outputs are only 0 and 1, and it is not linear (it jumps), so the collapse argument is not the reason.
A sigmoid unit has . By what factor, at most, does it scale the gradient passing back through it?
The slope is at 0, which is also its largest value. The value 1 is the largest slope of tanh, not of the sigmoid. The output is the value of the function and not its slope, and the sigmoid is flat in its tails, not at 0.
A ReLU unit has for every training example and the loss gradient arriving at it is nonzero. What does the unit pass back to its weights, and what does Leaky ReLU with do differently?
The ReLU slope is 0 for negative z, so the gradient is multiplied by 0 and the unit can stay off. Leaky ReLU multiplies by its left slope, 0.01, so a small push remains. ReLU does not pass back the full gradient on the left side, and the small slope belongs to the leaky version, not to ReLU.
You build a network to output the probability that an email is spam. Which function should turn the output score into a probability?
A sigmoid maps any score to a number between 0 and 1, which can be read as a probability (P3.A7). ReLU has no upper bound, so it can output values above 1. Softmax over one number is always 1, which carries no information. With no function the output can be any real number, not a probability. (Libraries often fold the sigmoid into the loss function for numerical reasons; that is still a sigmoid, applied inside the loss.)
Exercises
- Compute and , then , to three decimals.
Show answer
, so . , so . - A gradient of arrives at a ReLU unit whose input is . What gradient does it pass to ? What if the input were ? What about a Leaky ReLU with at ?
Show answer
For the ReLU slope is 0, so . For the slope is 1, so . The Leaky ReLU at passes . - Compute and from their definitions, given and .
Show answer
. . - Ten sigmoid layers are stacked and each is at its steepest point, . Ignoring the weights, by what factor does a gradient shrink between layer 10 and layer 1? What if each were a tanh unit at ?
Show answer
For the sigmoid, . For tanh at the slope is 1, so the factor from the slopes is . Real units are rarely all at , so tanh also shrinks the gradient once some units saturate, and the weights also scale it. - Show with one pair of numbers that ReLU is not a linear function, and say what the “not linear” property buys a network.
Show answer
, but , so it fails . A network with it between layers does not collapse into one matrix, so extra layers add power.
Next: P4.5 writes the forward pass in matrix form, with the shapes of a whole batch flowing through the layers. P4.6 covers the loss functions that go after the output activation, and P4.8 shows how the slopes in this lesson enter backpropagation.