The Wayback Machine - https://web.archive.org/web/20240818075315/https://www.geeksforgeeks.org/what-is-forward-propagation-in-neural-networks/
Open In App

What is Forward Propagation in Neural Networks?

Last Updated : 01 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Feedforward neural networks stand as foundational architectures in deep learning. Neural networks consist of an input layer, at least one hidden layer, and an output layer. Each node is connected to nodes in the preceding and succeeding layers with corresponding weights and thresholds. In this article, we will explore what is forward propagation and it’s working.

What is Forward Propagation in Neural Networks?

Forward propagation is the process in a neural network where the input data is passed through the network’s layers to generate an output. It involves the following steps:

  1. Input Layer: The input data is fed into the input layer of the neural network.
  2. Hidden Layers: The input data is processed through one or more hidden layers. Each neuron in a hidden layer receives inputs from the previous layer, applies an activation function to the weighted sum of these inputs, and passes the result to the next layer.
  3. Output Layer: The processed data moves through the output layer, where the final output of the network is generated. The output layer typically applies an activation function suitable for the task, such as softmax for classification or linear activation for regression.
  4. Prediction: The final output of the network is the prediction or classification result for the input data.

Forward propagation is essential for making predictions in neural networks. It calculates the output of the network for a given input based on the current values of the weights and biases. The output is then compared to the actual target value to calculate the loss, which is used to update the weights and biases during the training process.

Mathematical Explanation of Forward Propagation

Capture

  • In the above picture , the first layer of [Tex]X_{i1} , X_{i2} , X_{i3} , X_{i4}[/Tex] are the input layer and last layer of [Tex]b_{31}[/Tex] is the output layer .
  • Other layers are hidden layers in this structure of ANN . this is a 4 layered deep ANN where first hidden layer consists of 3 neuron and second layer consists of 2 neuron .
  • There are total 26 trainable parameters . here , in hidden layer 1 , the top to bottom biases are [Tex]b_{11} , b_{12} , b_{13}[/Tex] and in hidden layer 2 , the top to bottom biases are [Tex]b_{21}, b_{22}[/Tex] . the output layer contains the neuron having bias b31 . likewise the weights of corresponding connections are assigned like [Tex]W_{111}, W_{112}, W_{113} , W_{121}, W_{122} [/Tex]etc.
  • Here, considering we are using sigmoid function as the activation function

The output prediction function is: [Tex]\sigma(w^\Tau x+ b)[/Tex]

Inside Layer 1

Here, from the previous output function , weights and biases are segmented as matrices and the dot product has been done along with matrix manipulation .

The procedure of the matrix operations for layer 1 are as follows:

[Tex]\sigma\left(\begin{bmatrix} W_{111} & W_{112} & W_{113} \\ W_{121} & W_{122} & W_{123} \\ W_{131} & W_{132} & W_{133} \\ W_{141} & W_{142} & W_{143} \end{bmatrix}^T \begin{bmatrix} X_{i1} \\ X_{i2} \\ X_{i3} \\ X_{i4} \end{bmatrix} + \begin{bmatrix} b_{11} \\ b_{12} \\ b_{13} \end{bmatrix}\right) = \sigma\left(\begin{bmatrix} W_{111}X_{i1} + W_{121}X_{i2} + W_{131}X_{i3} + W_{141}X_{i4} \\ W_{112}X_{i1} + W_{122}X_{i2} + W_{132}X_{i3} + W_{142}X_{i4} \\ W_{113}X_{i1} + W_{123}X_{i2} + W_{133}X_{i3} + W_{143}X_{i4} \end{bmatrix} + \begin{bmatrix} b_{11} \\ b_{12} \\ b_{13} \end{bmatrix}\right) = \sigma\left(\begin{bmatrix} W_{111}X_{i1} + W_{121}X_{i2} + W_{131}X_{i3} + W_{141}X_{i4} + b_{11} \\ W_{112}X_{i1} + W_{122}X_{i2} + W_{132}X_{i3} + W_{142}X_{i4} + b_{12} \\ W_{113}X_{i1} + W_{123}X_{i2} + W_{133}X_{i3} + W_{143}X_{i4} + b_{13} \end{bmatrix}\right) = \begin{bmatrix} O_{11} \\ O_{12} \\ O_{13} \end{bmatrix} = a^{[1]} [/Tex]

After the completion of the matrix operations, the one-dimensional matrix has been formed as [Tex] \begin{bmatrix} O_{11} & O_{12} & O_{13} \end{bmatrix} [/Tex]which is continued as $a^{[1]}$ known as the output of the first hidden layer.

Inside Layer 2

[Tex]\sigma\left(\left[\begin{array}{cc} W_{211} & W_{212} \\ W_{221} & W_{222} \\ W_{231} & W_{232} \end{array}\right]^T \cdot \left[\begin{array}{c} O_{11} \\ O_{12} \\ O_{13} \end{array}\right] + \left[\begin{array}{c} b_{21} \\ b_{22} \end{array}\right]\right) \\ = \sigma\left(\left[\begin{array}{cc} W_{211} \cdot O_{11} + W_{221} \cdot O_{12} + W_{231} \cdot O_{13} \\ W_{212} \cdot O_{11} + W_{222} \cdot O_{12} + W_{232} \cdot O_{13} \end{array}\right] + \left[\begin{array}{c} b_{21} \\ b_{22} \end{array}\right]\right) \\ = \sigma\left(\left[\begin{array}{c} W_{211} \cdot O_{11} + W_{221} \cdot O_{12} + W_{231} \cdot O_{13} + b_{21} \\ W_{212} \cdot O_{11} + W_{222} \cdot O_{12} + W_{232} \cdot O_{13} + b_{22} \end{array}\right]\right) \\ = \left[\begin{array}{c} O_{21} \\ O_{22} \end{array}\right] \\ = a^{[2}] [/Tex]

The output of the first hidden layer and the weights of the second hidden layer will be computed under the previously stated prediction function which will be matrix manipulated with those biases to give us the output of the second hidden layer i.e. the matrix [Tex]\left[ O_{21} \quad O_{22} \right] [/Tex]. The output will be stated as [Tex]a^{[2]} [/Tex]here:

Inside Output Layer

[Tex]\sigma\left(\left[\begin{array}{c} W_{311} \\ W_{321} \end{array}\right]^T \cdot \left[\begin{array}{c} O_{21} \\ O_{22} \end{array}\right] + \left[ b_{31} \right]\right) \\ = \sigma\left(\left[W_{311} \cdot O_{21} + W_{321} \cdot O_{22}\right] + \left[ b_{31} \right]\right) \\ = \sigma\left(W_{311} \cdot O_{21} + W_{321} \cdot O_{22} + b_{31}\right) \\ = Y^{i} = \left[ O_{31} \right] \\ = a^{[3]} [/Tex]

like in first and second layer , here also matrix manipulation along with the prediction function takes action and present us a prediction as output for that particular guessed trainable parameters in form of [Tex]\left[ O_{31} \right] [/Tex] which is termed as[Tex]a^{[3]} = Y^{i} [/Tex] here.

Now as for the complete equation , we can conclude as follows :

[Tex]\sigma(a[0]*W[1] + b[1]) = a[1] \sigma(a[1]*W[2] + b[2]) = a[2] \sigma(a[2]*W[3] + b[3]) = a[3][/Tex]

which concludes us to :

[Tex]\sigma(\sigma((\sigma(a[0]*W[1] + b[1])*W[2] + b[2])*W[3] + b[3]) = a[3][/Tex]

Steps for Forward Propagation in Neural Network

The steps can be described at once as:

Step 1: Parameters Initialization

  • We will first initialize the weight matrices and the bias vectors. It’s important to note that we shouldn’t initialize all the parameters to zero because doing so will lead the gradients to be equal and on each iteration the output would be the same, and the learning algorithm won’t learn anything.
  • Therefore, it’s important to randomly initialize the parameters to a value between 0 and 1. The learning rate will be recommended as 0.01 to make the activation function active.

Step 2: Activation function

There is no definitive guide for which activation function works best on specific problems, based on specific requirements activation function must be choosen.

Step 3: Feeding forward

Given inputs from the previous layer, each unit computes an affine transformation [Tex]𝑧=𝑊𝑇ð‘Ĩ+𝑏[/Tex] and then applies an activation function [Tex]𝑔(𝑧) [/Tex]such as ReLU element-wise. During this process, we will store all the variables computed and used on each layer to be used in backpropagation.

Implementation of Forward Propagation in Neural Networks

In this section, we are going to implement basic components of neural network and demonstrate how data flows through the network, from input to output, by performing forward propagation. We have discussed the points below:

  1. Importing Modules: It imports the necessary libraries, NumPy and Pandas.
  2. Creating Dataset: It creates a DataFrame df with columns ‘cgpa’, ‘profile_score’, and ‘lpa’.
  3. Initialize Parameters Function (initialize_parameters): This function initializes the weights W and biases b for each layer of the neural network. It returns a dictionary containing the initialized parameters.
  4. Forward Propagation Functions (linear_forward, L_layer_forward): These functions perform the forward pass through the neural network. linear_forward computes the linear transformation [Tex]𝑍=𝑊𝑇⋅ðī_{prev}+𝑏[/Tex], while L_layer_forward iterates through the layers, applying the linear transformation and activation function to compute the output of the network.
  5. Example Execution: It demonstrates an example execution of the forward pass for the first row of the dataset df, using the initialized parameters.
Python3

import numpy as np import pandas as pd # Creating a dataset df = pd.DataFrame([[8, 8, 4], [7, 9, 5], [6, 10, 6], [5, 12, 7]], columns=['cgpa', 'profile_score', 'lpa']) # Initializing parameters def initialize_parameters(layer_dims): np.random.seed(3) parameters = {} L = len(layer_dims) for i in range(1, L): parameters['W' + str(i)] = np.ones((layer_dims[i-1], layer_dims[i])) * 0.1 parameters['b' + str(i)] = np.zeros((layer_dims[i], 1)) return parameters # Forward propagation def linear_forward(A_prev, W, b): Z = np.dot(W.T, A_prev) + b return Z def relu(Z): return np.maximum(0, Z) def L_layer_forward(X, parameters): A = X caches = [] L = len(parameters) // 2 for i in range(1, L): A_prev = A W = parameters['W' + str(i)] b = parameters['b' + str(i)] Z = linear_forward(A_prev, W, b) A = relu(Z) cache = (A_prev, W, b, Z) caches.append(cache) # Output layer W_out = parameters['W' + str(L)] b_out = parameters['b' + str(L)] Z_out = linear_forward(A, W_out, b_out) AL = Z_out return AL, caches # Example execution X = df[['cgpa', 'profile_score']].values[0].reshape(2, 1) parameters = initialize_parameters([2, 2, 1]) y_hat, caches = L_layer_forward(X, parameters) print("Final output:") print(y_hat)

Output:

Final output: [[0.32]]

Neural networks learn complex relationships by introducing non-linearity at each layer, combining different proportions of the output curve to minimize loss. Trainable parameters (weights and biases) are adjusted through backpropagation, a process of continuously assigning new values to them to minimize the deviation between the predicted and actual results over multiple epochs. Forward propagation is the foundational step of backpropagation, where inputs are passed through the network to generate predictions.



Similar Reads

Difference Between Feed-Forward Neural Networks and Recurrent Neural Networks
Pre-requisites: Artificial Neural Networks and its Applications Neural networks are artificial systems that were inspired by biological neural networks. These systems learn to perform tasks by being exposed to various datasets and examples without any task-specific rules. In this article, we will see the difference between Feed-Forward Neural Netwo
2 min read
Deep Neural net with forward and back propagation from scratch - Python
This article aims to implement a deep neural network from scratch. We will implement a deep neural network containing a hidden layer with four units and one output layer. The implementation will go from very scratch and the following steps will be implemented. Algorithm: 1. Visualizing the input data 2. Deciding the shapes of Weight and bias matrix
6 min read
Differences Between Bayesian Networks and Neural Networks
Bayesian networks and neural networks are two distinct types of graphical models used in machine learning and artificial intelligence. While both models are designed to handle complex data and make predictions, they differ significantly in their theoretical foundations, operational mechanisms, and applications. This article will delve into the diff
9 min read
Multilayer Feed-Forward Neural Network in Data Mining
Multilayer Feed-Forward Neural Network(MFFNN) is an interconnected Artificial Neural Network with multiple layers that has neurons with weights associated with them and they compute the result using activation functions. It is one of the types of Neural Networks in which the flow of the network is from input to output units and it does not have any
3 min read
Understanding Multi-Layer Feed Forward Networks
Let's understand how errors are calculated and weights are updated in backpropagation networks(BPNs). Consider the following network in the below figure. The network in the above figure is a simple multi-layer feed-forward network or backpropagation network. It contains three layers, the input layer with two neurons x1 and x2, the hidden layer with
7 min read
Introduction to ANN (Artificial Neural Networks) | Set 3 (Hybrid Systems)
Prerequisites: Genetic algorithms, Artificial Neural Networks, Fuzzy Logic Hybrid systems: A Hybrid system is an intelligent system that is framed by combining at least two intelligent technologies like Fuzzy Logic, Neural networks, Genetic algorithms, reinforcement learning, etc. The combination of different techniques in one computational model m
4 min read
Depth wise Separable Convolutional Neural Networks
Convolution is a very important mathematical operation in artificial neural networks(ANN's). Convolutional neural networks (CNN's) can be used to learn features as well as classify data with the help of image frames. There are many types of CNN's. One class of CNN's are depth wise separable convolutional neural networks. These type of CNN's are wid
4 min read
Recurrent Neural Networks Explanation
Today, different Machine Learning techniques are used to handle different types of data. One of the most difficult types of data to handle and the forecast is sequential data. Sequential data is different from other types of data in the sense that while all the features of a typical dataset can be assumed to be order-independent, this cannot be ass
8 min read
Dropout in Neural Networks
The concept of Neural Networks is inspired by the neurons in the human brain and scientists wanted a machine to replicate the same process. This craved a path to one of the most important topics in Artificial Intelligence. A Neural Network (NN) is based on a collection of connected units or nodes called artificial neurons, which loosely model the n
3 min read
DeepPose: Human Pose Estimation via Deep Neural Networks
DeepPose was proposed by researchers at Google for Pose Estimation in the 2014 Computer Vision and Pattern Recognition conference. They work on formulating the pose Estimation problem as a DNN-based regression problem towards body joints. They present a cascade of DNN-regressors which resulted in high precision pose estimates.. Architecture: Pose V
5 min read
How Neural Networks are used for Classification in R Programming
Neural Networks is a well known word in machine learning and data science. Neural networks are used almost in every machine learning application because of its reliability and mathematical power. In this article let's deal with applications of neural networks in classification problems by using R programming. First briefly look at neural network an
4 min read
Multi Layered Neural Networks in R Programming
A series or set of algorithms that try to recognize the underlying relationship in a data set through a definite process that mimics the operation of the human brain is known as a Neural Network. Hence, the neural networks could refer to the neurons of the human, either artificial or organic in nature. A neural network can easily adapt to the chang
6 min read
Single Layered Neural Networks in R Programming
Neural networks also known as neural nets is a type of algorithm in machine learning and artificial intelligence that works the same as the human brain operates. The artificial neurons in the neural network depict the same behavior of neurons in the human brain. Neural networks are used in risk analysis of business, forecasting the sales, and many
5 min read
Activation functions in Neural Networks | Set2
The article Activation-functions-neural-networks will help to understand the use of activation function along with the explanation of some of its variants like linear, sigmoid, tanh, Relu and softmax. There are some other variants of the activation function like Elu, Selu, Leaky Relu, Softsign and Softplus which are discussed briefly in this articl
3 min read
Training Neural Networks using Pytorch Lightning
Introduction: PyTorch Lightning is a library that provides a high-level interface for PyTorch. Problem with PyTorch is that every time you start a project you have to rewrite those training and testing loop. PyTorch Lightning fixes the problem by not only reducing boilerplate code but also providing added functionality that might come handy while t
7 min read
Auto-associative Neural Networks
Auto associative Neural networks are the types of neural networks whose input and output vectors are identical. These are special kinds of neural networks that are used to simulate and explore the associative process. Association in this architecture comes from the instruction of a set of simple processing elements called units which are connected
3 min read
Training Neural Networks with Validation using PyTorch
Neural Networks are a biologically-inspired programming paradigm that deep learning is built around. Python provides various libraries using which you can create and train neural networks over given data. PyTorch is one such library that provides us with various utilities to build and train neural networks easily. When it comes to Neural Networks i
8 min read
Numpy Gradient - Descent Optimizer of Neural Networks
NumPy Gradient Descent Optimizer is a commonly used optimization algorithm in neural network training that is based on the gradient descent algorithm. It is used to minimize the cost function of a neural network model, by adjusting the model's weights and biases through a series of iterations. The basic steps of NumPy Gradient Descent Optimizer are
6 min read
GrowNet: Gradient Boosting Neural Networks
GrowNet was proposed in 2020 by students from Purdue, UCLA, and Virginia Tech in collaboration with engineers from Amazon and LinkedIn California. They proposed a new gradient boosting algorithm where they used a shallow neural network as the weak learners, a general loss function for training the gradient boosting models under classification, regr
6 min read
Types of Recurrent Neural Networks (RNN) in Tensorflow
Recurrent neural network (RNN) is more like Artificial Neural Networks (ANN) that are mostly employed in speech recognition and natural language processing (NLP). Deep learning and the construction of models that mimic the activity of neurons in the human brain uses RNN. Text, genomes, handwriting, the spoken word, and numerical time series data fr
2 min read
Weight Initialization Techniques for Deep Neural Networks
While building and training neural networks, it is crucial to initialize the weights appropriately to ensure a model with high accuracy. If the weights are not correctly initialized, it may give rise to the Vanishing Gradient problem or the Exploding Gradient problem. Hence, selecting an appropriate weight initialization strategy is critical when t
5 min read
Implementing Neural Networks Using TensorFlow
Deep learning has been on the rise in this decade and its applications are so wide-ranging and amazing that it's almost hard to believe that it's been only a few years in its advancements. And at the core of deep learning lies a basic "unit" that governs its architecture, yes, It's neural networks. A neural network architecture comprises a number o
8 min read
How Neural Networks Can Be Used For Data Mining?
As all of us are aware that how technology is growing day-by-day and a Large amount of data is produced every second, analyzing data is going to be very important because it helps us in fraud detection, identifying spam e-mail, etc. So Data Mining comes into existence to help us find hidden patterns, discover knowledge from large datasets. In this
6 min read
Sentiment Analysis with an Recurrent Neural Networks (RNN)
Recurrent Neural Networks (RNN) are to the rescue when the sequence of information is needed to be captured (another use case may include Time Series, next word prediction, etc.). Due to its internal memory factor, it remembers past sequences along with current input which makes it capable to capture context rather than just individual words. For b
7 min read
Training of Recurrent Neural Networks (RNN) in TensorFlow
In this article, we shall train an RNN i.e., Recurrent Neural Networks(RNN) in TensorFlow. TensorFlow makes it effortless to build a Recurrent Neural Network without performing its mathematics calculations. Compare to other Deep Learning frameworks, TensorFlow is the easiest way to build and train a Recurrent Neural Network. Recurrent Neural Networ
8 min read
Recurrent Neural Networks in R
Recurrent Neural Networks (RNNs) are a type of neural network that is able to process sequential data, such as time series, text, or audio. This makes them well-suited for tasks such as language translation, speech recognition, and time series prediction. In this article, we will explore how to implement and train an RNN in the R programming langua
5 min read
Time Series Forecasting using Recurrent Neural Networks (RNN) in TensorFlow
Time Series Data: Each data point in a time series is linked to a timestamp, which shows the exact time when the data was observed or recorded. Many fields, including finance, economics, weather forecasting, and machine learning, frequently employ this kind of data. The fact that time series data frequently display patterns or trends across time, s
14 min read
Neural Networks Using the R nnet Package
A neural network is a computational model inspired by the structure and function of the human brain. It consists of interconnected nodes, called neurons, organized into layers. The network receives input data, processes it through multiple layers of neurons, and produces an output or prediction. The basic building block of a neural network is the n
15+ min read
What are Graph Neural Networks?
Graph Neural Network is a modern machine learning technique that is sued to perform various operations on graphical data. There are traditional neural networks already available for analyzing, and performing operations but they are limited to textual data only. When we need to tackle the graphical data, we use the Graph Neural Network. Graphical ne
10 min read
Train and Test Neural Networks Using R
Training and testing neural networks using R is a fundamental aspect of machine learning and deep learning. In this comprehensive guide, we will explore the theory and practical steps involved in building, training, and evaluating neural networks in R Programming Language. Neural networks are a class of machine learning models inspired by the human
11 min read
three90RightbarBannerImg