Mini-Batch Gradient Descent in Deep Learning Last Updated : 23 Jul, 2025 Comments Improve Suggest changes Like Article Like Report Mini-batch gradient descent is a variant of the traditional gradient descent algorithm used to optimize the parameters i.e weights and biases of a neural network. It divides the training data into small subsets called mini-batches allowing the model to update its parameters more frequently compared to using the entire dataset at once.The update rule for Mini-Batch Gradient Descent is:\theta := \theta - \frac{\alpha}{m} \sum_{i=1}^{m} \nabla_{\theta} \mathcal{L}(\theta; x^{(i)}, y^{(i)})Where:x^{(i)}, y^{(i)} are the input features and labels of the i-th data point in the mini-batch.\nabla_{\theta} \mathcal{L}(\theta; x^{(i)}, y^{(i)}) is the gradient of the loss function with respect to \theta for the i-th data point.Instead of updating weights after calculating the error for each data point (in stochastic gradient descent) or after the entire dataset (in batch gradient descent), mini-batch gradient descent updates the model’s parameters after processing a mini-batch of data. This provides a balance between computational efficiency and convergence stability.Why to use Mini-Batch Gradient Descent?The primary reason for using mini-batches is to improve both the computational efficiency and the convergence rate of the training process. By processing smaller subsets of data at a time we can update the weights more frequently than batch gradient descent while avoiding the noisiness of stochastic gradient descent.It can be summarized as a method that combines the benefits of both batch and stochastic gradient descent:Batch gradient descent uses the entire dataset for each iteration, which can be computationally expensive.Stochastic gradient descent updates the model after each training sample but this can lead to noisy updates and fluctuations in the training process.Mini-batch gradient descent offers a middle ground making it more efficient and often leading to faster convergence.How Mini-Batch Gradient Descent WorksSplitting the Data: The training dataset is divided into smaller mini-batches. Each mini-batch contains a subset of data points. For example if the dataset has 10,000 examples we might split it into 100 mini-batches each containing 100 data points.Computing the Gradient: For each mini-batch the gradient of the loss function is computed and used to update the model’s parameters. The loss is averaged over the mini-batch which helps in reducing the noise compared to the SGD approach.Updating the Parameters: Once the gradient is computed for a mini-batch the model’s parameters are updated using the learning rate and the gradient. This step is repeated for each mini-batch and the process continues until all mini-batches have been processed.Epochs: An epoch refers to one complete pass through the entire dataset. After each epoch the mini-batches are typically reshuffled to ensure that the model does not overfit to the specific order of the data.How to Choose the Mini-Batch SizeChoosing the right mini-batch size is crucial for the effectiveness of the model. Here are a few considerations:Small Batch Size: Usually between 32 and 128. This may result in more frequent updates but it can also introduce noise into the optimization process. It is suitable for smaller models or when computational resources are limited.Large Batch Size: Larger than 512. This results in more stable updates but can increase memory consumption. It is ideal when training on powerful hardware like GPUs or TPUs.General Guideline: Start with a batch size of 64 or 128 and adjust based on the training behavior. If training is too slow or unstable then experiment with smaller or larger batch sizes.Optimizing Mini-Batch Gradient DescentLearning Rate Schedulers: Dynamic adjustment of the learning rate during training can improve the performance of mini-batch gradient descent by helping the model converge more smoothly.Momentum: Using momentum with mini-batch gradient descent can accelerate convergence by helping the model overcome oscillations and reach the global minimum faster.Adam Optimizer: Adam optimizer combines the benefits of both momentum and RMSProp optimizers and is widely used with mini-batch gradient descent for faster and more reliable convergence.1. Implementing Mini Batch Gradient Descent in TensorFlow In the following code mini-batch gradient descent is used by setting batch_size=32 in model.fit() meaning the model processes 32 data points at a time before updating the weights. We are using tensorflow here.A custom callback BatchLossHistory is created to track the loss after each mini-batch. The on_train_batch_end method captures the loss after each batchWhile on_epoch_begin resets the loss list at the start of each epoch. The recorded losses are then plotted to visualize the loss per mini-batch during training. Python import tensorflow as tf from tensorflow.keras import layers, models import numpy as np import matplotlib.pyplot as plt X_train = np.random.rand(1000, 20) y_train = np.random.randint(0, 2, size=(1000, 1)) model = models.Sequential([ layers.Dense(64, activation='relu', input_shape=(20,)), layers.Dense(1, activation='sigmoid') ]) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) class BatchLossHistory(tf.keras.callbacks.Callback): def on_train_batch_end(self, batch, logs=None): self.losses.append(logs['loss']) def on_epoch_begin(self, epoch, logs=None): self.losses = [] batch_loss_history = BatchLossHistory() history = model.fit(X_train, y_train, epochs=10, batch_size=32, callbacks=[batch_loss_history], verbose=1) plt.plot(batch_loss_history.losses) plt.xlabel('Batch') plt.ylabel('Loss') plt.title('Mini-Batch Loss per Batch') plt.show() Output: training the modelloss-per-batch-tensorflow2. Implementing Mini Batch Gradient Descent in PyTorch In this PyTorch code mini-batch gradient descent is used with a batch size of 32 set via the DataLoader (batch_size=32). This means that the model processes 32 samples at a time before updating the weights.The training loop iterates over mini-batches where the loss for each batch is calculated using the BCELoss function. The adam optimizer performs the backward pass and updates the weights. Mini-batch loss for each batch is recorded in the batch_losses list. After training these losses are plotted to visualize the loss per mini-batch during the 10 epochs. Python import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader, TensorDataset import matplotlib.pyplot as plt X_train = torch.randn(1000, 20) y_train = torch.randint(0, 2, (1000, 1)).float() class SimpleNN(nn.Module): def __init__(self): super(SimpleNN, self).__init__() self.fc1 = nn.Linear(20, 64) self.fc2 = nn.Linear(64, 1) def forward(self, x): x = torch.relu(self.fc1(x)) x = torch.sigmoid(self.fc2(x)) return x model = SimpleNN() criterion = nn.BCELoss() optimizer = optim.Adam(model.parameters(), lr=0.001) dataset = TensorDataset(X_train, y_train) train_loader = DataLoader(dataset, batch_size=32, shuffle=True) batch_losses = [] epochs = 10 for epoch in range(epochs): for batch_X, batch_y in train_loader: outputs = model(batch_X) loss = criterion(outputs, batch_y) optimizer.zero_grad() loss.backward() optimizer.step() batch_losses.append(loss.item()) print(f"Epoch [{epoch+1}/{epochs}], Loss: {loss.item():.4f}") plt.plot(batch_losses) plt.xlabel('Batch') plt.ylabel('Loss') plt.title('Mini-Batch Loss per Batch') plt.show() Output: pytorch-mini-batchAdvantages of Mini-Batch Gradient DescentFaster Convergence: Because the model updates its parameters more frequently i.e after each mini-batch hence converges faster than batch gradient descent which waits until the entire dataset is processed.Reduced Memory Usage: Mini-batches allow training on large datasets without the need to load the entire dataset into memory at once. This makes it feasible to train deep learning models on large-scale data.Smoother Gradient Estimation: Compared to stochastic gradient descent (SGD), mini-batch gradient descent offers a smoother convergence. While SGD updates after each data point resulting in noisy gradients hence mini-batch offers a more balanced and stable gradient update.Parallelization and Speed: It can be parallelized on hardware like GPUs where the computation of gradients for each mini-batch can be executed simultaneously. This results in faster training especially for large neural networks.Disadvantages of Mini-Batch Gradient DescentWhile mini-batch gradient descent is widely used it has a few potential drawbacks:Choice of Batch Size: Selecting the appropriate batch size is crucial. A batch that’s too small may lead to noisy updates, while a batch too large may negate the efficiency benefits.Requires More Epochs: Since it doesn’t use the entire dataset at once it may require more epochs to converge compared to batch gradient descent.Complexity: It introduces complexity in terms of managing multiple mini-batches which can increase the development effort and tuning requirements. Comment More infoAdvertise with us Next Article Introduction to Deep Learning A alka1974 Follow Improve Article Tags : Deep Learning AI-ML-DS AI-ML-DS With Python Similar Reads Deep Learning Tutorial Deep Learning is a subset of Artificial Intelligence (AI) that helps machines to learn from large datasets using multi-layered neural networks. It automatically finds patterns and makes predictions and eliminates the need for manual feature extraction. Deep Learning tutorial covers the basics to adv 5 min read Deep Learning BasicsIntroduction to Deep LearningDeep Learning is transforming the way machines understand, learn and interact with complex data. Deep learning mimics neural networks of the human brain, it enables computers to autonomously uncover patterns and make informed decisions from vast amounts of unstructured data. How Deep Learning Works? 7 min read Artificial intelligence vs Machine Learning vs Deep LearningNowadays many misconceptions are there related to the words machine learning, deep learning, and artificial intelligence (AI), most people think all these things are the same whenever they hear the word AI, they directly relate that word to machine learning or vice versa, well yes, these things are 4 min read Deep Learning Examples: Practical Applications in Real LifeDeep learning is a branch of artificial intelligence (AI) that uses algorithms inspired by how the human brain works. It helps computers learn from large amounts of data and make smart decisions. Deep learning is behind many technologies we use every day like voice assistants and medical tools.This 3 min read Challenges in Deep LearningDeep learning, a branch of artificial intelligence, uses neural networks to analyze and learn from large datasets. It powers advancements in image recognition, natural language processing, and autonomous systems. Despite its impressive capabilities, deep learning is not without its challenges. It in 7 min read Why Deep Learning is ImportantDeep learning has emerged as one of the most transformative technologies of our time, revolutionizing numerous fields from computer vision to natural language processing. Its significance extends far beyond just improving predictive accuracy; it has reshaped entire industries and opened up new possi 5 min read Neural Networks BasicsWhat is a Neural Network?Neural networks are machine learning models that mimic the complex functions of the human brain. These models consist of interconnected nodes or neurons that process data, learn patterns and enable tasks such as pattern recognition and decision-making.In this article, we will explore the fundamental 12 min read Types of Neural NetworksNeural networks are computational models that mimic the way biological neural networks in the human brain process information. They consist of layers of neurons that transform the input data into meaningful outputs through a series of mathematical operations. In this article, we are going to explore 7 min read Layers in Artificial Neural Networks (ANN)In Artificial Neural Networks (ANNs), data flows from the input layer to the output layer through one or more hidden layers. Each layer consists of neurons that receive input, process it, and pass the output to the next layer. The layers work together to extract features, transform data, and make pr 4 min read Activation functions in Neural NetworksWhile building a neural network, one key decision is selecting the Activation Function for both the hidden layer and the output layer. It is a mathematical function applied to the output of a neuron. It introduces non-linearity into the model, allowing the network to learn and represent complex patt 8 min read Feedforward Neural NetworkFeedforward Neural Network (FNN) is a type of artificial neural network in which information flows in a single direction i.e from the input layer through hidden layers to the output layer without loops or feedback. It is mainly used for pattern recognition tasks like image and speech classification. 6 min read Backpropagation in Neural NetworkBack Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and 9 min read Deep Learning ModelsConvolutional Neural Network (CNN) in Machine LearningConvolutional Neural Networks (CNNs) are deep learning models designed to process data with a grid-like topology such as images. They are the foundation for most modern computer vision applications to detect features within visual data.Key Components of a Convolutional Neural NetworkConvolutional La 6 min read Introduction to Recurrent Neural NetworksRecurrent Neural Networks (RNNs) differ from regular neural networks in how they process information. While standard neural networks pass information in one direction i.e from input to output, RNNs feed information back into the network at each step.Lets understand RNN with a example:Imagine reading 10 min read What is LSTM - Long Short Term Memory?Long Short-Term Memory (LSTM) is an enhanced version of the Recurrent Neural Network (RNN) designed by Hochreiter and Schmidhuber. LSTMs can capture long-term dependencies in sequential data making them ideal for tasks like language translation, speech recognition and time series forecasting. Unlike 5 min read Gated Recurrent Unit NetworksIn machine learning Recurrent Neural Networks (RNNs) are essential for tasks involving sequential data such as text, speech and time-series analysis. While traditional RNNs struggle with capturing long-term dependencies due to the vanishing gradient problem architectures like Long Short-Term Memory 6 min read Transformers in Machine LearningTransformer is a neural network architecture used for performing machine learning tasks particularly in natural language processing (NLP) and computer vision. In 2017 Vaswani et al. published a paper " Attention is All You Need" in which the transformers architecture was introduced. The article expl 4 min read Autoencoders in Machine LearningAutoencoders are a special type of neural networks that learn to compress data into a compact form and then reconstruct it to closely match the original input. They consist of an:Encoder that captures important features by reducing dimensionality.Decoder that rebuilds the data from this compressed r 8 min read Generative Adversarial Network (GAN)Generative Adversarial Networks (GAN) help machines to create new, realistic data by learning from existing examples. It is introduced by Ian Goodfellow and his team in 2014 and they have transformed how computers generate images, videos, music and more. Unlike traditional models that only recognize 12 min read Deep Learning FrameworksTensorFlow TutorialTensorFlow is an open-source machine-learning framework developed by Google. It is written in Python, making it accessible and easy to understand. It is designed to build and train machine learning (ML) and deep learning models. It is highly scalable for both research and production.It supports CPUs 2 min read Keras TutorialKeras high-level neural networks APIs that provide easy and efficient design and training of deep learning models. It is built on top of powerful frameworks like TensorFlow, making it both highly flexible and accessible. Keras has a simple and user-friendly interface, making it ideal for both beginn 3 min read PyTorch TutorialPyTorch is an open-source deep learning framework designed to simplify the process of building neural networks and machine learning models. With its dynamic computation graph, PyTorch allows developers to modify the networkâs behavior in real-time, making it an excellent choice for both beginners an 7 min read Caffe : Deep Learning FrameworkCaffe (Convolutional Architecture for Fast Feature Embedding) is an open-source deep learning framework developed by the Berkeley Vision and Learning Center (BVLC) to assist developers in creating, training, testing, and deploying deep neural networks. It provides a valuable medium for enhancing com 8 min read Apache MXNet: The Scalable and Flexible Deep Learning FrameworkIn the ever-evolving landscape of artificial intelligence and deep learning, selecting the right framework for building and deploying models is crucial for performance, scalability, and ease of development. Apache MXNet, an open-source deep learning framework, stands out by offering flexibility, sca 6 min read Theano in PythonTheano is a Python library that allows us to evaluate mathematical operations including multi-dimensional arrays efficiently. It is mostly used in building Deep Learning Projects. Theano works way faster on the Graphics Processing Unit (GPU) rather than on the CPU. This article will help you to unde 4 min read Model EvaluationGradient Descent Algorithm in Machine LearningGradient descent is the backbone of the learning process for various algorithms, including linear regression, logistic regression, support vector machines, and neural networks which serves as a fundamental optimization technique to minimize the cost function of a model by iteratively adjusting the m 15+ min read Momentum-based Gradient Optimizer - MLMomentum-based gradient optimizers are used to optimize the training of machine learning models. They are more advanced than the classic gradient descent method and helps to accelerate the training process especially for large-scale datasets and deep neural networks.By incorporating a "momentum" ter 4 min read Adagrad Optimizer in Deep LearningAdagrad is an abbreviation for Adaptive Gradient Algorithm. It is an adaptive learning rate optimization algorithm used for training deep learning models. It is particularly effective for sparse data or scenarios where features exhibit a large variation in magnitude.Adagrad adjusts the learning rate 6 min read RMSProp Optimizer in Deep LearningRMSProp (Root Mean Square Propagation) is an adaptive learning rate optimization algorithm designed to improve the performance and speed of training deep learning models.It is a variant of the gradient descent algorithm which adapts the learning rate for each parameter individually by considering th 5 min read What is Adam Optimizer?Adam (Adaptive Moment Estimation) optimizer combines the advantages of Momentum and RMSprop techniques to adjust learning rates during training. It works well with large datasets and complex models because it uses memory efficiently and adapts the learning rate for each parameter automatically.How D 4 min read Deep Learning ProjectsLung Cancer Detection using Convolutional Neural Network (CNN)Computer Vision is one of the applications of deep neural networks and one such use case is in predicting the presence of cancerous cells. In this article, we will learn how to build a classifier using Convolution Neural Network which can classify normal lung tissues from cancerous tissues.The follo 7 min read Cat & Dog Classification using Convolutional Neural Network in PythonConvolutional Neural Networks (CNNs) are a type of deep learning model specifically designed for processing images. Unlike traditional neural networks CNNs uses convolutional layers to automatically and efficiently extract features such as edges, textures and patterns from images. This makes them hi 5 min read Sentiment Analysis with an Recurrent Neural Networks (RNN)Recurrent Neural Networks (RNNs) are used in sequence tasks such as sentiment analysis due to their ability to capture context from sequential data. In this article we will be apply RNNs to analyze the sentiment of customer reviews from Swiggy food delivery platform. The goal is to classify reviews 5 min read Text Generation using Recurrent Long Short Term Memory NetworkLSTMs are a type of neural network that are well-suited for tasks involving sequential data such as text generation. They are particularly useful because they can remember long-term dependencies in the data which is crucial when dealing with text that often has context that spans over multiple words 4 min read Machine Translation with Transformer in PythonMachine translation means converting text from one language into another. Tools like Google Translate use this technology. Many translation systems use transformer models which are good at understanding the meaning of sentences. In this article, we will see how to fine-tune a Transformer model from 6 min read Deep Learning Interview QuestionsDeep learning is a part of machine learning that is based on the artificial neural network with multiple layers to learn from and make predictions on data. An artificial neural network is based on the structure and working of the Biological neuron which is found in the brain. Deep Learning Interview 15+ min read Like