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
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.
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.
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.
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.
| Method | Rows used | New intercept θ₀ | New slope θ₁ | All-row MSE (dollars²) |
|---|---|---|---|---|
| Batch, update 1 | 1, 2, 3 | 0.008000000 | 20.666667 | 2.330186e+09 |
| SGD, update 1 | 1 | 0.006000000 | 12.000000 | 6.926670e+08 |
| SGD, update 2 | 2 | -0.056000012 | -174.000036 | 1.978838e+11 |
| SGD, update 3 | 3 | 0.822000280 | 2021.000694 | 2.616677e+13 |
| Mini-batch, update 1 | 1, 2 | 0.008000000 | 21.000000 | 2.412417e+09 |
| Mini-batch, update 2 | 3 | -0.089000016 | -221.500040 | 3.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.

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.
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.

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:
= parameters
= learning rate
= number of training examples
= 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:
= parameters
= learning rate
= 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:
= parameters
= learning rate
= number of training examples in a mini-batch
= 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: ,
Day 2: ,
Day 3: ,
Model:
Initial Parameters: ,
Learning Rate:
Applying Gradient Descent Methods
Batch Gradient Descent
Calculate the gradient for each parameter across all data points.
Update parameters based on these gradients.
Repeat until convergence or for a fixed number of iterations.
Gradient Calculations and Update (One iteration):
Gradient of =
Gradient of =
Updated =
Updated =
Stochastic Gradient Descent
Updates parameters using each data point individually:
Update after Day 1:
updated to 0.006
updated to 6
Update after Day 2:
updated to 0.011
updated to 21
Update after Day 3:
updated to 0.019
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):
updated to 0.007
updated to 13.5
Second Batch (Day 3):
updated to 0.015
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 | Update | 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:
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.
