Day 05 · Predict, measure, update
Stochastic gradient descent, step by step.
Follow one small update at a time. Work through the loss, gradients, weights and bias of a two-point example, with readable equations and computed visual guides.
Start the lesson
Understand the directionSee why the update moves against the gradient.
Follow every calculationTrace two complete epochs and their tabular recap.
Read loss with careCompare a single-point improvement with the full objective.
In this lesson
Reading note: a single-example update does not always reduce the loss over the whole dataset. Use the computed plots and reading notes alongside the original walkthrough.
In our previous blog post – on day 4 – we have talked about using the SGD algorithm for the MNIST dataset. But what is Stochastic Gradient Descent?
Stochastic Gradient Descent (SGD) is an iterative method for optimizing an objective function that is written as a sum of differentiable functions. It’s a variant of the traditional gradient descent algorithm but with a twist: instead of computing the gradient of the whole dataset, it approximates the gradient using a single data point or a small batch of data points. This makes SGD much faster and more scalable, especially for large datasets.
Why is SGD Important?
- Efficiency: By updating the parameters using only a subset of data, SGD reduces computation time, making it faster than batch gradient descent for large datasets.
- Online Learning: SGD can be used in online learning scenarios where the model is updated continuously as new data comes in.
- Convergence: Although SGD introduces more noise into the optimization process, this can help in escaping local minima and finding a better global minimum.
The SGD Algorithm
The goal of SGD is to minimize an objective function with respect to the parameters . Here’s the general procedure:
- Initialize: Randomly initialize the parameters .
-
Iterate: For each data point :
- Compute the gradient of the loss function with respect to using .
- Update the parameters: , where is the learning rate.
- Repeat: Continue iterating until convergence or for a specified number of epochs.
A Detailed Example of SGD
Let’s walk through a simple example of SGD using a linear regression problem with just two data points. This will help illustrate each step of the algorithm.
Problem Setup
We have two data points:
(x_1, y_1) = (1, 2) (x_2, y_2) = (2, 3)
We aim to find a linear function that best fits these data points using SGD to minimize the Mean Squared Error (MSE) loss function.
Objective Function
The Mean Squared Error (MSE) loss function measures how well the line fits the data points. It is defined as:
Here:
- : The loss function we want to minimize.
- : The number of data points.
- : The data points.
- : The predicted value for .
For our two data points, . So, the loss function becomes:
This loss function represents the average squared difference between the actual values and the predicted values. Minimizing this function means finding the line that best fits the data.
Gradients
To minimize the loss function, we need to compute its gradients (partial derivatives) with respect to the parameters and . The gradients indicate the direction and rate of change of the loss function with respect to each parameter.
The general formulas for the gradients of the loss function with respect to and are:
In Stochastic Gradient Descent (SGD), we update the parameters using only one data point at a time, rather than the entire dataset. So, for each individual data point, the gradients become:
These formulas derive from the chain rule in calculus and show how changes in and affect the overall error.
Detailed SGD Steps

Detailed Steps of Stochastic Gradient Descent (SGD)
SGD Steps
- Initialize Parameters: Start with initial guesses for and . Let’s initialize and . We also set a learning rate .
-
Iterate Over Data Points:
- Compute the predicted value using the current values of and .
- Calculate the error between the actual value and the predicted value .
- Compute the gradients of the loss function with respect to and .
- Update the parameters and using the computed gradients and the learning rate.
First Epoch (First Pass Over the Data Points)
Data Point 1:
- Predict the Value: Using the initial values and :
- Calculate the Error:
- Compute the Gradients: Substituting the values for the first data point: These gradients tell us how much the parameters and need to change to reduce the error.
- Update the Parameters: Applying the updates: The learning rate controls how much we adjust the parameters in each step. A smaller learning rate means smaller adjustments, and a larger learning rate means larger adjustments.
Data Point 2:
- Predict the Value: Using the updated values and :
- Calculate the Error:
- Compute the Gradients: Substituting the values for the second data point: These gradients indicate how much the parameters and need to change to reduce the error further.
- Update the Parameters: Applying the updates:
Second Epoch (Second Pass Over the Data Points)
Data Point 1:
- Predict the Value: Using the updated values and :
- Calculate the Error:
- Compute the Gradients: Substituting the values for the first data point:
- Update the Parameters: Applying the updates:
Data Point 2:
- Predict the Value: Using the updated values and :
- Calculate the Error:
- Compute the Gradients: Substituting the values for the second data point:
- Update the Parameters: Applying the updates:
Summary of Updates
After two epochs (two passes over the data points), the parameters and are updated as follows:
- After the first epoch: ,
- After the second epoch: ,
By continuing this process for more epochs, the parameters will converge further to the optimal solution that minimizes the MSE loss.

Conclusion
This detailed breakdown shows each step of Stochastic Gradient Descent (SGD) for a simple linear regression problem, explaining the formulas used and their purpose. SGD updates the model parameters iteratively based on the gradients computed from individual data points, making it efficient for large-scale data and suitable for online learning. Understanding these steps and formulas helps in comprehending how SGD works to minimize the error and improve the model.
Second Epoch (Tabular View)
Data Point 1:
| Step | Formula | Value |
|---|---|---|
| Predict the Value | 1.88 | |
| Calculate the Error | 0.12 | |
| Compute the Gradient | -0.24 | |
| Compute the Gradient | -0.24 | |
| Update | 1.144 | |
| Update | 0.784 |
Data Point 2:
| Step | Formula | Value |
|---|---|---|
| Predict the Value | 3.072 | |
| Calculate the Error | -0.072 | |
| Compute the Gradient | 0.288 | |
| Compute the Gradient | 0.144 | |
| Update | 1.1152 | |
| Update | 0.7696 |
Conclusion
In this blog post, we explored the step-by-step workings of Stochastic Gradient Descent (SGD), illustrating how parameters are initialized, errors calculated, gradients computed, and weights updated iteratively. Through detailed examples and tables, we saw how these steps help minimize the error function and optimize model predictions.
For example, consider a linear regression model predicting house prices based on size. SGD calculates the error as the difference between the predicted value (e.g., ) and the actual value (). This error is used to compute the gradients, which indicate how much the parameters (weight) and (bias) should be adjusted. The adjustments are proportional to the learning rate , ensuring gradual improvement with each iteration.
With more epochs (passes over the dataset), the model refines its parameters as it iterates through the data repeatedly. In the early epochs, errors tend to be higher due to randomly initialized parameters. However, as the gradients guide the updates, the error reduces progressively, bringing the predictions closer to the actual values. This iterative process ensures that the model learns effectively from the data, even in noisy or large datasets.
Real-World Implications: SGD is particularly powerful for tasks like:
- Predictive Modeling: Estimating continuous outcomes, such as sales forecasts or price predictions.
- Classification: Assigning categories, such as spam detection or image recognition.
- Large-Scale Learning: Training models on massive datasets where accessing the entire dataset at once is impractical.
The stochastic nature of SGD introduces a degree of randomness in parameter updates, which helps escape local minima and improves convergence toward a global minimum in non-convex problems. As demonstrated in our example, increasing epochs ensures that SGD captures the underlying patterns in data more effectively, leading to a model that predicts with greater accuracy.
By mastering these concepts and techniques, practitioners can leverage SGD to build robust models capable of solving a wide array of problems efficiently and effectively.
Make the interpretation precise
Small updates need careful interpretation.
- Single-example and mini-batch updates. This walkthrough visits point 1, then point 2, in each epoch. It illustrates one-example updates in a fixed order. SGD commonly samples or reshuffles examples; mini-batch SGD averages gradients over a small group.
- The loss convention matters. The article averages squared errors with 1/n. Its 1/2 is because there are two points, not an extra half multiplying every loss. The per-point derivative therefore includes the factor 2.
- Zero initialization is valid here. The worked example starts w and b at zero. Random initialization is not a universal requirement for linear regression; some other models need different initialization choices.
- Full loss need not fall after every update. At update 4, the selected point’s prediction changes from 3.072 to exactly 3, while the other point’s prediction changes from 1.928 to 1.8848. That trade-off raises the full MSE from 0.005184 to 0.00663552.
- More epochs are not an automatic accuracy guarantee. Learning rate, sampling, scaling and stopping choices matter. Monitor suitable validation evidence. SGD does not generally guarantee a global minimum for non-convex problems.
- These are two teaching points. Their exact fitting line is y = x + 1, giving w = 1 and b = 1. The four updates are a checked arithmetic example, not evidence of real-world prediction quality.
The two new plots are computed from the displayed example. Their complete numeric update record is summarized in the captions; the original equations, explanations and tables remain in the walkthrough.
Questions & further reading
Keep the core ideas close.
What is stochastic gradient descent?
Stochastic gradient descent updates model parameters using a gradient calculated from one sampled training example. Mini-batch SGD uses a small group. Both avoid calculating the full-dataset gradient for every update.
What do w, b and the learning rate mean?
In the example y = wx + b, w is the slope and b is the intercept. The learning rate determines how large a step is taken in the direction opposite to the gradient.
What is an epoch in this two-point example?
An epoch is one complete pass over the data. The walkthrough uses two points, so each epoch contains two single-example updates; two epochs contain four updates.
What values are reached after the two epochs?
Starting with w = 0, b = 0 and learning rate 0.1, the first epoch ends at w = 1.12 and b = 0.76. The second ends at w = 1.1152 and b = 0.7696.
Does every SGD step reduce the full training loss?
No. In this example, update four reduces the error of its selected point but raises the full two-point MSE from 0.005184 to 0.00663552. A single-example gradient is different from the full-dataset gradient.
Does training for more epochs guarantee a better model?
No. Convergence depends on the problem and optimization choices, while prediction quality needs suitable validation. More updates do not generally guarantee a global optimum or better results on unseen data.
Primary sources
Continue learning, then build something useful.
Compare iterative updates with the next lesson’s direct linear-regression solution.
