3 Types of Gradient Decent Types : Batch, Stochastic & Mini-Batch _ Day 8

Conceptual illustration of data grouped for batch, stochastic and mini-batch gradient descent.

Day 8 · Learning in batches

Batch, stochastic & mini-batch gradient descent

Same model. Different groups of data. Learn what changes at each update—with readable formulas, checked calculations and the complete original lesson.

Start the worked guide

Published 19 July 2024 · Expanded and checked 16 November 2026
Full original lesson preserved · Python, formulas and computed charts

Conceptual illustration of data grouped for batch, stochastic and mini-batch gradient descent.
A conceptual illustration of examples grouped for training; this is not a measured chart.

Choose the dataSee how many examples contribute to one gradient.

Follow the numbersUnderstand an unstable step size and a scaled alternative.

Read, then experimentCompare epochs, updates, original PyTorch and tested NumPy.

In this lesson

The quick answer

The batch size decides who contributes to the next step

Batch gradient descent uses the whole training set. Stochastic gradient descent, in its strict single-example form, uses one example. Mini-batch gradient descent uses a smaller group. Each then updates the parameters using the gradient calculated from that data.

If you are coming from Day 7’s gradient descent walkthrough, the new question is simple: how much data should the model examine before it takes another step?

Read the checked guide first

One update rule, three ways to choose the data

Batch, stochastic and mini-batch gradient descent differ in how many training examples contribute to each parameter update. Full batch uses all examples; the strict single-example version of SGD uses one; mini-batch uses a smaller group. The loss, model and learning rate still matter. Changing the batch size does not automatically make an unsuitable learning rate safe.

Calculation correction: the original revenue example contains arithmetic and cost-table errors, and its unscaled learning rate makes the verified updates diverge. The full original text, formulas, table and Python remain below. Use this added guide and its computed charts for the checked calculations; preserved historical numbers are not verified results.

1. Separate an example loss from the whole objective

Let ℓᵢ(θ) mean the loss for one example, and let J(θ) mean the average across all m training examples. The gradient points in the direction of steepest local increase. To minimize the objective, subtract a learning-rate-scaled gradient from the current parameters.

J(θ)=1m∑i=1mℓi(θ)

For a selected group B, average its individual gradients using the number of examples actually in that group. When B is the complete dataset, this is full-batch gradient descent. When it contains one example, this is a singleton update. Intermediate group sizes give mini-batch updates.

θnew=θold−η1|B|∑i∈B∇θℓi(θold)

The original formulas use J with an example argument. Read that argument as an individual-example loss in those expressions; averaging an already averaged full-dataset gradient again would introduce an unintended factor. All components of the parameter vector use the same old parameter values before the simultaneous update.

2. Count updates separately from epochs

An update changes the model once. An epoch visits the training dataset once. With 100 examples, full batch takes one update per epoch; batch size 1 takes 100; batch size 16 takes seven when the incomplete final group is retained. Those groups contain 16, 16, 16, 16, 16, 16 and 4 examples.

For this lesson’s three-row dataset, batch sizes 3, 1 and 2 produce one, three and two updates per epoch. The last mini-batch contains one row, so divide its summed gradient by one, not two. PyTorch’s default drop_last=False keeps incomplete batches. Setting it to true discards them and changes which data contribute.

3. Understand the trade-offs without declaring a universal winner

Using all training rows gives the exact gradient of the empirical objective at that parameter value. This avoids sampling noise, but does not guarantee small steps, monotonically decreasing loss or a global minimum for every objective. Full-batch gradients can also be accumulated in smaller chunks; holding the entire dataset in device memory is not a mathematical requirement.

Smaller groups can produce more variable gradients and more updates per pass. Mini-batches often use parallel hardware well, while singleton updates are useful for some streaming or online settings. Noise can change the optimization trajectory, but cannot guarantee escape from local minima, faster convergence or better predictions. The useful balance depends on the objective, hardware, data and evaluation budget.

Random sampling and reshuffling help avoid fixed ordering effects. In a typical shuffled finite-dataset epoch, examples are visited without replacement. Repeated sampling with replacement is a different scheme. The raw-dollar audit below deliberately follows the article’s stated row order; the scaled comparison uses reproducible shuffling shared by every method.

4. Recompute the original dollar example consistently

Keep the three original pairs: spend/revenue of ($2,000, $3,000), ($3,000, $5,000) and ($2,500, $4,000). The model is θ₀ + θ₁x, both parameters start at zero, and the stated learning rate is 0.000001. Here the objective is ordinary mean squared error, not the half-MSE convention used in Day 7.

J(θ)=1m∑i=1m(θ0+θ1xi−yi)2
g0=2|B|∑i∈Bei,g1=2|B|∑i∈Beixi

Each error eᵢ is the current prediction minus its target. Initially the errors are −3,000, −5,000 and −4,000. The intercept gradient is −8,000. The slope products sum to −31,000,000; multiplying by 2/3 gives −20,666,666.666667, rather than the original −36,666,666.67. The first full-batch update therefore gives θ₀ = 0.008 and θ₁ = 20.666667.

The initial all-row MSE is 16,666,666.666667 dollars². After that update it rises to approximately 2,330,185,947.851916 dollars². This is overshooting, not stable convergence. Subsequent singleton and mini-batch updates must recalculate errors using the newly updated model; repeatedly adding values based on the initial zero predictions is incorrect.

Verified raw-dollar updates at learning rate 0.000001. Values are rounded for display; calculations retain precision.
MethodRows usedNew intercept θ₀New slope θ₁All-row MSE (dollars²)
Batch, update 11, 2, 30.00800000020.6666672.330186e+09
SGD, update 110.00600000012.0000006.926670e+08
SGD, update 22-0.056000012-174.0000361.978838e+11
SGD, update 330.8220002802021.0006942.616677e+13
Mini-batch, update 11, 20.00800000021.0000002.412417e+09
Mini-batch, update 23-0.089000016-221.5000403.194107e+11

The first singleton update uses the first row, giving gradients −6,000 and −12,000,000, hence parameters 0.006 and 12. The second row is then predicted by that updated model, producing a large positive error and a negative next slope. The checked table shows why the original increasing positive slopes and decreasing cost table do not follow the stated MSE calculation.

5. Diagnose the learning rate before ranking methods

Dollar inputs in the thousands make the slope gradient large. For this exact two-parameter, full-batch quadratic, the largest Hessian eigenvalue is about 12,833,335.281385. Constant-step convergence from arbitrary starting parameters requires a positive learning rate below approximately 0.000000155844. The original 0.000001 exceeds that limit. This is a dataset-specific full-batch stability calculation, not a universal bound for every SGD or neural-network task.

Thus the old example cannot establish that mini-batch is the best method, nor that one method ran faster. Its arithmetic was inconsistent, its rate was unstable and no wall-clock benchmark was recorded. The first chart makes this concrete by evaluating the same full-dataset MSE after each checked update.

Three computed log-scale plots show full-dataset MSE rising after batch, singleton SGD and mini-batch updates at the original unscaled learning rate.
Exact recomputation of the original three-row dollar example. At the original learning rate of 0.000001, all three methods increase full-dataset MSE during the first epoch. Each marker is an update; the dashed line is the initial error. This is a numerical audit, not a runtime comparison. Select the chart to read its full-size labels.

6. Scale the example and keep the units explicit

For a clean teaching comparison, center spend at $2,500 and divide it by $500. Express revenue in thousands of dollars. The new inputs are −1, 1 and 0; the targets are 3, 5 and 4. Fit a + bz from zero using learning rate 0.1 and ordinary MSE.

z=x−2500500,t=y1000

The first full-batch gradients are −8 for a and −4/3 for b, so one update gives a = 0.8, b = 0.133333 and training MSE approximately 10.740741 in squared thousands of dollars. This loss uses different units from the raw-dollar chart and should not be compared numerically without converting units.

The exact fit to these three constructed points is a = 4 and b = 1. To return to dollars, predict 1,000 × (a + b × ((spend − 2,500) / 500)). At the exact solution this simplifies to revenue = 2 × spend − 1,000. That is an exact fit to three illustrative rows, not evidence that changing marketing spend causes a particular revenue or predicts future sales.

The new loss chart uses the same zero initialization, rate and epoch-by-epoch random permutations for every method, with seed 8. After 30 epochs there are 30 full-batch, 90 singleton and 60 mini-batch updates. All improve their training fit here. Comparing equal epochs also compares different update counts; the plot is not a wall-clock speed, sample-efficiency or held-out-accuracy ranking.

Computed log-scale MSE curves over 30 epochs for scaled batch, singleton SGD and mini-batch training, each starting from the same zero parameters.
A reproducible scaled version of the same teaching data. Every method starts at zero and receives the same epoch permutations (seed 8); the final one-row mini-batch is included. An epoch processes all three rows, but batch, SGD and mini-batch take 1, 3 and 2 updates respectively. The curves show training error only, not measured runtime or unseen-data accuracy. Select the chart to read its full-size labels.

7. Make the original PyTorch comparison fair

The preserved snippets correctly illustrate changing DataLoader batch sizes. However, running them consecutively reuses the model and optimizer trained by the earlier loop. Reset or recreate both for each independent comparison, use identical initial weights, control random seeds and keep the dataset, objective and evaluation rules consistent.

torch.optim.SGD uses the gradients supplied by the training loop; its name does not force batch size 1. The loader determines which examples contribute before loss.backward() and optimizer.step(). The default mean reduction in MSELoss averages over output elements; this example has one output per row. Original independent random inputs and targets have no specified predictive relationship.

The compact NumPy version below was executed and checked against the computed chart. The original PyTorch snippets remain intact further down; they were reviewed against official documentation but were not executed in this environment.


import numpy as np

# Three synthetic teaching rows, not a business forecasting dataset.
spend = np.array([2000., 3000., 2500.])
revenue = np.array([3000., 5000., 4000.])
z = (spend - 2500.) / 500.
X = np.column_stack([np.ones(3), z])
y = revenue / 1000.

def train(batch_size, epochs=30, rate=0.1):
    theta = np.zeros(2)       # Reset the model for every method.
    rng = np.random.default_rng(8)  # Identical epoch orders.
    history = [np.mean((X @ theta - y) ** 2)]
    for epoch in range(epochs):
        order = rng.permutation(len(y))
        for start in range(0, len(y), batch_size):
            ids = order[start:start + batch_size]
            error = X[ids] @ theta - y[ids]
            gradient = 2 * X[ids].T @ error / len(ids)
            theta = theta - rate * gradient
        history.append(np.mean((X @ theta - y) ** 2))
    return theta, np.array(history)

for name, size in [("Batch", 3), ("SGD", 1), ("Mini-batch", 2)]:
    theta, losses = train(size)
    print(name, theta, losses[-1])

8. Use the lesson in a real project

Choose the objective and units first. Monitor loss and finite parameters, check batching and the final partial batch, and record what an epoch and an update mean. Tune learning rate alongside batch size. To select a practical model, evaluate appropriate held-out data and measure runtime on your actual hardware. Three training rows cannot establish real business forecasting quality.

Primary documentation: PyTorch’s DataLoader reference documents batching, reshuffling and incomplete batches; MSELoss defines mean reduction; and SGD describes the parameter update. The numerical corrections and charts here were recomputed directly from the original three data points.

The complete original lesson

Every original explanation, formula, table and code example

The complete original text remains below, including its repeated explanations and historical numbers. Clearly labelled additions distinguish checked calculations from the preserved material. Use the guide above for the verified numerical results.

Long equations, tables and code scroll within their own regions. Select a region with the keyboard and use the arrow keys to read across. Charts open at full size.

Understanding Gradient Descent: Batch, Stochastic, and Mini-Batch

Understanding Gradient Descent: Batch, Stochastic, and Mini-Batch

Learn the key differences between Batch Gradient Descent, Stochastic Gradient Descent, and Mini-Batch Gradient Descent, and how to apply them in your machine learning models.

Batch Gradient Descent

Batch Gradient Descent uses the entire dataset to calculate the gradient of the cost function, leading to stable, consistent steps toward an optimal solution. It is computationally expensive, making it suitable for smaller datasets where high precision is crucial.

Formula:

θ:=θ−η·1m∑i=1m∇θJ(θ;x(i),y(i))

  • θ = parameters

  • η = learning rate

  • m = number of training examples

  • ∇θJ(θ;x(i),y(i)) = gradient of the cost function

Stochastic Gradient Descent (SGD)

Stochastic Gradient Descent updates parameters using each training example individually. This method can quickly adapt to new patterns, potentially escaping local minima more effectively than Batch Gradient Descent. It is particularly useful for large datasets and online learning environments.

Formula:

θ:=θ−η·∇θJ(θ;x(i),y(i))

  • θ = parameters

  • η = learning rate

  • ∇θJ(θ;x(i),y(i)) = gradient of the cost function for a single training example

Mini-Batch Gradient Descent

Mini-Batch Gradient Descent is a hybrid approach that divides the dataset into small batches and updates parameters for each batch. This method balances the robustness of Batch Gradient Descent with the flexibility and speed of Stochastic Gradient Descent, making it highly efficient, especially on modern hardware that can parallelize computations.

Formula:

θ:=θ−η·1n∑i=1n∇θJ(θ;x(i),y(i))

  • θ = parameters

  • η = learning rate

  • n = number of training examples in a mini-batch

  • ∇θJ(θ;x(i),y(i)) = gradient of the cost function for a mini-batch

Key Takeaways

  • Batch Gradient Descent: Best for smaller datasets; provides stable but slow convergence.

  • Stochastic Gradient Descent (SGD): Suitable for large datasets and online learning; faster updates but can be noisy.

  • Mini-Batch Gradient Descent: Combines the benefits of both; optimal for deep learning with balanced performance and stability.

Choosing the right gradient descent method can significantly impact the efficiency and performance of your machine learning model. For most deep learning tasks, Mini-Batch Gradient Descent is the preferred choice due to its balanced approach. For more in-depth guides and practical implementations, check out resources from Machine Learning Mastery and Analytics Vidhya.

Gradient Descent Example for Small Business Revenue Prediction

Gradient Descent Example for Small Business Revenue Prediction

Introduction

This part of the blog will use a simple linear regression to predict the revenue based on marketing spend. We will use a small dataset to illustrate how each gradient descent method performs and impacts the efficiency and accuracy of the model.

Dataset and Initial Setup

Our dataset consists of three data points representing daily marketing spend and the revenue:

  • Day 1: x1=$2000, y1=$3000

  • Day 2: x2=$3000, y2=$5000

  • Day 3: x3=$2500, y3=$4000

Model: y=θ0+θ1·x

Initial Parameters: θ0=0, θ1=0

Learning Rate: η=0.000001

Applying Gradient Descent Methods

Batch Gradient Descent

  1. Calculate the gradient for each parameter across all data points.

  2. Update parameters based on these gradients.

  3. Repeat until convergence or for a fixed number of iterations.

Gradient Calculations and Update (One iteration):

  • Gradient of θ0 = 23[(−3000)+(−5000)+(−4000)]=−8000

  • Gradient of θ1 = 23[(−3000×2000)+(−5000×3000)+(−4000×2500)]=−36666666.67

  • Updated θ0 = 0−0.000001×−8000=0.008

  • Updated θ1 = 0−0.000001×−36666666.67=36.67

Stochastic Gradient Descent

Updates parameters using each data point individually:

  • Update after Day 1:

    • θ0 updated to 0.006

    • θ1 updated to 6

  • Update after Day 2:

    • θ0 updated to 0.011

    • θ1 updated to 21

  • Update after Day 3:

    • θ0 updated to 0.019

    • θ1 updated to 29.5

Mini-Batch Gradient Descent

Using mini-batches of size 2 (First two days as one batch and the third day as another batch):

  • First Batch (Day 1 & 2):

    • θ0 updated to 0.007

    • θ1 updated to 13.5

  • Second Batch (Day 3):

    • θ0 updated to 0.015

    • θ1 updated to 26.75

Comparison and Conclusion

Batch Gradient Descent provides the most stable and consistent updates but may be slow for larger datasets. Stochastic Gradient Descent offers faster updates but can result in significant parameter fluctuations, which may hinder convergence. Mini-Batch Gradient Descent balances both approaches, providing updates that are both timely and relatively stable, making it ideal for most practical applications.

Gradient Descent Detailed Comparison for Revenue Prediction Model

Gradient Descent Detailed Comparison for Revenue Prediction Model

Overview

This section provides a comprehensive view of how different gradient descent methods perform over multiple iterations using the revenue prediction model. Detailed calculations help determine the most effective method for this specific dataset.

Method Iteration θ0 Update θ1 Update Cost Function Value
Batch Gradient Descent 1 0.008 36.67 15083333.33
2 0.015 52.33 7531250.00
3 0.021 61.75 3760572.92
Stochastic Gradient Descent 1 0.019 29.5 2004625.00
2 0.027 41.20 1002568.75
3 0.034 47.85 501300.78
Mini-Batch Gradient Descent 1 0.015 26.75 5037083.33
2 0.023 38.67 2517786.46
3 0.029 45.20 1258893.23

Calculations Explained

Each method was iterated three times. The cost function used was Mean Squared Error (MSE), calculated as follows:

MSE=1m∑(y(i)−(θ0+θ1×x(i)))2

After three iterations, here is how each method performed:

  • Batch Gradient Descent showed the most significant reduction in the cost function due to stable, consistent updates but was slowest in terms of computational speed.

  • Stochastic Gradient Descent had more frequent updates with less stability, which sometimes led to faster convergence but at the cost of higher volatility in parameter changes.

  • Mini-Batch Gradient Descent provided a balance between stability and speed, resulting in efficient and moderately stable parameter updates.

Conclusion for this example

For the given small dataset, Mini-Batch Gradient Descent emerged as the preferred method due to its efficient use of resources and balance between speed and stability. This method allows for faster convergence without the high volatility associated with SGD, making it suitable for both small and moderately large datasets.

General Conclusion on Gradient Descent Methods

When evaluating gradient descent methods—Batch, Stochastic, and Mini-Batch—each serves specific needs depending on the dataset size, computational resources, and the desired balance between stability and speed of convergence:

  • Batch Gradient Descent: Ideal when computational resources are abundant and stability is crucial, as it computes precise gradients using the entire dataset. However, it is impractical for very large datasets due to high memory and time requirements.

  • Stochastic Gradient Descent (SGD): Suitable for extremely large or streaming datasets where quick updates are needed. Its noisy updates can help escape local minima but may lead to instability and slower convergence due to high variance in gradient estimation.

  • Mini-Batch Gradient Descent: Offers the best of both worlds by balancing stability and computational efficiency. It reduces the noise in gradient updates while processing data in smaller batches, making it a versatile choice for most applications.

In summary, the choice of gradient descent method should align with the problem requirements and available resources. Mini-Batch Gradient Descent often stands out as the most practical and adaptable approach, suitable for a wide range of dataset sizes and scenarios.

Example of How it look on Code ? Lets see lastly, theGradient Descent Code Example in PyTorch

Gradient Descent Methods in PyTorch

1. Batch Gradient Descent

Batch Gradient Descent processes the entire dataset in one go to compute the gradients and update the weights.


import torch
from torch import nn, optim
from torch.utils.data import DataLoader, TensorDataset

# Example Dataset
X = torch.rand(100, 3)
y = torch.rand(100, 1)

# DataLoader for Batch Gradient Descent
batch_loader = DataLoader(TensorDataset(X, y), batch_size=len(X), shuffle=True)

# Simple Model
model = nn.Linear(3, 1)
criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)

# Training Loop
for epoch in range(100):
    for batch_X, batch_y in batch_loader:
        optimizer.zero_grad()
        predictions = model(batch_X)
        loss = criterion(predictions, batch_y)
        loss.backward()
        optimizer.step()
    

2. Stochastic Gradient Descent (SGD)

Stochastic Gradient Descent processes one data point at a time for updates.


# DataLoader for Stochastic Gradient Descent
sgd_loader = DataLoader(TensorDataset(X, y), batch_size=1, shuffle=True)

# Training Loop
for epoch in range(100):
    for sample_X, sample_y in sgd_loader:
        optimizer.zero_grad()
        predictions = model(sample_X)
        loss = criterion(predictions, sample_y)
        loss.backward()
        optimizer.step()
    

3. Mini-Batch Gradient Descent

Mini-Batch Gradient Descent uses a small batch of data to compute the gradients and update weights.


# DataLoader for Mini-Batch Gradient Descent
mini_batch_loader = DataLoader(TensorDataset(X, y), batch_size=16, shuffle=True)

# Training Loop
for epoch in range(100):
    for mini_batch_X, mini_batch_y in mini_batch_loader:
        optimizer.zero_grad()
        predictions = model(mini_batch_X)
        loss = criterion(predictions, mini_batch_y)
        loss.backward()
        optimizer.step()
    

Key Differences in these 3 Codes

Each gradient descent method differs primarily in the choice of batch size, which determines the number of samples used to compute the gradient updates. Here’s how it is set in the code:

  • Batch Gradient Descent: batch_size=len(X) (entire dataset as one batch). This ensures the model processes the whole dataset before performing a single update.

  • Stochastic Gradient Descent (SGD): batch_size=1 (one sample at a time). Each gradient update is computed for a single data point, introducing high variability in updates.

  • Mini-Batch Gradient Descent: batch_size=16 (a subset of data, e.g., 16 samples). This balances the stability of Batch GD and the faster updates of SGD, making it a commonly used approach.

These differences in batch size directly impact the speed, stability, and computational efficiency of the training process, allowing you to choose the most suitable method based on the dataset size and computational resources available.

Common questions

Batch size and gradient descent, explained

What is the difference between batch, stochastic and mini-batch gradient descent?

Full-batch gradient descent uses every training example for one update. The single-example version of stochastic gradient descent uses one example. Mini-batch gradient descent averages gradients over a smaller group. The model, loss, learning rate and data order also affect the result.

How many updates are in one epoch?

It depends on the batch size. With 100 examples and an incomplete final batch retained, batch sizes 100, 1 and 16 produce 1, 100 and 7 updates per epoch. The final group at batch size 16 contains four examples.

Does torch.optim.SGD require a batch size of one?

No. The optimizer applies the gradients supplied by the training loop. DataLoader batching and the loss calculation determine whether an update uses one example, a mini-batch or the entire training dataset.

Why does the original revenue example diverge?

The original arithmetic is inconsistent with ordinary MSE, and its learning rate of 0.000001 is too large for the unscaled three-point full-batch quadratic. The checked first batch update gives intercept 0.008 and slope about 20.666667, increasing rather than decreasing all-row MSE.

Is mini-batch gradient descent always the best choice?

No. Useful batch sizes depend on the objective, data, memory, hardware and evaluation budget. Compare learning rates alongside batch sizes, reset the model for each experiment, and measure validation performance and runtime separately.

Does fitting the three revenue rows predict future sales?

No. These three illustrative rows demonstrate optimization arithmetic. An exact training fit does not establish future forecasting accuracy or a causal effect of marketing spend on revenue. Real forecasting needs suitable data and independent evaluation.

Continue the series

Next: build a first artificial neuron

You now know how examples are grouped for training. In Day 9, connect these optimization ideas with the perceptron, a simple foundation for neural networks.

Editorial note: added calculations and charts were independently recomputed from the original three-row example. The added NumPy example was executed. The preserved PyTorch snippets were reviewed against official documentation but were not executed here. This lesson illustrates optimization; it does not establish marketing outcomes or future revenue.

You Can Also Learn Deep Learning in 80 Days Inside the iOS App Continue this roadmap in a focused mobile study experience with offline access, flashcards, notes, and progress tracking.
Open on the App Store