The Wayback Machine - https://web.archive.org/web/20240926131803/https://www.geeksforgeeks.org/activation-functions-in-pytorch/
Open In App

Activation Functions in Pytorch

Last Updated : 12 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will Understand PyTorch Activation Functions. 

What is an activation function and why to use them?

Activation functions are the building blocks of Pytorch. Before coming to types of activation function, let us first understand the working of neurons in the human brain. In the Artificial Neural Networks, we have an input layer which is the input by the user in some format, a hidden layer that performs the hidden calculations and identifies features and output is the result. So the whole structure is like a network with neurons connected to one another. So we have artificial neurons which are activated by these activation functions. The activation function is a function that performs calculations to provide an output that may act as input for the next neurons. An ideal activation function should handle non-linear relationships by using the linear concepts and it should be differentiable so as to reduce the errors and adjust the weights accordingly. All activation functions are present in the torch.nn library.

Types of Pytorch Activation Function

Let us look at the different Pytorch Activation functions:

  • ReLU Activation Function
  • Leaky ReLU Activation Function
  • Sigmoid Activation Function
  • Tanh Activation Function
  • Softmax Activation Function

ReLU Activation Function:

ReLU stands for Rectified Linear Activation function. It is a non-linear function and, graphically ReLU has the following transformative behavior:

ReLU Activation Function

 

ReLU is a popular activation function since it is differentiable and nonlinear. If the inputs are negative its derivative becomes zero which causes the ‘dying’ of neurons and learning doesn’t take place. Let us illustrate the use of ReLU with the help of the Python program.

Python
import torch
import torch.nn as nn

# defining relu
r = nn.ReLU()

# Creating a Tensor with an array
input = torch.Tensor([1, -2, 3, -5])

# Passing the array to relu function
output = r(input)

print(output)

Output:

tensor([1., 0., 3., 0.])

Leaky ReLU Activation Function:

Leaky ReLU Activation Function or LReLU is another type of activation function which is similar to ReLU but solves the problem of ‘dying’ neurons and, graphically Leaky ReLU has the following transformative behavior:

Leaky ReLU Activation Function

 

This function is very useful as when the input is negative the differentiation of the function is not zero. Hence the learning of neurons doesn’t stop.  Let us illustrate the use of LReLU with the help of the Python program.

Python
# code
import torch
import torch.nn as nn

# defining Lrelu and the parameter 0.2 is passed to control the negative slope ; a=0.2
r = nn.LeakyReLU(0.2)

# Creating a Tensor with an array 
input = torch.Tensor([1,-2,3,-5])

output = r(input) 

print(output)

Output:

tensor([ 1.0000, -0.4000,  3.0000, -1.0000])

Sigmoid Activation Function:

Sigmoid Function is a non-linear and differentiable activation function. It is an S-shaped curve that does not pass through the origin. It produces an output that lies between 0 and 1. The output values are often treated as a probability. It is often used for binary classification. It is slow in computation and, graphically Sigmoid has the following transformative behavior:

Sigmoid Activation Function

 

Sigmoid activation function has a problem of “Vanishing Gradient”.  Vanishing Gradient is a significant problem as a large number of inputs are fed to the neural network and the number of hidden layers increases, the gradient or derivative becomes close to zero thus leading to inaccuracy in the neural network.

Let us illustrate the use of the Sigmoid function with the help of a Python Program.

Python
import torch
import torch.nn as nn

# Calling the sigmoid function
sig = nn.Sigmoid()

# Defining tensor
input = torch.Tensor([1,-2,3,-5]) 

# Applying sigmoid to the tensor
output = sig(input)

print(output) 

Output:

tensor([0.7311, 0.1192, 0.9526, 0.0067])

Tanh Activation Function:

Tanh function is a non-linear and differentiable function similar to the sigmoid function but output values range from -1 to +1. It is an S-shaped curve that passes through the origin and, graphically Tanh has the following transformative behavior:

Tanh Activation Function

 

The problem with the Tanh Activation function is it is slow and the vanishing gradient problem persists. Let us illustrate the use of the Tanh function with the help of a Python Program.

Python
import torch
import torch.nn as nn

# Calling the Tanh function
t = nn.Tanh()

# Defining tensor
input = torch.Tensor([1,-2,3,-5]) 

# Applying Tanh to the tensor
output = t(input) 
print(output) 

Output:

tensor([ 0.7616, -0.9640,  0.9951, -0.9999])

Softmax Activation Function:

The softmax function is different from other activation functions as it is placed at the last to normalize the output. We can use other activation functions in combination with Softmax to produce the output in probabilistic form. It is used in multiclass classification and generates an output of probabilities whose sum is 1. The range of output lies between 0 and 1. Softmax has the following transformative behavior:

Softmax Activation Function

Let us illustrate with the help of the Python Program:

Python
import torch
import torch.nn as nn

# Calling the Softmax function with 
# dimension = 0 as dimension starts 
# from 0
sm = nn.Softmax(dim=0)  

# Defining tensor
input = torch.Tensor([1,-2,3,-5]) 

# Applying function to the tensor
output = sm(input) 
print(output)

Output:

tensor([0.7311, 0.1192, 0.9526, 0.0067])


Previous Article
Next Article

Similar Reads

Extending PyTorch with Custom Activation Functions
In the context of deep learning and neural networks, activation functions are mathematical functions that are applied to the output of a neuron or a set of neurons. The output of the activation function is then passed on as input to the next layer of neurons. The purpose of an activation function is to introduce non-linearity into the network. With
7 min read
Swish activation function in Pytorch
Activation functions are a fundamental component of artificial neural networks. They introduce non-linearity into the model, allowing it to learn complex relationships in the data. One such activation function, the Swish activation function, has gained attention for its unique properties and potential advantages over the widely used Rectified Linea
6 min read
Understanding Activation Functions in Depth
What is an Activation function ? In artificial neural networks, the activation function of a node defines the output of that node or neuron for a given input or set of inputs. This output is then used as input for the next node and so on until a desired solution to the original problem is found. It maps the resulting values into the desired range s
8 min read
PyTorch vs PyTorch Lightning
The PyTorch research team at Facebook AI Research (FAIR) introduced PyTorch Lightning to address these challenges and provide a more organized and standardized approach. In this article, we will see the major differences between PyTorch Lightning and Pytorch. Table of Content PytorchPytorch Lightning: Advanced Framework of PytorchPytorch vs Pytorch
9 min read
How to disable GPU in PyTorch (force Pytorch to use CPU instead of GPU)?
PyTorch is a deep learning framework that offers GPU acceleration. This enables the users to utilize the GPU's processing power. The main goal is to accelerate the training and interference processes of deep learning models. PyTorch automatically utilizes the GPU for operations and this leads to quicker computation times. Using the GPU for PyTorch
5 min read
Pytorch Functions - tensor(), fill_diagnol(), append(), index_copy()
This article aims to share some PyTorch functions that will help you a lot in your deep learning and data science journey. Each function will be explained using two write examples and one example where you can't use those functions. So let's get started. PyTorch is an open-source machine learning library, it contains a tensor library that enables t
9 min read
5 Statistical Functions for Random Sampling in PyTorch
PyTorch is an open source machine learning library used for deep learning with more flexibility and feasibility. This is an extension of NumPy. For Statistical Functions for Random Sampling, let's see what they are along with their easy implementations. To run all these the first step is to import Pytorch by import torch. There are 5 functions: tor
6 min read
PyTorch Loss Functions
Loss functions are a crucial component in neural network training, as every machine learning model requires optimization, which helps in reducing the loss and making correct predictions. Without loss functions, there's no way to drive your model to make correct predictions. But what exactly are loss functions, and how do you use them? In this artic
12 min read
Mathematical Functions in Python | Set 1 (Numeric Functions)
In python a number of mathematical operations can be performed with ease by importing a module named "math" which defines various functions which makes our tasks easier. 1. ceil() :- This function returns the smallest integral value greater than the number. If number is already integer, same number is returned. 2. floor() :- This function returns t
3 min read
Mathematical Functions in Python | Set 2 (Logarithmic and Power Functions)
Numeric functions are discussed in set 1 below Mathematical Functions in Python | Set 1 ( Numeric Functions) Logarithmic and power functions are discussed in this set. 1. exp(a) :- This function returns the value of e raised to the power a (e**a) . 2. log(a, b) :- This function returns the logarithmic value of a with base b. If base is not mentione
3 min read
Mathematical Functions in Python | Set 3 (Trigonometric and Angular Functions)
Some of the mathematical functions are discussed in below set 1 and set 2 Mathematical Functions in Python | Set 1 (Numeric Functions) Mathematical Functions in Python | Set 2 (Logarithmic and Power Functions) Trigonometric and angular functions are discussed in this article. 1. sin() :- This function returns the sine of value passed as argument. T
3 min read
Mathematical Functions in Python | Set 4 (Special Functions and Constants)
Some of the mathematical functions are discussed in below set 1, set 2 and set 3 Mathematical Functions in Python | Set 1 (Numeric Functions) Mathematical Functions in Python | Set 2 (Logarithmic and Power Functions) Mathematical Functions in Python | Set 3 (Trigonometric and Angular Functions) Special Functions and constants are discussed in this
2 min read
Python | PyTorch sin() method
PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes. The function torch.sin() provides support for the sine function in PyTorch. It expects the input in radian form and the output is in the range [-1, 1]. The input type is tensor and if the input conta
2 min read
Create Model using Custom Module in Pytorch
Custom module in Pytorch A custom module in PyTorch is a user-defined module that is built using the PyTorch library's built-in neural network module, torch.nn.Module. It's a way of creating new modules by combining and extending the functionality provided by existing PyTorch modules. The torch.nn.Module class provides a convenient way to create cu
8 min read
Graphs, Automatic Differentiation and Autograd in PyTorch
Graphs, Automatic Differentiation and Autograd are powerful tools in PyTorch that can be used to train deep learning models. Graphs are used to represent the computation of a model, while Automatic Differentiation and Autograd allow the model to learn by updating its parameters during training. In this article, we will explore the concepts behind t
7 min read
Install Pytorch on Linux
In this article, we are going to see how you can install PyTorch in the Linux system. We are using Ubuntu 20 LTS you can use any other one. To successfully install PyTorch in your Linux system, follow the below procedure: First, check if you are using python’s latest version or not. Because PyGame requires python 3.7 or a higher version, make sure
2 min read
Python | PyTorch sinh() method
PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes. The function torch.sinh() provides support for the hyperbolic sine function in PyTorch. It expects the input in radian form. The input type is tensor and if the input contains more than one element,
2 min read
Python | PyTorch cosh() method
PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes. The function torch.cosh() provides support for the hyperbolic cosine function in PyTorch. It expects the input in radian form. The input type is tensor and if the input contains more than one element
2 min read
Python | PyTorch tanh() method
PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes.One of the many activation functions is the hyperbolic tangent function (also known as tanh) which is defined as [Tex]tanh(x) = (e^x - e^{-x}) / (e^x + e^{-x}) [/Tex].The hyperbolic tangent function o
2 min read
Python | PyTorch cos() method
PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes.The function torch.cos() provides support for the cosine function in PyTorch. It expects the input in radian form and the output is in the range [-1, 1]. The input type is tensor and if the input cont
2 min read
Python | PyTorch tan() method
PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes. The function torch.tan() provides support for the tangent function in PyTorch. It expects the input in radian form and the output is in the range [-∞, ∞]. The input type is tensor and if
2 min read
Python | PyTorch asin() method
PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes.The function torch.asin() provides support for the inverse sine function in PyTorch. It expects the input to be in the range [-1, 1] and gives the output in radian form. It returns nan if the input do
2 min read
Python | PyTorch acos() method
PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes. The function torch.acos() provides support for the inverse cosine function in PyTorch. It expects the input to be in the range [-1, 1] and gives the output in radian form. It returns nan if the input
2 min read
Python | PyTorch atan() method
PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes. The function torch.atan() provides support for the inverse tangent function in PyTorch. It gives the output in radian form. The input type is tensor and if the input contains more than one element, e
2 min read
Deep Learning with PyTorch | An Introduction
PyTorch in a lot of ways behaves like the arrays we love from Numpy. These Numpy arrays, after all, are just tensors. PyTorch takes these tensors and makes it simple to move them to GPUs for the faster processing needed when training neural networks. It also provides a module that automatically calculates gradients (for backpropagation) and another
7 min read
Python PyTorch – RandomHorizontalFlip() Function
In this article, we will discuss the RandomHorizontalFlip() Method in PyTorch Python. RandomHorizontalFlip() method RandomHorizontalFlip() method of torchvision.transforms module is used to horizontally flip the given image at a random angle with a given probability. This method accepts a PIL and tensor image as input. The tensor image is a PyTorch
2 min read
How To Sort The Elements of a Tensor in PyTorch?
In this article, we are going to see how to sort the elements of a PyTorch Tensor in Python. To sort the elements of a PyTorch tensor, we use torch.sort() method. We can sort the elements along with columns or rows when the tensor is 2-dimensional. Syntax: torch.sort(input, dim=- 1, descending=False) Parameters: input: It is an input PyTorch tensor
3 min read
Python PyTorch zeros() method
PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes. The function torch.zeros() returns a tensor filled with the scalar value 0, with the shape defined by the variable argument size. Syntax: torch.zeros(size, out=None) Parameters: size: a sequence of i
1 min read
Python Pytorch ones() method
PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes. The function torch.ones() returns a tensor filled with the scalar value 1, with the shape defined by the variable argument size. Syntax: torch.ones(size, out=None) Parameters: size: a sequence of int
1 min read
Python Pytorch arrange() method
PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes.The function torch.arrange() returns a 1-D tensor of size [Tex]\left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil [/Tex]with values from the interval [Tex][start, end) [/Tex]taken
2 min read
Article Tags :
Practice Tags :