The Wayback Machine - https://web.archive.org/web/20241009042343/https://www.geeksforgeeks.org/backpropagation-in-neural-network/
Open In App

Backpropagation in Neural Network

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

Machine learning models learn from data and make predictions. One of the fundamental concepts behind training these models is backpropagation. In this article, we will explore what backpropagation is, why it is crucial in machine learning, and how it works.

A neural network is a network structure, by the presence of computing units(neurons) the neural network has gained the ability to compute the function. The neurons are connected with the help of edges, and it is said to have an assigned activation function and also contains the adjustable parameters. These adjustable parameters help the neural network to determine the function that needs to be computed by the network. In terms of activation function in neural networks, the higher the activation value is the greater the activation is.

What is backpropagation?

  • In machine learning, backpropagation is an effective algorithm used to train artificial neural networks, especially in feed-forward neural networks.
  • Backpropagation is an iterative algorithm, that helps to minimize the cost function by determining which weights and biases should be adjusted. During every epoch, the model learns by adapting the weights and biases to minimize the loss by moving down toward the gradient of the error. Thus, it involves the two most popular optimization algorithms, such as gradient descent or stochastic gradient descent.
  • Computing the gradient in the backpropagation algorithm helps to minimize the cost function and it can be implemented by using the mathematical rule called chain rule from calculus to navigate through complex layers of the neural network.
Frame-13
fig(a) A simple illustration of how the backpropagation works by adjustments of weights


Advantages of Using the Backpropagation Algorithm in Neural Networks

Backpropagation, a fundamental algorithm in training neural networks, offers several advantages that make it a preferred choice for many machine learning tasks. Here, we discuss some key advantages of using the backpropagation algorithm:

  1. Ease of Implementation: Backpropagation does not require prior knowledge of neural networks, making it accessible to beginners. Its straightforward nature simplifies the programming process, as it primarily involves adjusting weights based on error derivatives.
  2. Simplicity and Flexibility: The algorithm’s simplicity allows it to be applied to a wide range of problems and network architectures. Its flexibility makes it suitable for various scenarios, from simple feedforward networks to complex recurrent or convolutional neural networks.
  3. Efficiency: Backpropagation accelerates the learning process by directly updating weights based on the calculated error derivatives. This efficiency is particularly advantageous in training deep neural networks, where learning features of a function can be time-consuming.
  4. Generalization: Backpropagation enables neural networks to generalize well to unseen data by iteratively adjusting weights during training. This generalization ability is crucial for developing models that can make accurate predictions on new, unseen examples.
  5. Scalability: Backpropagation scales well with the size of the dataset and the complexity of the network. This scalability makes it suitable for large-scale machine learning tasks, where training data and network size are significant factors.

In conclusion, the backpropagation algorithm offers several advantages that contribute to its widespread use in training neural networks. Its ease of implementation, simplicity, efficiency, generalization ability, and scalability make it a valuable tool for developing and training neural network models for various machine learning applications.

Working of Backpropagation Algorithm

The Backpropagation algorithm works by two different passes, they are:

  • Forward pass
  • Backward pass

How does Forward pass work?

  • In forward pass, initially the input is fed into the input layer. Since the inputs are raw data, they can be used for training our neural network.
  • The inputs and their corresponding weights are passed to the hidden layer. The hidden layer performs the computation on the data it receives. If there are two hidden layers in the neural network, for instance, consider the illustration fig(a), h1 and h2 are the two hidden layers, and the output of h1 can be used as an input of h2. Before applying it to the activation function, the bias is added.
  • To the weighted sum of inputs, the activation function is applied in the hidden layer to each of its neurons. One such activation function that is commonly used is ReLU can also be used, which is responsible for returning the input if it is positive otherwise it returns zero. By doing this so, it introduces the non-linearity to our model, which enables the network to learn the complex relationships in the data. And finally, the weighted outputs from the last hidden layer are fed into the output to compute the final prediction, this layer can also use the activation function called the softmax function which is responsible for converting the weighted outputs into probabilities for each class.
forwards-pass
The forward pass using weights and biases

How does backward pass work?

  • In the backward pass process shows, the error is transmitted back to the network which helps the network, to improve its performance by learning and adjusting the internal weights.
  • To find the error generated through the process of forward pass, we can use one of the most commonly used methods called mean squared error which calculates the difference between the predicted output and desired output. The formula for mean squared error is: Mean squared error = (predicted output – actual output)^2
  • Once we have done the calculation at the output layer, we then propagate the error backward through the network, layer by layer.
  • The key calculation during the backward pass is determining the gradients for each weight and bias in the network. This gradient is responsible for telling us how much each weight/bias should be adjusted to minimize the error in the next forward pass. The chain rule is used iteratively to calculate this gradient efficiently.
  • In addition to gradient calculation, the activation function also plays a crucial role in backpropagation, it works by calculating the gradients with the help of the derivative of the activation function.

Example of Backpropagation in Machine Learning

Let us now take an example to explain backpropagation in Machine Learning,

Assume that the neurons have the sigmoid activation function to perform forward and backward pass on the network. And also assume that the actual output of y is 0.5 and the learning rate is 1. Now perform the backpropagation using backpropagation algorithm.

example-1
Example (1) of backpropagation sum

Implementing forward propagation:

Step1: Before proceeding to calculating forward propagation, we need to know the two formulae:

a_j = \sum (w_i,j * x_i)

Where,

  • aj is the weighted sum of all the inputs and weights at each node,
  • wi,j – represents the weights associated with the jth input to the ith neuron,
  • xi – represents the value of the jth input,

y_j = F(a_j) = \frac 1 {1+e^{-aj}}, yi – is the output value, F denotes the activation function [sigmoid activation function is used here), which transforms the weighted sum into the output value.

Step 2: To compute the forward pass, we need to compute the output for y3 , y4 , and y5.

example-2
To find the outputs of y3, y4 and y5

We start by calculating the weights and inputs by using the formula:

a_j = ∑ (w_{i,j} * x_i) To find y3 , we need to consider its incoming edges along with its weight and input. Here the incoming edges are from X1 and X2.

At h1 node,

\begin {aligned} a_1 &= (w_{1,1} x_1) + (w_{2,1} x_2) \\& = (0.2 * 0.35) + (0.2* 0.7) \\&= 0.21 \end {aligned}

Once, we calculated the a1 value, we can now proceed to find the y3 value:

y_j= F(a_j) = \frac 1 {1+e^{-aj}}

y_3 = F(0.21) = \frac 1 {1+e^{-0.21}}

y_3 = 0.56

Similarly find the values of y4 at h2 and y5 at O3 ,

a2 = (w_{1,2} * x_1) + (w_{2,2} * x_2) = (0.3*0.35)+(0.3*0.7)=0.315

y_4 = F(0.315) = \frac 1{1+e^{-0.315}}

a3 = (w_{1,3}*y_3)+(w_{2,3}*y_4) =(0.3*0.57)+(0.9*0.59) =0.702

y_5 = F(0.702) = \frac 1 {1+e^{-0.702} } = 0.67

example-3
Values of y3, y4 and y5


Note that, our actual output is 0.5 but we obtained 0.67. To calculate the error, we can use the below formula:

Error_j= y_{target} – y_5

Error = 0.5 – 0.67

= -0.17

Using this error value, we will be backpropagating.

Implementing Backward Propagation

Each weight in the network is changed by,

∇wij = η ?j Oj
?j = Oj (1-Oj)(tj - Oj) (if j is an output unit)
?j = Oj (1-O)∑k ?k wkj (if j is a hidden unit)  
where ,


η is the constant which is considered as learning rate,

tj is the correct output for unit j

?j is the error measure for unit j

Step 3: To calculate the backpropagation, we need to start from the output unit:

To compute the ?5, we need to use the output of forward pass,

?5 = y5(1-y5) (ytarget -y5)

= 0.67(1-0.67) (-0.17)

= -0.0376

For hidden unit,

To compute the hidden unit, we will take the value of ?5

?3 = y3(1-y3) (w1,3 * ?5)

=0.56(1-0.56) (0.3*-0.0376)

=-0.0027

?4 = y4 (1-y5) (w2,3 * ?5)

=0.59(1-0.59) (0.9*-0.0376)

=-0.0819

Step 4: We need to update the weights, from output unit to hidden unit,

∇ wj,i = η ?j Oj


Note- Here our learning rate is 1

∇ w2,3 = η ?5 O4

= 1 * (-0.376) * 0.59

= -0.22184

We will be updating the weights based on the old weight of the network,

w2,3(new) = ∇ w4,5 + w4,5 (old)

= -0.22184 + 0.9

= 0.67816

From hidden unit to input unit,

For an hidden to input node, we need to do calculations by the following;

∇ w1,1 = η ?3 O4

= 1 * (-0.0027) * 0.35

= 0.000945

Similarly, we need to calculate the new weight value using the old one:

w1,1(new) = ∇ w1,1+ w1,1 (old)

= 0.000945 + 0.2

= 0.200945

Similarly, we update the weights of the other neurons: The new weights are mentioned below

w1,2 (new) = 0.271335

w1,3 (new) = 0.08567

w2,1 (new) = 0.29811

w2,2 (new) = 0.24267

The updated weights are illustrated below,

example-4-(1)
Through backward pass the weights are updated


Once, the above process is done, we again perform the forward pass to find if we obtain the actual output as 0.5.

While performing the forward pass again, we obtain the following values:

y3 = 0.57

y4 = 0.56

y5 = 0.61

We can clearly see that our y5 value is 0.61 which is not an expected actual output, So again we need to find the error and backpropagate through the network by updating the weights until the actual output is obtained.

Error = y_{target} – y_5

= 0.5 – 0.61

= -0.11

This is how the backpropagate works, it will be performing the forward pass first to see if we obtain the actual output, if not we will be finding the error rate and then backpropagating backwards through the layers in the network by adjusting the weights according to the error rate. This process is said to be continued until the actual output is gained by the neural network.

Python program for backpropagation

Here’s a simple implementation of feedforward neural network with backpropagation in Python:

  1. Neural Network Initialization: The NeuralNetwork class is initialized with parameters for the input size, hidden layer size, and output size. It also initializes the weights and biases with random values.
  2. Sigmoid Activation Function: The sigmoid method implements the sigmoid activation function, which squashes the input to a value between 0 and 1.
  3. Sigmoid Derivative: The sigmoid_derivative method calculates the derivative of the sigmoid function. It computes the gradients of the loss function with respect to weights.
  4. Feedforward Pass: The feedforward method calculates the activations of the hidden and output layers based on the input data and current weights and biases. It uses matrix multiplication to propagate the inputs through the network.
  5. Backpropagation: The backward method performs the backpropagation algorithm. It calculates the error at the output layer and propagates it back through the network to update the weights and biases using gradient descent.
  6. Training the Neural Network: The train method trains the neural network using the specified number of epochs and learning rate. It iterates through the training data, performs the feedforward and backward passes, and updates the weights and biases accordingly.
  7. XOR Dataset: The XOR dataset (X) is defined, which contains input pairs that represent the XOR operation, where the output is 1 if exactly one of the inputs is 1, and 0 otherwise.
  8. Testing the Trained Model: After training, the neural network is tested on the XOR dataset (X) to see how well it has learned the XOR function. The predicted outputs are printed to the console, showing the neural network’s predictions for each input pair.
Python
import numpy as np

class NeuralNetwork:
    def __init__(self, input_size, hidden_size, output_size):
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.output_size = output_size

        # Initialize weights
        self.weights_input_hidden = np.random.randn(self.input_size, self.hidden_size)
        self.weights_hidden_output = np.random.randn(self.hidden_size, self.output_size)

        # Initialize the biases
        self.bias_hidden = np.zeros((1, self.hidden_size))
        self.bias_output = np.zeros((1, self.output_size))

    def sigmoid(self, x):
        return 1 / (1 + np.exp(-x))

    def sigmoid_derivative(self, x):
        return x * (1 - x)

    def feedforward(self, X):
        # Input to hidden
        self.hidden_activation = np.dot(X, self.weights_input_hidden) + self.bias_hidden
        self.hidden_output = self.sigmoid(self.hidden_activation)

        # Hidden to output
        self.output_activation = np.dot(self.hidden_output, self.weights_hidden_output) + self.bias_output
        self.predicted_output = self.sigmoid(self.output_activation)

        return self.predicted_output

    def backward(self, X, y, learning_rate):
        # Compute the output layer error
        output_error = y - self.predicted_output
        output_delta = output_error * self.sigmoid_derivative(self.predicted_output)

        # Compute the hidden layer error
        hidden_error = np.dot(output_delta, self.weights_hidden_output.T)
        hidden_delta = hidden_error * self.sigmoid_derivative(self.hidden_output)

        # Update weights and biases
        self.weights_hidden_output += np.dot(self.hidden_output.T, output_delta) * learning_rate
        self.bias_output += np.sum(output_delta, axis=0, keepdims=True) * learning_rate
        self.weights_input_hidden += np.dot(X.T, hidden_delta) * learning_rate
        self.bias_hidden += np.sum(hidden_delta, axis=0, keepdims=True) * learning_rate

    def train(self, X, y, epochs, learning_rate):
        for epoch in range(epochs):
            output = self.feedforward(X)
            self.backward(X, y, learning_rate)
            if epoch % 4000 == 0:
                loss = np.mean(np.square(y - output))
                print(f"Epoch {epoch}, Loss:{loss}")

X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([[0], [1], [1], [0]])

nn = NeuralNetwork(input_size=2, hidden_size=4, output_size=1)
nn.train(X, y, epochs=10000, learning_rate=0.1)

# Test the trained model
output = nn.feedforward(X)
print("Predictions after training:")
print(output)

Output:

Epoch 0, Loss:0.36270360966344145
Epoch 4000, Loss:0.005546947165311874
Epoch 8000, Loss:0.00202378766386817
Predictions after training:
[[0.02477654]
 [0.95625286]
 [0.96418129]
 [0.04729297]]






Similar Reads

Backpropagation in Convolutional Neural Networks
Convolutional Neural Networks (CNNs) have become the backbone of many modern image processing systems. Their ability to learn hierarchical representations of visual data makes them exceptionally powerful. A critical component of training CNNs is backpropagation, the algorithm used for effectively updating the network's weights. This article delves
4 min read
How Does Gradient Descent and Backpropagation Work Together?
Answer: Gradient descent updates the model parameters iteratively using gradients computed by backpropagation, which efficiently calculates the gradients of the loss function concerning each parameter in a neural network.Gradient descent and backpropagation are essential components of training neural networks. Here's a detailed explanation of how t
2 min read
How to Update Bias and Bias's Weight Using Backpropagation Algorithm?
Answer: In backpropagation, biases are updated by applying the chain rule to the loss function with respect to the bias parameters in each layer during gradient descent.Let's explore the details of how biases and their weights are updated using the backpropagation algorithm: Backpropagation Overview:Backpropagation is an algorithm used to train art
3 min read
A single neuron neural network in Python
Neural networks are the core of deep learning, a field that has practical applications in many different areas. Today neural networks are used for image classification, speech recognition, object detection, etc. Now, Let's try to understand the basic unit behind all these states of art techniques.A single neuron transforms given input into some out
3 min read
Effect of Bias in Neural Network
Neural Network is conceptually based on actual neuron of brain. Neurons are the basic units of a large neural network. A single neuron passes single forward based on input provided. In Neural network, some inputs are provided to an artificial neuron, and with each input a weight is associated. Weight increases the steepness of activation function.
3 min read
Importance of Convolutional Neural Network | ML
Convolutional Neural Network as the name suggests is a neural network that makes use of convolution operation to classify and predict. Let's analyze the use cases and advantages of a convolutional neural network over a simple deep learning network. Weight sharing: It makes use of Local Spatial coherence that provides same weights to some of the edg
2 min read
Neural Network Advances
We know that our world is changing quickly but there are lot of concrete technology advances that you might not hear a lot about in the newspaper or on tv, that are nevertheless having a dramatic impact on our lives. Some of these big new stories are related to the ANN(Artificial Neural Network) - a relatively new phenomenon in artificial intellige
3 min read
Why For loop is not preferred in Neural Network Problems?
For loop take much time for completing iterations and in ML practise we have to optimize the time so we can use for loops. But then you must be wondering what to use then? Don't worry we will discuss this in the below section. How to get rid from loop in Machine Learning or Neural Network? The solution is Vectorization. Now the question arises what
2 min read
Implementation of Artificial Neural Network for AND Logic Gate with 2-bit Binary Input
Artificial Neural Network (ANN) is a computational model based on the biological neural networks of animal brains. ANN is modeled with three types of layers: an input layer, hidden layers (one or more), and an output layer. Each layer comprises nodes (like biological neurons) are called Artificial Neurons. All nodes are connected with weighted edge
4 min read
Implementation of Artificial Neural Network for OR Logic Gate with 2-bit Binary Input
Artificial Neural Network (ANN) is a computational model based on the biological neural networks of animal brains. ANN is modeled with three types of layers: an input layer, hidden layers (one or more), and an output layer. Each layer comprises nodes (like biological neurons) are called Artificial Neurons. All nodes are connected with weighted edge
4 min read
Implementation of Artificial Neural Network for NAND Logic Gate with 2-bit Binary Input
Artificial Neural Network (ANN) is a computational model based on the biological neural networks of animal brains. ANN is modeled with three types of layers: an input layer, hidden layers (one or more), and an output layer. Each layer comprises nodes (like biological neurons) are called Artificial Neurons. All nodes are connected with weighted edge
4 min read
Implementation of Artificial Neural Network for NOR Logic Gate with 2-bit Binary Input
Artificial Neural Network (ANN) is a computational model based on the biological neural networks of animal brains. ANN is modeled with three types of layers: an input layer, hidden layers (one or more), and an output layer. Each layer comprises nodes (like biological neurons) are called Artificial Neurons. All nodes are connected with weighted edge
4 min read
Implementation of Artificial Neural Network for XOR Logic Gate with 2-bit Binary Input
Artificial Neural Network (ANN) is a computational model based on the biological neural networks of animal brains. ANN is modeled with three types of layers: an input layer, hidden layers (one or more), and an output layer. Each layer comprises nodes (like biological neurons) are called Artificial Neurons. All nodes are connected with weighted edge
4 min read
Implementation of Artificial Neural Network for XNOR Logic Gate with 2-bit Binary Input
Artificial Neural Network (ANN) is a computational model based on the biological neural networks of animal brains. ANN is modeled with three types of layers: an input layer, hidden layers (one or more), and an output layer. Each layer comprises nodes (like biological neurons) are called Artificial Neurons. All nodes are connected with weighted edge
4 min read
Difference between Neural Network And Fuzzy Logic
Neural Network: Neural network is an information processing system that is inspired by the way biological nervous systems such as brain process information. A neural network is composed of a large number of interconnected processing elements known as neurons which are used to solve problems. A neural network is an attempt to make a computer model o
2 min read
ANN - Implementation of Self Organizing Neural Network (SONN) from Scratch
Prerequisite: ANN | Self Organizing Neural Network (SONN) Learning Algorithm To implement a SONN, here are some essential consideration- Construct a Self Organizing Neural Network (SONN) or Kohonen Network with 100 neurons arranged in a 2-dimensional matrix with 10 rows and 10 columns Train the network with 1500 2-dimensional input vectors randomly
4 min read
ANN - Self Organizing Neural Network (SONN)
Self Organizing Neural Network (SONN) is an unsupervised learning model in Artificial Neural Network termed as Self-Organizing Feature Maps or Kohonen Maps. These feature maps are the generated two-dimensional discretized form of an input space during the model training (based on competitive learning). This phenomenon is very similar to biological
2 min read
ANN - Self Organizing Neural Network (SONN) Learning Algorithm
Prerequisite: ANN | Self Organizing Neural Network (SONN) In the Self Organizing Neural Network (SONN), learning is performed by shifting the weights from inactive connections to active ones. The neurons which were won are selected to learn along with their neighborhood neurons. If a neuron does not respond for a specific input pattern, then learni
3 min read
Adjusting Learning Rate of a Neural Network in PyTorch
Learning Rate is an important hyperparameter in Gradient Descent. Its value determines how fast the Neural Network would converge to minima. Usually, we choose a learning rate and depending on the results change its value to get the optimal value for LR. If the learning rate is too low for the Neural Network the process of convergence would be very
7 min read
Architecture and Learning process in neural network
In order to learn about Backpropagation, we first have to understand the architecture of the neural network and then the learning process in ANN. So, let's start about knowing the various architectures of the ANN: Architectures of Neural Network: ANN is a computational system consisting of many interconnected units called artificial neurons. The co
9 min read
Applications of Neural Network
A neural network is a processing device, either an algorithm or genuine hardware, that endeavors to recognize underlying relationships in a set of data through a process that mimics the way the human brain operates. The computing world has a ton to acquire from neural networks, also known as artificial neural networks or neural nets. The neural net
3 min read
How to Visualize a Neural Network in Python using Graphviz ?
In this article, We are going to see how to plot (visualize) a neural network in python using Graphviz. Graphviz is a python module that open-source graph visualization software. It is widely popular among researchers to do visualizations. It's representing structural information as diagrams of abstract graphs and networks means you only need to pr
4 min read
Deep parametric Continuous Convolutional Neural Network
Deep Parametric Continuous Kernel convolution was proposed by researchers at Uber Advanced Technologies Group. The motivation behind this paper is that the simple CNN architecture assumes a grid-like architecture and uses discrete convolution as its fundamental block. This inhibits their ability to perform accurate convolution to many real-world ap
6 min read
Convolutional Neural Network (CNN) Architectures
Convolutional Neural Network(CNN) is a neural network architecture in Deep Learning, used to recognize the pattern from structured arrays. However, over many years, CNN architectures have evolved. Many variants of the fundamental CNN Architecture This been developed, leading to amazing advances in the growing deep-learning field. Let's discuss, How
11 min read
Transformer Neural Network In Deep Learning - Overview
In this article, we are going to learn about Transformers. We'll start by having an overview of Deep Learning and its implementation. Moving ahead, we shall see how Sequential Data can be processed using Deep Learning and the improvement that we have seen in the models over the years. Deep Learning So now what exactly is Deep Learning? But before w
10 min read
Training of Convolutional Neural Network (CNN) in TensorFlow
In this article, we are going to implement and train a convolutional neural network CNN using TensorFlow a massive machine learning library. Now in this article, we are going to work on a dataset called 'rock_paper_sissors' where we need to simply classify the hand signs as rock paper or scissors. Stepwise ImplementationStep 1: Importing the librar
5 min read
Working of Convolutional Neural Network (CNN) in Tensorflow
In this article, we are going to see the working of convolution neural networks with TensorFlow a powerful machine learning library to create neural networks. Now to know, how a convolution neural network lets break it into parts. the 3 most important parts of this convolution neural networks are, ConvolutionPoolingFlattening These 3 actions are th
5 min read
Convolutional Neural Network (CNN) in Tensorflow
It is assumed that the reader knows the concepts of Neural Networks and Convolutional Neural Networks. If you are sure about the topics please refer to Neural Networks and Convolutional Neural Networks. Building Blocks of CNN: Convolutional Neural Networks are mainly made up of three types of layers: Convolutional Layer: It is the main building blo
4 min read
Difference between a Neural Network and a Deep Learning System
Since their inception in the late 1950s, Artificial Intelligence and Machine Learning have come a long way. These technologies have gotten quite complex and advanced in recent years. While technological advancements in the Data Science domain are commendable, they have resulted in a flood of terminologies that are beyond the understanding of the av
7 min read
What is Padding in Neural Network?
As we know while building a neural network we are doing convolution to extract features with the help of kernels with respect to the current datasets which is the important part to make your network learn while convolving. For example, if you want to train your neural network to classify whether it is a dog or cat then while applying convolution, k
9 min read