Hello! Welcome to the next lesson in our journey through supervised learning.
In the last lesson, you successfully implemented the sigmoid function, our tool for converting a linear model's output into a probability between 0 and 1. We now have a way to make a prediction: given an input , we can compute a linear score and then find the predicted probability .
But how do we know if our prediction is any good? And more importantly, how can we systematically improve our model's parameters, and , to make better predictions? To answer these questions, we need a loss function that quantifies the error between our prediction and the true label .
Today, we will dive into the binary cross-entropy loss function, the standard for binary classification tasks. Our main goal is to derive and calculate its gradient. This gradient is the crucial signal that will tell our gradient descent optimizer how to adjust the model's parameters to minimize the error.
1. Quantifying Error with Binary Cross-Entropy
For linear regression, we used Mean Squared Error (MSE), which measures the average squared distance between predicted and true values. For classification, the problem is different. We are predicting probabilities, not continuous values.
The loss function for logistic regression is called Binary Cross-Entropy (BCE), or log loss. For a single training example, it's defined as:
Let's break down why this works:
-
Case 1: True label
The formula simplifies to . If our prediction is close to 1 (e.g., 0.99), is close to 0, so the loss is very small. If is close to 0 (e.g., 0.01), is a large negative number, so the loss becomes very large. The model is heavily penalized for being confidently wrong. -
Case 2: True label
The formula simplifies to . If our prediction is close to 0, then is close to 1, and the loss is small. If is close to 1, then is close to 0, and the loss becomes very large. Again, the model is penalized for being wrong.
This plot visualizes the behavior perfectly.

The total cost over the entire training set of examples is simply the average of the individual losses:
Our goal is to find the parameters (or weights ) and that minimize this cost function .
2. Deriving the Gradient of the Loss Function
To use gradient descent, we need to compute the partial derivatives of the cost function with respect to each parameter. Let's focus on a single parameter (a single weight in our weight vector) and the bias . For simplicity, let's consider the loss for a single training example, .
We'll use the chain rule, which is fundamental to how neural networks are trained. You'll see it again when we cover backpropagation. Our variables are linked like this:
- A linear combination:
- The sigmoid activation:
- The loss:
To find , we can chain the derivatives together:
Let's derive each piece. The following reading provides an excellent, step-by-step derivation.
Logistic Regression Model from Scratch
This article, 'Logistic Regression Model from Scratch', contains a clear derivation of the gradient using the chain rule. We'll follow its logic closely.
Read the section titled 'Gradient Descent' up to equation (13). Focus on how the author breaks down the problem using the chain rule into three smaller derivatives and then combines them at the end. Don't worry about the vector notation (∇) for now; we'll focus on the single-variable derivatives first.
Let's re-create that derivation here to solidify our understanding.
Step 1: Derivative of Loss w.r.t. Prediction ()
Step 2: Derivative of Sigmoid w.r.t. its Input ()
This is a classic derivative. The derivative of has a neat form:
Step 3: Derivative of Linear Combination w.r.t. a Weight ()
Given , the partial derivative with respect to is simply its corresponding feature value, .
Putting It All Together
Now, we multiply the three parts:
The terms cancel out, leaving us with a wonderfully simple result:
This result is elegant and intuitive. The gradient for a weight is the prediction error multiplied by the corresponding input feature . If the error is large, the gradient is large, leading to a bigger update.
For the bias term, , the derivation is similar, but since , the final gradient is just the error term:
Test your understanding!
Looking at the final gradient formula , what happens to the gradient if the model's prediction is perfect (i.e., )? What does this imply for the gradient descent update step?
Show answer
If the prediction is perfect, the error term becomes zero. This makes the entire gradient equal to zero. In the gradient descent update step (), this means the weight will not be updated at all, because we are already at a point of minimum loss for that specific training example.
3. Vectorizing the Gradient Calculation
Performing these calculations one example and one feature at a time is inefficient. Given your experience with NumPy, you know that vectorization is the key to performance. Let's see how to compute the gradients for all parameters across all training examples in one go.
The cost function gradient, averaged over all examples, can be written in matrix form.
- Let be the design matrix of shape (), where is the number of examples and is the number of features.
- Let be the vector of true labels of shape ().
- Let be the vector of predicted probabilities of shape ().
- Let be the weight vector of shape ().
The vectorized gradients are:
This matrix multiplication might seem abstract, but it's just a compact way of computing for all and and summing them up correctly.
The following video from the DeepLearningAI course by Andrew Ng provides an excellent explanation of how this vectorization works in practice.
Vectorizing Logistic Regression's Gradient Computation (C1W2L14)
This video breaks down how to transition from a for loop over training examples to a fully vectorized implementation for computing the gradients.
Watch the entire video (from 00:35 to 08:22). Pay close attention to how the individual dz terms are stacked into a vector DZ, and how matrix multiplication (X * DZ.T) is used to compute the final dw gradient vector without any explicit loops. This is a core concept you will use when implementing logistic regression.
To summarize the key idea from the video, the steps for one iteration of gradient descent are:
- Forward Pass (Vectorized):
Z = np.dot(X, w) + b(orw.T @ Xifwis a row vector)A = sigmoid(Z)(HereAis )
- Backward Pass / Gradient Calculation (Vectorized):
dZ = A - Ydw = (1/m) * np.dot(X.T, dZ)db = (1/m) * np.sum(dZ)
- Parameter Update:
w = w - learning_rate * dwb = b - learning_rate * db
This sequence of operations is exactly what you will implement in the next lesson to build your logistic regression classifier.
Conclusion
In this lesson, we bridged the gap between making a prediction and learning from our errors. You now understand the "engine" of logistic regression.
Key Takeaways:
- Binary Cross-Entropy is the loss function used to measure the error in binary classification models. It heavily penalizes confident but incorrect predictions.
- Using the chain rule, we derived the gradient of the loss function with respect to the model's parameters.
- The gradient for a single weight has the simple and intuitive form: (prediction_error) × (input_feature), or .
- Vectorization allows us to compute these gradients efficiently across the entire dataset with a few lines of NumPy code, avoiding slow Python loops. The key formulas are and .
Preview of the Next Lesson:
You are now fully equipped! You have the sigmoid function to make predictions and the vectorized gradient of the loss function to guide the learning process. In the next lesson, you will put all the pieces together and implement a complete binary logistic regression model from scratch using your gradient descent optimizer.