Recommended resources
The freely available resources this lesson will direct you to.
- Derivative of Cost function for Logistic Regression | Machine Learningwww.youtube.com
- Locally Weighted & Logistic Regression | Stanford CS229: Machine Learning - Lecture 3 (Autumn 2018)www.youtube.com
- Logistic Regressionweb.stanford.edu
- 9 Optimization with Gradient Descent – Machine Learningwww.philchodrow.prof
Hello! Welcome to the next lesson in our journey through the mathematical foundations of machine learning.
In our previous session, we accomplished a crucial task: we derived the gradient of the logistic regression cost function. We found that for the average cross-entropy loss , the partial derivative with respect to a single parameter is:
With the cost function and its gradient, we now have a map of the "error surface" and a compass that points in the direction of steepest ascent. Today's lesson is about using that compass to find the lowest point on the map. We will apply the gradient descent algorithm to iteratively find the optimal set of parameters that minimizes our cost function, effectively training our model.
This lesson is the bridge between the pure calculus of the last session and a functional machine learning algorithm.
1. The Gradient Descent Algorithm: A Formal View
You've likely encountered gradient descent in your practical work, but your goal is to master the theory. So, let's move beyond the common analogy of "walking downhill" and formally establish why the algorithm works. The core idea is to take a small step in the direction opposite to the gradient, which is guaranteed to decrease the function's value, provided the step is small enough.
We can prove this using a Taylor approximation. For a deeper, more rigorous explanation of this process, the following resource is an excellent read.
9 Optimization with Gradient Descent – Machine Learning
The note 'Optimization with Gradient Descent' by Prof. Phil Chodrow provides a formal justification for the gradient descent algorithm. It uses first-order Taylor approximations to prove that the update step indeed reduces the objective function's value.
Please read the sections 'Gradient Descent in 1 dimension' and 'Multivariate Gradient Descent'. Pay close attention to the derivation that shows how choosing the update direction as the negative gradient leads to a reduction in the function's value (e.g., (g(\hat{\mathbf{w}} - \alpha abla g(\hat{\mathbf{w}})) < g(\hat{\mathbf{w}}))).
The General Update Rule
As shown in the reading, the argument culminates in a simple, powerful, iterative update rule. Starting with an initial guess for the parameters , we repeatedly update them at each step :
Let's break this down:
- is the vector of parameters at iteration .
- is the learning rate, a scalar hyperparameter that controls the size of our step.
- is the gradient of the cost function evaluated with the current parameters.
This update is performed for each parameter in the vector simultaneously.
2. Gradient Descent for Logistic Regression
Now, let's make this concrete by substituting the specific gradient for logistic regression that we derived in the last lesson.
The update rule for a single parameter becomes:
Here, is the model's prediction for example using the parameters from step .
The Guarantee of Convergence: Convexity
A critical question is whether this iterative process will find the best possible parameters. For many complex models, gradient descent can get stuck in "local minima"—valleys that aren't the lowest point on the entire error surface.
Fortunately, for logistic regression, this is not a concern. The cross-entropy loss function is convex. A convex function has a bowl-like shape, meaning it has only one minimum, which is the global minimum.

Andrew Ng also discusses this important property in his CS229 lecture.
Locally Weighted & Logistic Regression | Stanford CS229: Machine Learning - Lecture 3 (Autumn 2018)
In this segment from Stanford's CS229 lecture, Andrew Ng explains the optimization process for logistic regression. He highlights that the log-likelihood function is concave (which means the negative log-likelihood, our cost function, is convex), and thus gradient descent will not get stuck in local optima.
Please watch from 00:57:55 to 01:04:53. Focus on the explanation of gradient ascent for maximizing the log-likelihood and the explicit mention that the function is concave, guaranteeing a single global maximum (and thus a single global minimum for our cost function).
3. A Worked Example
Let's trace one single step of gradient descent to make this tangible. The following resource provides a clear walkthrough.
The textbook chapter 'Logistic Regression' by Jurafsky and Martin provides an excellent, easy-to-follow worked example of a single gradient descent update step.
Read the short section 'Working through an example' (Section 5.4.3). It demonstrates how to calculate the prediction, the gradient, and the new updated weights for a single training example.
Let's recap the example from the text.
- Input: , with true label .
- Initial Parameters: . (Using notation here, equivalent to ).
- Learning Rate: .
-
Calculate Prediction ( or ):
The linear part is .
The prediction is . -
Calculate Gradient: The gradient of the loss for this single example w.r.t each parameter is .
So, .
-
Update Parameters: .
After just one step, the weights have been nudged in a direction that will make the prediction for this example closer to the true label. This process is repeated until the parameters converge.
4. Practical Aspects of Gradient Descent
The update rule we've used so far, which sums over all training examples for every single update, is known as Batch Gradient Descent. In practice, there are variations with different trade-offs.
The Learning Rate
The learning rate is arguably the most important hyperparameter.
- If is too small: Convergence will be very slow, requiring many iterations.
- If is too large: The algorithm can "overshoot" the minimum and fail to converge. The cost might oscillate or even diverge (increase) with each step.

Batch, Stochastic, and Mini-Batch Gradient Descent
The choice of how many examples to use for computing the gradient in each update step leads to three main variants. The Jurafsky and Martin text provides an excellent summary.
To understand the practical variants of gradient descent, we'll return to the Jurafsky and Martin textbook.
Please read Section 5.4.2 ('The Stochastic Gradient Descent Algorithm') and Section 5.4.4 ('Mini-batch training'). This will explain the three main flavors of gradient descent.
Here is a summary:
-
Batch Gradient Descent:
- Update: Uses the entire training set ( examples) to compute the gradient for one parameter update.
- Pros: Stable, straight path towards the minimum.
- Cons: Very computationally expensive and slow on large datasets.
-
Stochastic Gradient Descent (SGD):
- Update: Uses a single training example to compute the gradient and update the parameters.
- Pros: Much faster updates. Allows for online learning.
- Cons: The path to the minimum is very noisy ("stochastic"). The cost function may fluctuate heavily.
-
Mini-Batch Gradient Descent:
- Update: Uses a small batch of examples (e.g., 32, 64, 128) to compute the gradient.
- Pros: A compromise that offers the best of both worlds. It's computationally efficient due to vectorization and provides a more stable convergence than SGD.
- Cons: Introduces another hyperparameter: the batch size.
In modern deep learning and machine learning, mini-batch gradient descent is the most common approach.
Test your understanding!
Imagine you are training a logistic regression model on a dataset with 10 million images. You have a powerful GPU available. Which variant of gradient descent (Batch, Stochastic, or Mini-Batch) would you choose and why? What would be the main problem with the other two options in this scenario?
Show answer
The best choice would be Mini-Batch Gradient Descent.
- Why? It takes advantage of the GPU's parallel processing capabilities. A mini-batch of images (e.g., 256) can be processed in a highly vectorized manner, making gradient computation very efficient. It provides a good balance between the stability of Batch GD and the speed of SGD.
The problems with the other two are:
- Batch Gradient Descent: It would be prohibitively slow. To perform a single parameter update, you would need to process all 10 million images, which would be a massive computational bottleneck and wouldn't fit in the memory of most GPUs.
- Stochastic Gradient Descent: While fast per update, it fails to leverage the parallel power of the GPU. Processing one image at a time is inefficient. Furthermore, the updates would be extremely noisy, leading to a very erratic convergence path.
Conclusion
In this lesson, we put the gradient to work. We formally defined the gradient descent algorithm and proved why it is guaranteed to reduce our cost function. By combining this algorithm with the specific gradient for logistic regression, we now have a complete recipe for training the model.
Key Takeaways:
- The gradient descent update rule is .
- We can prove that this update reduces the cost function using a Taylor series approximation.
- Because the cross-entropy loss for logistic regression is a convex function, gradient descent is guaranteed to find the unique global minimum.
- The learning rate () is a critical hyperparameter that balances convergence speed and stability.
- Mini-Batch Gradient Descent is the most common optimization strategy in practice, offering a balance between computational efficiency and update stability.
Preview of the Next Lesson:
We have now covered how to define, derive, and optimize a logistic regression model to find the best parameters . But what do these learned parameters actually represent? In our next lesson, we will explore the geometric interpretation of and see how it defines the decision boundary that the model uses to separate the classes.