Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 22

Common Activation Functions

This lesson is built with resources from github.com and machinelearningmastery.com.

Hello! Welcome back to our module on Deep Learning with PyTorch.

In the last lesson, we constructed the blueprint for a feedforward neural network (FNN). We saw how an FNN is built from layers of neurons, and that each neuron performs a linear operation () followed by an activation function. We briefly included nn.Sigmoid in our code, but didn't explore what it really does or what alternatives exist.

Today's lesson fulfills the learning outcome: Apply common activation functions including Sigmoid, Tanh, and ReLU. We will investigate the critical role these functions play. You'll learn why they are essential for a neural network's learning capabilities and how to choose and implement the right one for your model in PyTorch.

1. The Role of Activation Functions: Introducing Non-Linearity

In the previous lesson, we established that a neuron computes a weighted sum of its inputs and adds a bias. This is a linear operation. If we were to stack multiple layers of these linear operations, the entire network would still only be able to represent a linear function.

Mathematically, if and , then , which is just another linear function.

This is a major limitation because most real-world data contains complex, non-linear patterns. To overcome this, we apply a non-linear activation function to the output of each neuron. This simple addition is what gives neural networks their immense power to approximate any complex function.

Let's begin with a reading that explains this concept.

machine-learning-articles/using-relu-sigmoid-and-tanh-with-pytorch-ignite-and-lightning.md at main · christianversloot/machine-learning-articles · GitHub

This article provides a clear explanation of what activation functions are and why their non-linearity is crucial for neural networks.

Please read the section titled 'Activation functions: what are they?'. Focus on understanding why stacking linear operations is insufficient and how activation functions introduce the necessary non-linearity.


2. A Visual Tour of Common Activation Functions

The three most common activation functions you will encounter, especially in foundational and modern architectures, are Sigmoid, Tanh, and ReLU. Each has distinct characteristics.

Graphs of Common Activation Functions
A visual comparison of the Tanh, ReLU, Sigmoid, and Linear activation functions. Notice the distinct shapes and output ranges that give each function its unique properties.

Let's dive into each of these in more detail.


3. Deep Dive: Sigmoid, Tanh, and ReLU

For each function, we will look at its properties, pros, cons, and how to implement it in PyTorch.

3.1. Sigmoid (Logistic) Function

The Sigmoid function takes any real-valued number and "squashes" it into a range between 0 and 1.

This makes it particularly useful for the output layer of a binary classification model, where the output can be interpreted as a probability.

To see its shape and a simple PyTorch implementation, please read the following section.

Activation Functions in PyTorch

This article from Machine Learning Mastery will introduce the Sigmoid function, show you how to plot it, and discuss its properties.

Read the section 'Logistic Activation Function'. Pay attention to its output range (0 to 1) and the associated PyTorch code.

Pros & Cons:

  • Pro: Excellent for binary classification output layers.
  • Con (Vanishing Gradients): As you can see from the graph, for very large positive or negative inputs, the function's slope (gradient) becomes extremely close to zero. During backpropagation (which we'll cover soon), these tiny gradients get multiplied across many layers, causing the gradients in the early layers to "vanish." This effectively stops the network from learning.
  • Con (Not zero-centered): The outputs are always positive (between 0 and 1). This can slow down the training process.

3.2. Tanh (Hyperbolic Tangent) Function

The Tanh function is mathematically related to Sigmoid, but it squashes values to a range between -1 and 1.

Being zero-centered makes it generally preferred over Sigmoid for hidden layers.

Activation Functions in PyTorch

Let's now look at the Tanh function in the same article.

Read the section 'Tanh Activation Function' to understand its shape and implementation.

Pros & Cons:

  • Pro (Zero-centered): Its output is centered around 0, which helps the optimization process during training.
  • Con (Vanishing Gradients): Like Sigmoid, Tanh also suffers from the vanishing gradient problem in its saturated regions (flat parts of the curve).

3.3. ReLU (Rectified Linear Unit)

ReLU is the most popular activation function for hidden layers in modern neural networks. Its definition is disarmingly simple.

If the input is positive, it returns the input; otherwise, it returns 0.

Activation Functions in PyTorch

Finally, let's examine the ReLU function, the current default choice for most deep learning tasks.

Read the section 'ReLU Activation Function'. Note its simplicity and how it differs from Sigmoid and Tanh.

Pros & Cons:

  • Pro (Computationally Efficient): The max(0, x) operation is much faster to compute than the exponentials in Sigmoid and Tanh.
  • Pro (Avoids Vanishing Gradients): For positive inputs, the gradient is constant (equal to 1), which prevents it from vanishing and allows for faster learning.
  • Con (Dying ReLU Problem): If a neuron's input is consistently negative, it will always output 0. Consequently, its gradient will also be 0, and the neuron's weights will never be updated. The neuron effectively "dies" and stops contributing to the network.

For a consolidated summary of these trade-offs, this next reading is excellent.

machine-learning-articles/using-relu-sigmoid-and-tanh-with-pytorch-ignite-and-lightning.md at main · christianversloot/machine-learning-articles · GitHub

This article summarizes the benefits and drawbacks of each function, providing context on why ReLU has become so popular despite its own issues.

Read the bullet points under the image that detail the benefits and drawbacks of ReLU, Sigmoid, and Tanh. This is a crucial section for understanding the practical implications of your choice.

Test your understanding!

You are tasked with building a neural network to predict house prices (a regression task). Which activation function—Sigmoid, Tanh, or ReLU—would be a poor choice for the final output layer? Why? What about for the hidden layers?

Show answer
  • Final Output Layer: Sigmoid and Tanh would be poor choices. Sigmoid caps the output between 0 and 1, and Tanh caps it between -1 and 1. House prices can be large positive numbers, so these functions would prevent the model from ever predicting a price outside their limited range. A linear activation (i.e., no activation) is typically used for regression outputs, although ReLU could also work if prices are always positive.

  • Hidden Layers: ReLU is the standard, modern choice for hidden layers due to its efficiency and ability to mitigate the vanishing gradient problem. Tanh is a reasonable alternative, but Sigmoid is rarely used in hidden layers of deep networks today because of its non-zero-centered output and strong susceptibility to vanishing gradients.


4. Applying Activation Functions in PyTorch

As a software engineer, you'll appreciate that PyTorch offers two clean ways to add activation functions to your models, catering to different coding styles.

  1. Module-based (nn): You can instantiate an activation function as a layer in your __init__ method (e.g., self.relu = nn.ReLU()) and call it in forward. This is common when using nn.Sequential.
  2. Functional (torch.nn.functional): You can directly call the function in your forward method (e.g., out = F.relu(out)). This offers more flexibility for complex forward passes.

The following resource clearly demonstrates both approaches.

machine-learning-articles/using-relu-sigmoid-and-tanh-with-pytorch-ignite-and-lightning.md at main · christianversloot/machine-learning-articles · GitHub

Let's see the code. This guide shows how to implement all three activation functions using both the module-based and functional APIs in PyTorch.

Read the section 'Implementing ReLU, Sigmoid and Tanh with PyTorch', focusing on the subsection 'Classic PyTorch'. Observe the two different code snippets: one that adds nn.Sigmoid() inside nn.Sequential, and another that uses F.sigmoid() in the forward method.


5. Seeing the Impact: A Practical Example

Theory is useful, but seeing the impact of these choices in a real training scenario provides a deeper understanding. The following resource trains a simple neural network on the MNIST dataset using different activation functions and compares their performance.

Activation Functions in PyTorch

Let's see how the choice of activation function affects a model's training performance on a real task.

Read the sections 'Exploring Activation Functions in a Neural Network' and 'Training and Testing the Model with Different Activation Functions'. You don't need to run the code yourself right now, but study the structure. Notice how the NeuralNetwork class takes an activation_function as a parameter, allowing for easy experimentation. Then, look at the final printed output, which shows the test accuracy for models trained with ReLU, Sigmoid, and Tanh. You'll likely see that ReLU and Tanh perform better than Sigmoid in this case.

This practical demonstration highlights that while the code change is minor, the impact on model performance can be significant. It underscores why understanding these components is vital for an AI engineer.


Conclusion

In this lesson, you've moved from knowing that activation functions exist to understanding why they are essential and how to apply them. You are now equipped to make informed decisions about which activation function to use in different parts of your network.

Key Takeaways:

  • Purpose: Activation functions introduce the non-linearity that allows neural networks to learn complex patterns.
  • Sigmoid: Squashes output to (0, 1). Best for binary classification outputs. Suffers from vanishing gradients.
  • Tanh: Squashes output to (-1, 1). A good choice for hidden layers as it's zero-centered, but still suffers from vanishing gradients.
  • ReLU: Outputs max(0, x). The modern default for hidden layers due to its computational efficiency and resistance to vanishing gradients for positive inputs. Can suffer from the "dying ReLU" problem.
  • Implementation: PyTorch allows you to apply activations as modules (nn.ReLU()) or as functions (F.relu).

Next up:

So far, we've only discussed how data flows forward through the network to produce a prediction. But how does the network learn from its mistakes? In the next lesson, we will conceptually explore backpropagation, the core algorithm that calculates the error gradient and enables the network to update its weights, and see how to implement the full forward pass.