The Wayback Machine - https://web.archive.org/web/20240927185501/https://www.geeksforgeeks.org/ml-momentum-based-gradient-optimizer-introduction/
Open In App

ML | Momentum-based Gradient Optimizer introduction

Last Updated : 01 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Gradient Descent is an optimization technique used in Machine Learning frameworks to train different models. The training process consists of an objective function (or the error function), which determines the error a Machine Learning model has on a given dataset. 
While training, the parameters of this algorithm are initialized to random values. As the algorithm iterates, the parameters are updated such that we reach closer and closer to the optimal value of the function.

However, Adaptive Optimization Algorithms are gaining popularity due to their ability to converge swiftly. All these algorithms, in contrast to the conventional Gradient Descent, use statistics from the previous iterations to robustify the process of convergence.

Momentum-based Gradient Optimizer is a technique used in optimization algorithms, such as Gradient Descent, to accelerate the convergence of the algorithm and overcome local minima. In the Momentum-based Gradient Optimizer, a fraction of the previous update is added to the current update, which creates a momentum effect that helps the algorithm to move faster towards the minimum.

The momentum term can be viewed as a moving average of the gradients. The larger the momentum term, the smoother the moving average, and the more resistant it is to changes in the gradients. The momentum term is typically set to a value between 0 and 1, with a higher value resulting in a more stable optimization process.

The update rule for the Momentum-based Gradient Optimizer can be expressed as follows:

makefile
v = beta * v - learning_rate * gradient
parameters = parameters + v

// Where v is the velocity vector, beta is the momentum term, 
// learning_rate is the step size, 
// gradient is the gradient of the cost function with respect to the parameters, 
// and parameters are the parameters of the model.

The Momentum-based Gradient Optimizer has several advantages over the basic Gradient Descent algorithm, including faster convergence, improved stability, and the ability to overcome local minima. It is widely used in deep learning applications and is an important optimization technique for training deep neural networks.

Momentum-based Optimization:

An Adaptive Optimization Algorithm uses exponentially weighted averages of gradients over previous iterations to stabilize the convergence, resulting in quicker optimization. For example, in most real-world applications of Deep Neural Networks, the training is carried out on noisy data. It is, therefore, necessary to reduce the effect of noise when the data are fed in batches during Optimization. This problem can be tackled using Exponentially Weighted Averages (or Exponentially Weighted Moving Averages).

Implementing Exponentially Weighted Averages: 

In order to approximate the trends in a noisy dataset of size N: 
\theta_{0}, \theta_{1}, \theta_{2}, ..., \theta_{N}    , we maintain a set of parameters v_{0}, v_{1}, v_{2}, v_{3}, ..., v_{N}    . As we iterate through all the values in the dataset, we calculate the parameters below: 

On iteration t:
    Get next \theta_{t}[Tex]v_{\theta} = \beta v_{\theta} + (1 - \beta) \theta_{t}[/Tex]

This algorithm averages the value of v_{\theta}    over its values from previous \frac{1}{1 - \beta}    iterations. This averaging ensures that only the trend is retained and the noise is averaged out. This method is used as a strategy in momentum-based gradient descent to make it robust against noise in data samples, resulting in faster training.

As an example, if you were to optimize a function f(x)    on the parameter x, the following pseudo-code illustrates the algorithm:

On iteration t:
    On the current batch, compute \frac{\partial f(x)}{\partial x}[Tex]v := v + (1 - \beta) \frac{\partial f(x)}{\partial x}[/Tex]x := x - \alpha v

The HyperParameters for this Optimization Algorithm are \alpha    , called the Learning Rate and, \beta    , similar to acceleration in mechanics.

Implementation:

Following is an implementation of Momentum-based Gradient Descent on a function f(x) = x ^ 2 - 4 x + 4    :  

Python3

import math
 
# HyperParameters of the optimization algorithm
alpha = 0.01
beta = 0.9
 
# Objective function
 
 
def obj_func(x):
    return x * x - 4 * x + 4
 
# Gradient of the objective function
 
 
def grad(x):
    return 2 * x - 4
 
 
# Parameter of the objective function
x = 0
 
# Number of iterations
iterations = 0
 
v = 0
 
while (1):
    iterations += 1
    v = beta * v + (1 - beta) * grad(x)
 
    x_prev = x
 
    x = x - alpha * v
 
    print("Value of objective function on iteration", iterations, "is", x)
 
    if x_prev == x:
        print("Done optimizing the objective function. ")
        break

                    

Output
...999999938
Value of objective function on iteration 1261 is 1.999999999999994
Value of objective function on iteration 1262 is 1.9999999999999942
Value of objective function on iteration 1263 is 1.9999999999999944
Value of objective function on iteration 1264 is 1.9999999999999947
Value of objective function on iteration 1265 is 1.999999999999995
Value of objective function on iteration 1266 is 1.9999999999999951
Value of objective function on iteration 1267 is 1.9999999999999953
Value of objective function on iteration 1268 is 1.9999999999999956
Value of objective function on iteration 1269 is 1.9999999999999958
Value of objective function on iteration 1270 is 1.999999999999996
Value of objective function on iteration 1271 is 1.9999999999999962
Value of objective function on iteration 1272 is 1.9999999999999964
Value of objective function on iteration 1273 is 1.9999999999999967
Value of objective function on iteration 1274 is 1.9999999999999967
Done optimizing the objective function. 


Previous Article
Next Article

Similar Reads

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
Difference between Batch Gradient Descent and Stochastic Gradient Descent
In order to train a Linear Regression model, we have to learn some model parameters such as feature weights and bias terms. An approach to do the same is Gradient Descent which is an iterative optimization algorithm capable of tweaking the model parameters by minimizing the cost function over the train data. It is a complete algorithm i.e it is gua
5 min read
What Is the Difference Between Gradient Descent and Gradient Boosting?
Answer: Gradient descent is an optimization algorithm used for minimizing a loss function, while gradient boosting is a machine learning technique that combines weak learners (typically decision trees) iteratively to improve predictive performance.Gradient Descent vs Gradient Boosting: Comparison AspectGradient DescentGradient BoostingObjectiveMini
1 min read
Difference between Gradient Descent and Gradient Ascent?
Gradient Descent and Gradient Ascent are optimization techniques commonly used in machine learning and other fields, but they serve opposite purposes. Here’s a breakdown of the key differences: 1. Objective:Gradient Descent: The goal of gradient descent is to minimize a function. It iteratively adjusts the parameters of the model in the direction t
3 min read
Intuition behind Adagrad Optimizer
Adagrad stands for Adaptive Gradient Optimizer. There were optimizers like Gradient Descent, Stochastic Gradient Descent, mini-batch SGD, all were used to reduce the loss function with respect to the weights. The weight updating formula is as follows: [Tex](\mathrm{w})_{\mathrm{new}}=(\mathrm{w})_{\mathrm{old}}-\eta \frac{\partial \mathrm{L}}{\math
3 min read
Adam Optimizer in Tensorflow
Optimizers are algorithms or methods that are used to change or tune the attributes of a neural network such as layer weights, learning rate, etc. in order to reduce the loss and in turn improve the model. In this article, I am going to talk about Adam optimizer and its implementation in Tensorflow. Before starting the discussion let's talk a littl
5 min read
What is Adam Optimizer?
Prerequisites :  Optimization techniques in Gradient Descent Adam Optimizer  Adaptive Moment Estimation is an algorithm for optimization technique for gradient descent. The method is really efficient when working with large problem involving a lot of data or parameters. It requires less memory and is efficient. Intuitively, it is a combination of t
4 min read
RMSProp Optimizer in Deep Learning
RMSProp (Root Mean Square Propagation) is an adaptive learning rate optimization algorithm designed to improve the performance and speed of training deep learning models. This article aims to explain the working of RMSProp, its advantages and disadvantages, and demonstrate its application in deep learning. Table of Content Understanding RMSProp in
11 min read
PyTorch: Connection Between loss.backward() and optimizer.step()
In deep learning with PyTorch, understanding the connection between loss.backward() and optimizer.step() is crucial for effectively training neural networks. These two functions play pivotal roles in the backpropagation and optimization processes, respectively. This article delves into their functionalities, how they interact, and why both are indi
4 min read
LightGBM Gradient-Based Strategy
LightGBM is a well-known high-performing model that uses a gradient-based strategy in its internal training process. Gradient-based strategy effectively enhances a model to make it highly optimized, accurate in prediction, and memory efficient which unlocks an easy way to handle complex and large real-world datasets used in various machine learning
9 min read
What is Momentum in Neural Network?
Answer: Momentum in neural networks is a parameter optimization technique that accelerates gradient descent by adding a fraction of the previous update to the current update.In neural networks, momentum is a technique used to accelerate the optimization process during training by taking into account the previous updates made to the model parameters
3 min read
Difference Between RMSProp and Momentum?
Answer: RMSProp adjusts learning rates based on recent gradients' magnitude, while momentum accelerates convergence by accumulating past gradients' direction and velocity.RMSProp and Momentum are both optimization algorithms used to speed up the convergence of gradient descent in training neural networks, but they work in different ways to achieve
2 min read
What is the difference between word-based and char-based text generation RNNs?
Answer: Word-based RNNs generate text based on words as units, while char-based RNNs use characters as units for text generation.Word-based RNNs emphasizing semantic meaning and higher-level structures, while char-based RNNs excel in capturing finer character-level patterns. AspectWord-based RNNsChar-based RNNsUnit of ProcessingOperates on words as
2 min read
Optimization techniques for Gradient Descent
Gradient Descent is a widely used optimization algorithm for machine learning models. However, there are several optimization techniques that can be used to improve the performance of Gradient Descent. Here are some of the most popular optimization techniques for Gradient Descent: Learning Rate Scheduling: The learning rate determines the step size
4 min read
ML | Mini-Batch Gradient Descent with Python
In machine learning, gradient descent is an optimization technique used for computing the model parameters (coefficients and bias) for algorithms like linear regression, logistic regression, neural networks, etc. In this technique, we repeatedly iterate through the training set and update the model parameters in accordance with the gradient of the
5 min read
Multivariate Optimization - Gradient and Hessian
In a multivariate optimization problem, there are multiple variables that act as decision variables in the optimization problem. z = f(x1, x2, x3.....xn) So, when you look at these types of problems a general function z could be some non-linear function of decision variables x1, x2, x3 to xn. So, there are n variables that one could manipulate or c
3 min read
Difference between Gradient descent and Normal equation
In regression models, our objective is to discover a model that can make predictions that closely resemble the actual target values. Basically, we try to find the parameters of the model which support our objective of the best model. The general behind finding this parameter is that we calculate the error between our actual value and predicted valu
4 min read
Gradient Boosting in ML
Gradient Boosting is a popular boosting algorithm in machine learning used for classification and regression tasks. Boosting is one kind of ensemble Learning method which trains the model sequentially and each new model tries to correct the previous model. It combines several weak learners into strong learners. There is two most popular boosting al
6 min read
Vectorization Of Gradient Descent
In Machine Learning, Regression problems can be solved in the following ways: 1. Using Optimization Algorithms - Gradient Descent Batch Gradient Descent.Stochastic Gradient Descent.Mini-Batch Gradient DescentOther Advanced Optimization Algorithms like ( Conjugate Descent ... ) 2. Using the Normal Equation : Using the concept of Linear Algebra. Let'
5 min read
How to implement a gradient descent in Python to find a local minimum ?
Gradient Descent is an iterative algorithm that is used to minimize a function by finding the optimal parameters. Gradient Descent can be applied to any dimension function i.e. 1-D, 2-D, 3-D. In this article, we will be working on finding global minima for parabolic function (2-D) and will be implementing gradient descent in python to find the opti
8 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
How to Differentiate a Gradient in PyTorch?
PyTorch is an open-source machine-learning framework based on the Torch library. It is built by the Facebook AI team. It is used for Computer vision and Natural Language Processing applications. PyTorch uses tensors to use the power of GPU. Differentiation is part of Calculus. So, In this article, we will know to calculate the derivative value of a
8 min read
Gradient Descent With RMSProp from Scratch
Gradient descent is an optimization algorithm used to find the set of parameters (coefficients) of a function that minimizes a cost function. This method iteratively adjusts the coefficients of the function until the cost reaches the local, or global, minimum. Gradient descent works by calculating the partial derivatives of the cost function with r
6 min read
How to Implement Adam Gradient Descent from Scratch using Python?
Grade descent is an extensively used optimization algorithm in machine literacy and deep literacy. It's used to minimize the cost or loss function of a model by iteratively confirming the model's parameters grounded on the slants of the cost function with respect to those parameters. One variant of gradient descent that has gained popularity is the
14 min read
ML | XGBoost (eXtreme Gradient Boosting)
XGBoost, short for eXtreme Gradient Boosting, is a powerful machine learning algorithm known for its efficiency, speed, and accuracy. It belongs to the family of boosting algorithms, which are ensemble learning techniques that combine the predictions of multiple weak learners. In this article, we will explore XGBoost step by step, building on exist
12 min read
Understanding Gradient Clipping
Gradient Clipping is the process that helps maintain numerical stability by preventing the gradients from growing too large. When training a neural network, the loss gradients are computed through backpropagation. However, if these gradients become too large, the updates to the model weights can also become excessively large, leading to numerical i
12 min read
Does Gradient Descent Always Converge to an Optimum?
Answer: Gradient descent doesn't always converge to an optimum due to saddle points, plateaus, or poor initialization.Gradient descent, while a widely used optimization algorithm, doesn't guarantee convergence to an optimum in all cases. Several factors can impede convergence: Saddle Points: In high-dimensional spaces, gradient descent may get stuc
2 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 Tune Hyperparameters in Gradient Boosting Algorithm
Gradient boosting algorithms (GBMs) are ensemble learning methods that excel in various machine learning tasks, from regression to classification. They work by iteratively adding decision trees that correct the mistakes of their predecessors. Each tree focuses on the errors left by the previous ones, gradually building a stronger collective predict
10 min read
Support Vector Machine vs Extreme Gradient Boosting
Support Vector Machine (SVM) and Extreme Gradient Boosting (XGBoost) are both powerful machine learning algorithms widely used for classification and regression tasks. They belong to different families of algorithms and have distinct characteristics in terms of their approach to learning, model type, and performance. In this article, we discuss abo
4 min read