Imagine a farmer who has just spread his harvested rice on the ground to dry. It takes a full day in the sun. If rain comes, the whole batch can be ruined.
He checks a weather app. Two different apps give him two different answers.
App A says: "60% chance of rain." App B says: "1% chance of rain. I am almost completely sure."
The next day, it pours.
Both apps were wrong. But which one was more wrong? Most of us feel the answer right away. App B. It was not just wrong, it was confident while being wrong. That confidence is what cost the farmer his rice.
Hold on to that feeling. It is exactly what this post is about. Because the cost function we have used since the third post of this series does not feel that difference. And that quietly breaks everything once we use it on yes or no problems.
Two Posts of Hand-Picked Weights
In the last two posts, I picked the weights for you. First w = 2 and b = -11. Then w1 = 1, w2 = -1.5 and b = -10. That was fine to show how the model works. But a real model has to find its own weights.
So the natural next step is to do what we always do. Take the cost function from post three, squared error, and let gradient descent walk downhill. Let's see what really happens.
A New Problem: Will It Rain?
Let's build a small example. Eight days. For each day, we have a cloud darkness score from 1 (clear sky) to 8 (very dark). And we know if it rained that day, 1 for yes and 0 for no.
| Cloud Darkness | Rained? |
|---|---|
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 1 |
| 6 | 1 |
| 7 | 1 |
| 8 | 1 |
The model is the same logistic regression from before: probability of rain = sigmoid(w × darkness + b).
Squared Error Cannot Feel Confidence
Let's go back to our two weather apps and put actual numbers on how much each one should be punished. The real answer is "no rain" here, so y = 0, and we look at what each prediction costs us.
| Predicted chance of rain | Squared error | Log-loss |
|---|---|---|
| 0.60 | 0.36 | 0.92 |
| 0.90 | 0.81 | 2.30 |
| 0.99 | 0.98 | 4.61 |
| 0.99999 | 0.99998 | 11.51 |
Look at the squared error column. It starts at 0.36, climbs to 0.81, then 0.98, and then it basically stops. It can never go above 1. Going from "99% sure" to "99.999% sure" of the wrong answer barely changes the punishment at all. Squared error treats a confident wrong answer almost the same as a regular wrong answer.
Now look at the log-loss column. The more confident the wrong answer, the faster the punishment grows. 0.92, then 2.30, then 4.61, then 11.51. It keeps climbing with no ceiling. This is the cost function that feels what our farmer felt.
Here is how log-loss is calculated for one example:
- If the real answer is 1: loss = -log(predicted probability)
- If the real answer is 0: loss = -log(1 - predicted probability)
Let's check the 0.99 row by hand. The real answer is 0, so loss = -log(1 - 0.99) = -log(0.01) = 4.61. That matches the table.
This is the picture to remember. In both panels, the orange squared error line stays low and gentle. The blue log-loss line shoots straight up as the prediction moves toward the wrong end. The model is being told, very loudly, "do not be sure and wrong."
The Real Problem: Gradients That Go Quiet
Being punished too lightly is not even the worst part. The worse part is what happens inside gradient descent.
Remember from the sigmoid post that its rate of change is g(z) × (1 - g(z)). When the sigmoid is very sure, close to 0 or close to 1, that number gets tiny. When we use squared error on top of a sigmoid, this tiny number gets multiplied into the slope. So exactly when the model is confidently wrong, the slope almost disappears, and gradient descent barely moves.
Let's see this with numbers. Say a model computes z = -8 for a day that did rain. The predicted chance of rain is only 0.00034. Very confident, and very wrong. How strong is the push to fix it?
- With squared error, the slope on z is -0.00034
- With log-loss, the slope on z is -0.99966
That is a difference of almost 3,000 times. Squared error whispers. Log-loss shouts. And the model needs the shout, because this is exactly the situation where it has the most to learn.
For log-loss, the slope turns out to be just (prediction - actual). Nothing extra gets multiplied in to make it fade away. That is the clean property that makes log-loss the right partner for the sigmoid.
Watching It Fail, For Real
Let's run both cost functions on our rain data. To make this fair, we use the same starting point and the same learning rate for both. We start at w = -3 and b = 10. That is a bad start on purpose. It says "darker clouds mean less rain," which is the opposite of the truth. A real model can start somewhere bad, so this is a fair test.
Here is where each one ends up after 10,000 steps of gradient descent:
| Cost function | Final w | Final b | Final cost (by its own formula) |
|---|---|---|---|
| Squared error | -8.53 | 5.74 | 0.2502 |
| Log-loss | 3.13 | -13.96 | 0.0501 |
The two cost numbers use different formulas, so do not compare them directly. The weights tell the real story.
Squared error ended with w = -8.53. Still negative. It went deeper into the wrong idea. If you let it run for 200,000 steps, it barely changes, still around 0.25. It slid onto a big flat patch and stayed there. At that spot, the model says "no rain" for almost every day, which is right only half the time.
Log-loss ended with w = 3.13, a positive weight, which says darker clouds mean more rain. That is correct. It found its way out of the bad start.
This picture shows why. On the left, the squared error surface has a huge flat patch. Gradient descent starts near the top, slides left, and stops there, because the ground is flat and there is no slope to follow. On the right, log-loss has a clear slope that leads from the start all the way down to the bottom.
I want to be honest about one thing. Squared error does not always fail. If we start from w = 0 and b = 0, it finds a decent answer. The danger is that it works on some starting points and silently fails on others, and you have no way of knowing which one you got. A cost function that depends on luck is not one we can trust.
Putting It All Together: The Cost Over the Whole Dataset
For one example, the loss is what we saw above. For the whole dataset, we just average it over all m examples, the same way we did in post three.
cost = -(1/m) × sum of [ y × log(prediction) + (1 - y) × log(1 - prediction) ]
This single line is the same two cases from before, squeezed into one formula. If y = 1, the second part disappears and we are left with -log(prediction). If y = 0, the first part disappears and we are left with -log(1 - prediction).
Let's check it on a tiny example, two days. Day one, it rained (y = 1) and the model said 0.9. Day two, it did not rain (y = 0) and the model said 0.2.
- Day one loss: -log(0.9) = 0.105
- Day two loss: -log(1 - 0.2) = -log(0.8) = 0.223
- Average: (0.105 + 0.223) / 2 = 0.164
Turning This Into Code
Here is log-loss, first for one example, then for the whole dataset.
import numpy as np
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def log_loss_one(prediction, actual):
if actual == 1:
return -np.log(prediction)
return -np.log(1 - prediction)
def log_loss(predictions, actual):
m = len(actual)
total = 0
for i in range(m):
total += log_loss_one(predictions[i], actual[i])
return total / m
# the two-day example from above
print(log_loss(np.array([0.9, 0.2]), np.array([1, 0]))) # 0.1643
And the vectorized version, which does the same thing without a loop.
def log_loss_vectorized(predictions, actual):
return -np.mean(actual * np.log(predictions) + (1 - actual) * np.log(1 - predictions))
print(log_loss_vectorized(np.array([0.9, 0.2]), np.array([1, 0]))) # 0.1643
Now the experiment itself. We write the slope for each cost function, and run the exact same loop on both.
darkness = np.array([1, 2, 3, 4, 5, 6, 7, 8], dtype=float)
rained = np.array([0, 0, 0, 0, 1, 1, 1, 1], dtype=float)
def slopes_squared_error(w, b):
p = sigmoid(w * darkness + b)
d = (p - rained) * p * (1 - p) # the tiny p(1-p) factor
return np.mean(d * darkness), np.mean(d)
def slopes_log_loss(w, b):
p = sigmoid(w * darkness + b)
d = p - rained # just prediction minus actual
return np.mean(d * darkness), np.mean(d)
def run(slopes, w, b, learning_rate, steps):
for _ in range(steps):
slope_w, slope_b = slopes(w, b)
w = w - learning_rate * slope_w
b = b - learning_rate * slope_b
return w, b
print(run(slopes_squared_error, -3.0, 10.0, 0.1, 10000)) # (-8.53, 5.74)
print(run(slopes_log_loss, -3.0, 10.0, 0.1, 10000)) # (3.13, -13.96)
Look at the one line that differs. In slopes_squared_error, there is an extra * p * (1 - p). That small piece is the whole story. It is the part that goes quiet when the model is confident.
Where We Go From Here
We have fixed the missing piece. We now have a way to measure how wrong a probability is, one that punishes confident mistakes hard, and gives gradient descent a clear slope to follow. And the slope turned out to be beautifully simple, just prediction minus actual, the same shape as the linear regression slope from post four.
That means we are finally ready to stop picking weights by hand. Next time, we put everything together: the sigmoid, the weighted sum, and log-loss, and let the machine find its own w and b, from nothing but data, with code built from scratch.
The full notebook for this post is up on GitHub here: github.com/tharun-pandya/Machine-Learning-Blog-Series/blob/main/Log_Loss.ipynb
See you in the next one.
Comments
Join the discussionNo comments yet. Be the first to comment.



