Sub topic 7
Log loss as the training objective
This chapter assumes you know the sigmoid model, which maps a linear score to a probability p. It also assumes you have seen the idea of a loss function and the basics of maximum likelihood.
From likelihood to loss
For one example with label y (0 or 1) and predicted probability p of the positive class, the model's probability of the observed label is:
pify = 11 - pify = 0
Both cases fit one expression: p^y × (1 - p)^(1 - y). Maximum likelihood picks the weights that make the product of these terms over all examples as large as possible.
Products of many small numbers underflow, and they are awkward to differentiate. Taking the logarithm turns the product into a sum without moving the maximum. Optimizers minimize, so we negate the result and average over n examples:
L = -(1/n) Σ [ y·log(p) + (1 - y)·log(1 - p) ]
This is log loss, also called binary cross-entropy. Minimizing it is the same as maximizing the likelihood.
What the loss rewards and punishes
Only one of the two terms is active for each example. For y = 1 the loss is -log(p). The loss grows without bound as p approaches 0, so confident wrong predictions are punished heavily.
| Label | Predicted p | Loss |
|---|---|---|
| 1 | 0.90 | 0.105 |
| 1 | 0.50 | 0.693 |
| 1 | 0.10 | 2.303 |
| 1 | 0.01 | 4.605 |
A model that always outputs 0.5 scores log(2) ≈ 0.693. This makes a useful baseline: a trained model with a higher loss is worse than a constant guess.
Computing it
import numpy as np
def log_loss(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, 0])
p = np.array([0.9, 0.2, 0.6, 0.01])
print(log_loss(y, p))This prints about 0.212. The np.clip call keeps p away from exactly 0 and 1, where log(0) would give -inf.
Why not squared error
Squared error on sigmoid outputs gives a non-convex loss in the weights, with flat regions where gradients vanish. Log loss is convex for logistic regression, so gradient descent reaches the global minimum. Its gradient also simplifies to Xᵀ(p − y)/n, which the next chapters use.
Common errors
- Passing hard 0/1 predictions instead of probabilities. One wrong label then gives an infinite loss, or a huge one after clipping.
- Mixing up the label order.
pmust be the probability of the class coded as 1. - Reading log loss like accuracy. A lower value means better probabilities, not necessarily more correct labels.
- Using
logof the wrong base when comparing results. Natural log is the usual choice.
Exercise
A single example has label y = 1 and the model predicts p = 0.25. What is its log loss, and is it better or worse than the constant-0.5 baseline of 0.693?
Show answer
The loss is -ln(0.25) ≈ 1.386. It is worse than the baseline, because the model puts only 0.25 probability on the correct class.