The Wayback Machine - https://web.archive.org/web/20240927181827/https://www.geeksforgeeks.org/ml-mini-batch-gradient-descent-with-python/
Open In App

ML | Mini-Batch Gradient Descent with Python

Last Updated : 02 Aug, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 error with respect to the training set. Depending on the number of training examples considered in updating the model parameters, we have 3-types of gradient descents:

  1. Batch Gradient Descent: Parameters are updated after computing the gradient of the error with respect to the entire training set
  2. Stochastic Gradient Descent: Parameters are updated after computing the gradient of the error with respect to a single training example
  3. Mini-Batch Gradient Descent: Parameters are updated after computing the gradient of  the error with respect to a subset of the training set
Batch Gradient Descent Stochastic Gradient Descent Mini-Batch Gradient Descent
Since the entire training data is considered before taking a step in the direction of gradient, therefore it takes a lot of time for making a single update. Since only a single training example is considered before taking a step in the direction of gradient, we are forced to loop over the training set and thus cannot exploit the speed associated with vectorizing the code. Since a subset of training examples is considered, it can make quick updates in the model parameters and can also exploit the speed associated with vectorizing the code.
It makes smooth updates in the model parameters It makes very noisy updates in the parameters Depending upon the batch size, the updates can be made less noisy – greater the batch size less noisy is the update

Thus, mini-batch gradient descent makes a compromise between the speedy convergence and the noise associated with gradient update which makes it a more flexible and robust algorithm.

Convergence in BGD, SGD & MBGD

 Mini-Batch Gradient Descent: Algorithm-

Let theta = model parameters and max_iters = number of epochs. for itr = 1, 2, 3, …, max_iters:       for mini_batch (X_mini, y_mini):

  • Forward Pass on the batch X_mini:
    • Make predictions on the mini-batch
    • Compute error in predictions (J(theta)) with the current values of the parameters
  • Backward Pass:
    • Compute gradient(theta) = partial derivative of J(theta) w.r.t. theta
  • Update parameters:
    • theta = theta – learning_rate*gradient(theta)

Below is the Python Implementation: 

Step #1: First step is to import dependencies, generate data for linear regression, and visualize the generated data. We have generated 8000 data examples, each having 2 attributes/features. These data examples are further divided into training sets (X_train, y_train) and testing set (X_test, y_test) having 7200 and 800 examples respectively. 

Python3




# importing dependencies
import numpy as np
import matplotlib.pyplot as plt
 
# creating data
mean = np.array([5.0, 6.0])
cov = np.array([[1.0, 0.95], [0.95, 1.2]])
data = np.random.multivariate_normal(mean, cov, 8000)
 
# visualising data
plt.scatter(data[:500, 0], data[:500, 1], marker='.')
plt.show()
 
# train-test-split
data = np.hstack((np.ones((data.shape[0], 1)), data))
 
split_factor = 0.90
split = int(split_factor * data.shape[0])
 
X_train = data[:split, :-1]
y_train = data[:split, -1].reshape((-1, 1))
X_test = data[split:, :-1]
y_test = data[split:, -1].reshape((-1, 1))
 
print(& quot
       Number of examples in training set= % d & quot
       % (X_train.shape[0]))
print(& quot
       Number of examples in testing set= % d & quot
       % (X_test.shape[0]))


Output:

  

Number of examples in training set = 7200 Number of examples in testing set = 800   

Step #2: Next, we write the code for implementing linear regression using mini-batch gradient descent. gradientDescent() is the main driver function and other functions are helper functions used for making predictions – hypothesis(), computing gradients – gradient(), computing error – cost() and creating mini-batches – create_mini_batches(). The driver function initializes the parameters, computes the best set of parameters for the model, and returns these parameters along with a list containing a history of errors as the parameters get updated.

Example 

Python3




# linear regression using "mini-batch" gradient descent
# function to compute hypothesis / predictions
 
 
def hypothesis(X, theta):
    return np.dot(X, theta)
 
# function to compute gradient of error function w.r.t. theta
 
 
def gradient(X, y, theta):
    h = hypothesis(X, theta)
    grad = np.dot(X.transpose(), (h - y))
    return grad
 
# function to compute the error for current values of theta
 
 
def cost(X, y, theta):
    h = hypothesis(X, theta)
    J = np.dot((h - y).transpose(), (h - y))
    J /= 2
    return J[0]
 
# function to create a list containing mini-batches
 
 
def create_mini_batches(X, y, batch_size):
    mini_batches = []
    data = np.hstack((X, y))
    np.random.shuffle(data)
    n_minibatches = data.shape[0] // batch_size
    i = 0
 
    for i in range(n_minibatches + 1):
        mini_batch = data[i * batch_size:(i + 1)*batch_size, :]
        X_mini = mini_batch[:, :-1]
        Y_mini = mini_batch[:, -1].reshape((-1, 1))
        mini_batches.append((X_mini, Y_mini))
    if data.shape[0] % batch_size != 0:
        mini_batch = data[i * batch_size:data.shape[0]]
        X_mini = mini_batch[:, :-1]
        Y_mini = mini_batch[:, -1].reshape((-1, 1))
        mini_batches.append((X_mini, Y_mini))
    return mini_batches
 
# function to perform mini-batch gradient descent
 
 
def gradientDescent(X, y, learning_rate=0.001, batch_size=32):
    theta = np.zeros((X.shape[1], 1))
    error_list = []
    max_iters = 3
    for itr in range(max_iters):
        mini_batches = create_mini_batches(X, y, batch_size)
        for mini_batch in mini_batches:
            X_mini, y_mini = mini_batch
            theta = theta - learning_rate * gradient(X_mini, y_mini, theta)
            error_list.append(cost(X_mini, y_mini, theta))
 
    return theta, error_list


Calling the gradientDescent() function to compute the model parameters (theta) and visualize the change in the error function. 

Python3




theta, error_list = gradientDescent(X_train, y_train)
print("Bias = ", theta[0])
print("Coefficients = ", theta[1:])
 
# visualising gradient descent
plt.plot(error_list)
plt.xlabel("Number of iterations")
plt.ylabel("Cost")
plt.show()


Output: Bias = [0.81830471] Coefficients = [[1.04586595]]

    

Step #3: Finally, we make predictions on the testing set and compute the mean absolute error in predictions. 

Python3




# predicting output for X_test
y_pred = hypothesis(X_test, theta)
plt.scatter(X_test[:, 1], y_test[:, ], marker='.')
plt.plot(X_test[:, 1], y_pred, color='orange')
plt.show()
 
# calculating error in predictions
error = np.sum(np.abs(y_test - y_pred) / y_test.shape[0])
print(& quot
       Mean absolute error = & quot
       , error)


Output:

  

Mean absolute error = 0.4366644295854125 

The orange line represents the final hypothesis function: theta[0] + theta[1]*X_test[:, 1] + theta[2]*X_test[:, 2] = 0



Previous Article
Next Article

Similar Reads

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
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
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
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
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
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
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
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
ML | Stochastic Gradient Descent (SGD)
Gradient Descent is an iterative optimization process that searches for an objective function's optimum value (Minimum/Maximum). It is one of the most used methods for changing a model's parameters in order to reduce a cost function in machine learning projects.   The primary goal of gradient descent is to identify the model parameters that provide
10 min read
Stochastic Gradient Descent Regressor using Scikit-learn
Stochastic Gradient Descent (SGD) is a popular optimization technique in the field of machine learning. It is particularly well-suited for handling large datasets and online learning scenarios where data arrives sequentially. In this article, we will discuss how a stochastic gradient descent regressor is implemented using Scikit-Learn. What is a st
3 min read
Stochastic Gradient Descent In R
Gradient Descent is an iterative optimization process that searches for an objective function’s optimum value (Minimum/Maximum). It is one of the most used methods for changing a model’s parameters to reduce a cost function in machine learning projects. In this article, we will learn the concept of SGD and its implementation in the R Programming La
10 min read
Applications of Derivatives in Machine Learning: From Gradient Descent to Probabilistic Models
Derivatives are fundamental concepts in calculus that measure how a function changes as its input changes. In machine learning, derivatives play a crucial role in various aspects, optimization algorithms, training models, and improving the performance of various machine learning techniques. This article explores the applications of derivatives in m
7 min read
Different Variants of Gradient Descent
Gradient descent is a fundamental optimization algorithm in machine learning, used to minimize functions by iteratively moving towards the minimum. It's crucial for training models by fine-tuning parameters to reduce prediction errors. The article aims to explore the fundamentals of different variants of Gradient Descent along with their advantages
11 min read
Gradient Descent in Linear Regression
We know that in any machine learning project our main aim relies on how good our project accuracy is or how much our model prediction differs from the actual data point. Based on the difference between model prediction and actual data points we try to find the parameters of the model which give better accuracy on our dataset\, In order to find thes
9 min read
Gradient Descent Algorithm in Machine Learning
Think about how a machine learns from the data in machine learning and deep learning during training.  This involves a large amount of data. Through the lens of this article, we will delve into the intricacies of minimizing the cost function, a pivotal task in training models. Table of Content Gradient Descent in Machine LearningGradient Descent Py
15+ min read
ML | Mini Batch K-means clustering algorithm
Prerequisite: Optimal value of K in K-Means Clustering K-means is one of the most popular clustering algorithms, mainly because of its good time performance. With the increasing size of the datasets being analyzed, the computation time of K-means increases because of its constraint of needing the whole dataset in main memory. For this reason, sever
6 min read
Introduction to AWS Batch
Amazon Web Services is a subsidiary of Amazon.com that provides on-demand cloud computing platforms to individuals, companies, and governments, on a paid subscription basis. What is Cloud Computing? Cloud computing is the on-demand delivery of compute power, database storage, applications, and other IT resources through a cloud services platform vi
4 min read
Apply torch.inverse() Function of PyTorch to Every Sample in the Batch
PyTorch is a deep learning framework that provides a variety of functions to perform different operations on tensors. One such function is torch.inverse(), which can be used to compute the inverse of a square matrix. Sometimes we may have a batch of matrices, where each matrix represents some data that we want to process using deep learning. In suc
3 min read
Batch Processing Operating System
In the beginning, computers were very large types of machinery that ran from a console table. In all-purpose, card readers or tape drivers were used for input, and punch cards, tape drives, and line printers were used for output. Operators had no direct interface with the system, and job implementation was done in a batch system. These systems are
6 min read
How to choose Batch Size and Number of Epochs When Fitting a Model?
When developing machine learning models, two of the most critical hyperparameters to fine-tune are batch size and number of epochs. These parameters significantly influence the training process and ultimately the performance of your model. But determining the right values for batch size and number of epochs can be complex and often requires a balan
5 min read
ML | Momentum-based Gradient Optimizer introduction
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
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
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
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
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
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
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
Gradient Boosting vs Random Forest
Gradient Boosting Trees (GBT) and Random Forests are both popular ensemble learning techniques used in machine learning for classification and regression tasks. While they share some similarities, they have distinct differences in terms of how they build and combine multiple decision trees. The article aims to discuss the key differences between Gr
7 min read
Practice Tags :