Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Activation Functions

So far we have focused on the linear regression part of the network model and set aside the activation function of the M-P neuron model.

In theory, if we only use linear regression, a network model with any number of layers is still a linear transformation and is not fundamentally different from a single-layer network model. This is exactly what we observed in the previous chapter.

💡 Tip: According to the universal approximation theorem, it has been mathematically proven that, under certain conditions, a network model with at least one hidden layer and a nonlinear activation function can approximate any continuous function to arbitrary precision.

To make a neural network truly powerful, we must introduce nonlinearity. This is what an activation function does. Using activation functions between linear layers frees the network model from being limited to linear models, so that it can learn more complex relationships between inputs and outputs.

The activation function is part of the artificial neuron. In deep learning practice, however, it is usually designed as a separate layer that works together with the linear layers.

Tensor

Dataset

Model

Abstract layer

Linear layer

Sequential layer

Activation functions

Rectified linear unit (ReLU)

The rectified linear unit (ReLU) is the most commonly used activation function for intermediate hidden layers. Its logic is very simple: negative numbers become zero.

The advantages of the ReLU activation function are obvious:

  • it is computationally efficient and only needs a threshold operation;

  • it filters out all negative numbers. This can be understood as filtering out all the unimportant information, or noise;

  • all positive numbers stay unchanged, and the derivative is always 1 in the positive range. So it does not weaken useful information and avoids vanishing gradients. This is essential for training deep networks.


Forward propagation: negative numbers are set to zero.

y=ReLU(x)=max⁡(0,x)y = \text{ReLU}(x) = \max(0, x)

Gradient computation: positive numbers keep their gradient. The derivative of the ReLU activation function is:

dydx={1if x>00if x≤0\frac{dy}{dx} = \begin{cases} 1 & \text{if } x > 0 \\ 0 & \text{if } x \leq 0 \end{cases}

Parent list (parents): the input.

Parameter list (parameters): none, because there are no parameters to train.

Let’s look at the effect of the ReLU activation function:

<Figure size 500x300 with 1 Axes>

Hyperbolic tangent (Tanh)

The hyperbolic tangent (Tanh) maps any value into the range (−1,1)(-1, 1) while preserving the relative relationships between values. It can be used to remove extreme values caused by “overexposure” and center the data around zero. Like the ReLU activation function, it is commonly used in intermediate hidden layers.


Forward propagation: the hyperbolic tangent maps the input into the range (−1,1)(-1, 1). The output is zero-centered (its mean is 0). We simply call the tanh function provided by NumPy to compute it.

y=tanh⁡(x)=ex−e−xex+e−xy = \tanh(x) = \frac{e^x - e^{-x}}{e^x + e^{-x}}

Gradient computation: the derivative of the Tanh activation function can be expressed with the function itself. This means we do not need to compute the complicated exponential functions again. The derivative of the Tanh activation function is:

dydx=1−tanh⁡2(x)=1−y2\frac{dy}{dx} = 1 - \tanh^2(x) = 1 - y^2

When the input is very large or very small, the derivative approaches 0. This is what we usually call gradient saturation. In deep networks, it makes the signal passed back weaker and weaker, and eventually leads to vanishing gradients.

Parent list (parents): the input.

Parameter list (parameters): none.

Let’s look at the effect of the Tanh activation function:

<Figure size 500x300 with 1 Axes>

Sigmoid

The sigmoid function (also called the logistic curve) smoothly squashes any value into the range (0,1)(0, 1). The output can therefore be interpreted as the probability of an event, and it is commonly used in the output layer of binary classification problems to regularize the prediction.


Forward propagation: the probability of logistic regression, mapping any real number into the interval (0,1)(0, 1). Commonly used in the output layer of binary classification problems.

y=σ(x)=11+e−xy = \sigma(x) = \frac{1}{1 + e^{-x}}

Gradient computation: the derivative of the Sigmoid activation function can also be expressed with the function itself. The derivative of the Sigmoid activation function is:

dydx=σ(x)⋅(1−σ(x))=y(1−y)\frac{dy}{dx} = \sigma(x) \cdot (1 - \sigma(x)) = y(1 - y)

The Sigmoid activation function also suffers from gradient saturation. In deep networks, the gradient may vanish. In addition, the Sigmoid activation function suffers from gradient decay.

Parent list (parents): the input.

Parameter list (parameters): none.

Let’s look at the effect of the Sigmoid activation function:

<Figure size 500x300 with 1 Axes>

Softmax

The softmax function (normalized exponential function) works on a group of values: it converts them into relative proportions of one another and keeps the total at 1. It is therefore commonly used in the output layer of multi-class classification problems, where the option with the largest value is the prediction.


Forward propagation: maps any real vector to a probability distribution, so that every component lies in the interval (0,1)(0, 1) and all the components sum to 1. Commonly used in the output layer of multi-class classification problems.

yi=exi∑j=1nexjy_i = \frac{e^{x_i}}{\sum_{j=1}^{n} e^{x_j}}

Gradient computation: the Softmax activation function is a vector function, and its gradient is a Jacobian matrix. The derivative of the Softmax activation function is:

∂L∂xi=yi(gi−∑j=1nyjgj)\frac{\partial L}{\partial x_i} = y_i (g_i - \sum_{j=1}^{n} y_j g_j)

Where:

  • yiy_i: the ii-th output of Softmax;

  • gig_i: the gradient of the loss with respect to the ii-th output, that is, the gradient passed back from the next layer;

  • nn: the number of components of the vector.

The meaning of this formula is intuitive: first compute the average gradient weighted by all the output probabilities, then output the difference between each component’s gradient and the average gradient.

Parent list (parents): the input.

Parameter list (parameters): none.

Let’s look at the effect of the Softmax activation function:

<Figure size 500x300 with 1 Axes>

The Softmax activation function is a vector function, so we can see how its components relate to one another.

The figure compares the variable xx with two constants, 0.1 and 0.9, after they pass through the Softmax activation function. We can see that when xx is less than 0.9, the best choice is always 0.9; when xx is greater than 0.9, the best choice becomes xx; and 0.1 is never the best choice.

Loss function (mean squared error)

Optimizer (stochastic gradient descent)

Trainer

Hyperparameters

Learning rate

Batch size

Number of epochs

Modeling

Now let’s apply the ReLU activation function after the hidden layer and see what effect it has.

💡 Tip: In regression models that predict numerical values, no activation function is usually needed after the output layer. Later we will see that in classification models, an activation function is also used after the output layer to help with the decision.

With the hidden layer activation function, the three core processes of the model change a little (the parameter update does not change):

  1. Forward propagation:

Forward propagation with the ReLU layer: the feature x goes through hidden.forward() (parameters w₁, b₁) and relu.forward() to produce the intermediate value h, and then through output.forward() (parameters w₂, b₂) to produce the prediction p
Figure: Forward propagation (model inference)
  1. Backpropagation:

Backpropagation with the ReLU layer: loss.backward() computes the error term d from the prediction p and the label y, and output.backward() (using w₂) and relu.backward() then produce the gradient g
Figure: Backpropagation (gradient computation)
  1. Parameter update:

Parameter update in the two-layer network: optimizer.step() updates w₂ and b₂ from the error term d and the intermediate value h, and updates w₁ and b₁ from the gradient g and the feature x
Figure: Parameter update

Training

Evaluation

prediction:	Tensor([[164.60610313]])
loss:	Tensor(0.15515474192848927)

In the previous chapter, we observed that the two-layer network model worked, but did not perform better than the single-layer model and was even slightly worse.

After we add the hidden layer activation function, however, the loss drops to 0.16, close to 0.

This shows that after introducing a nonlinear activation function, the model has a stronger expressive power: it fits the training data well and gives reasonable predictions on the test sample.

Summary

The four activation functions compare as follows:

Activation functionMain useAdvantagesDisadvantagesRecommended position
ReLUDefault first choice
Handles nonlinear features
Fast to compute
No gradient saturation in the positive range
Mitigates vanishing gradients
Zero gradient in the negative range
Neurons may “die permanently”
Hidden layers
TanhData with positive and negative valuesZero-centered output (mean 0)
Makes the next layer converge faster
Gradient saturation
Exponentials are expensive to compute
Hidden layers
SigmoidProbability prediction for binary classificationSmoothly squashes the output into (0,1)(0, 1)
Output can be interpreted as a probability
Output mean is not 0
Severe gradient saturation
Causes vanishing gradients
Binary classification
output layer
SoftmaxProbability prediction for multi-class classificationHandles the probabilities of several classes
Ensures the probabilities sum to 1
Complex to compute
Sensitive to extreme values
Multi-class classification
output layer

Exercises

  1. Try Tanh as the activation function, or use Sigmoid or Softmax after the output layer, and see how the training results change.