Sub topic 7
Log loss as the training objective
This chapter assumes you know the sigmoid model from earlier chapters, where p = σ(w·x + b). It also assumes you are comfortable with logarithms and with NumPy. You should also know that a loss function turns "how wrong is the model" into one number that training minimizes.
What the loss must do
The model outputs a probability p for each example. The label y is either 0 or 1. A good loss for this setting should:
- Be small when p is close to the true label and large when it is far away.
- Punish confident wrong answers much more than hesitant ones.
- Be smooth, so gradient descent can follow it.
- Ideally have a single minimum, so training does not depend on where it starts.
Log loss, also called binary cross-entropy or negative log-likelihood, meets all four.
From likelihood to loss
For one example, the model assigns probability p to the label 1 and 1 − p to the label 0. Both cases fit into one expression:
P(y | x) = p^y · (1 − p)^(1 − y)If y = 1, the second factor becomes 1 and the result is p. If y = 0, the first factor becomes 1 and the result is 1 − p.
Assuming the examples are independent, the likelihood of the whole dataset is the product of these terms. Maximum likelihood picks the weights that make this product as large as possible. Products of many small numbers underflow, so we take the logarithm. The log is increasing, so it has the same maximizer. We then negate it and average, so the result is a loss to minimize:
L(w, b) = −(1/n) Σ [ yᵢ·log(pᵢ) + (1 − yᵢ)·log(1 − pᵢ) ]Only one of the two terms is active for each example. For y = 1 the loss is −log(p). For y = 0 it is −log(1 − p).
What the penalty looks like
The chart shows the loss for an example whose true label is 1. As p falls toward 0, the loss grows without bound.
| Predicted p for a true y = 1 | Loss −ln(p) |
|---|---|
| 0.9 | 0.105 |
| 0.5 | 0.693 |
| 0.1 | 2.303 |
| 0.01 | 4.605 |
| 0.001 | 6.908 |
Always predicting 0.5 gives a loss of ln 2 ≈ 0.693 on any dataset. That makes 0.693 a useful baseline. A trained model with a loss above it is worse than ignoring the features.
Computing it in NumPy
import numpy as np
from sklearn.metrics import log_loss
def log_loss_np(y, p, eps=1e-15):
p = np.clip(p, eps, 1 - eps)
return -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))
y = np.array([1, 0, 1, 1, 0])
p = np.array([0.9, 0.2, 0.6, 0.3, 0.05])
print(log_loss_np(y, p))
print(log_loss(y, p))Both lines print about 0.4189. The per-example losses are 0.105, 0.223, 0.511, 1.204 and 0.051. The fourth example, a positive scored 0.3, contributes more than half of the total. A few confident mistakes dominate the average.
Numerical edge cases
If p is exactly 0 or 1, the code takes log(0) and gets −inf, and the loss becomes inf or nan. The clip call keeps p inside (ε, 1 − ε). With ε = 1e-15 the largest possible per-example loss is about 34.5.
Clipping fixes the output, but it does not fix the cause. Computing σ(z) first can already round to exactly 1.0 for large z. A safer approach computes the loss directly from the score z = w·x + b:
import numpy as np
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
def log_loss_from_logits(y, z):
return np.mean(np.logaddexp(0.0, z) - y * z)
y = np.array([1, 0, 1, 1, 0])
z = np.array([2.0, -1.0, 0.5, -0.7, 3.0])
p = sigmoid(z)
direct = -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))
print(direct, log_loss_from_logits(y, z))The two numbers match. The identity used is −log σ(z) = log(1 + e^(−z)) = logaddexp(0, z) − z for y = 1, and −log(1 − σ(z)) = logaddexp(0, z) for y = 0. logaddexp never overflows, so this form stays finite for any score. Deep learning libraries use the same trick under names like "BCE with logits".
Why not squared error?
You could plug the sigmoid output into mean squared error. Two things go wrong.
- Weak gradients when the model is confidently wrong. The squared-error gradient contains the factor p(1 − p), which is near zero when p is near 0 or 1. A badly wrong, saturated prediction barely moves the weights. For log loss, the gradient with respect to the score z is simply p − y. It is large exactly when the error is large.
- Loss shape. Squared error composed with a sigmoid is not convex in the weights. Log loss is convex in w and b, so gradient descent with a suitable step size reaches the global minimum.
Squared error also caps the penalty for a confident mistake at 1. Log loss does not. This is the property you want when a wrong answer given with high confidence is the costly outcome.
Common mistakes
- Passing hard labels.
log_loss(y, model.predict(X))gives clipped 0/1 predictions, so every error costs about 34.5. Passpredict_proba(X)[:, 1]. - Summing instead of averaging. A sum grows with n, so the same learning rate behaves differently on different dataset sizes. The gradient code in this tutorial divides by n.
- Mixing logarithm bases. Natural log is the convention. Base 2 gives the same minimizer, but the values differ by a constant factor and will not match library output.
- Reading the loss as a percentage. A log loss of 0.3 is not "70% correct". It measures probability quality, not label accuracy.
- Comparing losses across datasets. The 0.693 baseline holds for balanced predictions only. On a dataset with 5% positives, a constant prediction of 0.05 scores a loss of about 0.199, and that is the baseline to beat.
- Ignoring the penalty term. With regularization, the training objective is log loss plus a penalty. The log loss you report on test data should not include the penalty.
Exercise
A model predicts p = 0.25 for an example whose true label is y = 1, and p = 0.25 for another example whose true label is y = 0. What is the loss for each example, and what is the mean log loss of the pair?
Show answer
For y = 1 the loss is −ln(0.25) = ln 4 ≈ 1.386. For y = 0 the loss is −ln(1 − 0.25) = −ln(0.75) ≈ 0.288. The mean is (1.386 + 0.288) / 2 ≈ 0.837, which is worse than the 0.693 baseline of always predicting 0.5.
Exercise
Why does log_loss_from_logits stay finite for z = 800, while computing sigmoid(z) and then np.log(1 - p) fails?
Show answer
For z = 800, np.exp(-800) underflows to 0 and sigmoid(800) rounds to exactly 1.0, so 1 − p is 0 and log(0) gives −inf. The logit form uses logaddexp(0, z), which computes log(1 + e^z) without ever forming e^z, so it returns about 800 with no overflow or underflow.