Cross-entropy and maximum likelihood
Last updated
Lesson 3.9 left logistic regression without a good loss: squared error stalls. The right loss comes from a simple idea: choose the weights under which the labels you actually saw were most likely. Take its log and you get binary cross-entropy, whose gradient is as simple as a gradient can be. This lesson derives it, trains logistic regression with it in NumPy, and shows the one numerical trap in computing it.
By the end of this lesson you can
- Write the likelihood of a set of labels, and turn it into binary cross-entropy
- Derive the gradient , and check it numerically
- Train logistic regression in NumPy, and match scikit-learn
- Compute log-probabilities without getting -inf
The likelihood of the labels
A logistic model gives each example a probability that its label is 1. Look at the labels you actually have, and ask: how likely were they, according to the model? For an example labelled 1 the model said ; for one labelled 0 it said . If the examples are independent (lesson 1.9), the probability of all the labels together is the product:
The powers are a trick to write both cases at once: when the second factor is , and when the first one is. Maximum likelihood (lesson 1.10) means choosing the weights that make this as big as possible: the model that was least surprised by the data.
The model gave the four true labels probabilities 0.9, 0.8, 0.6 and 0.99, so the likelihood is their product, 0.4277. With thousands of examples, a product of thousands of numbers below 1 underflows to 0 (lesson 1.11), so everyone works with its log instead: here −0.8494.
Taking the log: binary cross-entropy
The log turns the product into a sum. Making the log-likelihood as big as possible is the same as making its negative as small as possible, so take the negative, and divide by to get a mean. That's the loss:
This is binary cross-entropy, lesson 1.11's cross-entropy between the labels and the model's probabilities. Each example's term is of the probability the model gave the truth: its surprise.
The last cell is the important one. A true label of 1, given probability 0.99, costs 0.01; given 0.5, 0.693; given 0.01, a confident wrong answer, 4.605. Cross-entropy punishes confident mistakes hard, and the cost has no ceiling: as the probability for the truth goes to 0, the loss goes to infinity. Every penguin's surprise, as a bar:
Binary cross-entropy, the mean bar: 0.487. The tallest bar is a Chinstrap with a 40.9 mm bill, given only 0.016 for its true species: loss 4.12. Solid bars are wrong answers (under 0.5 for the truth).
Its gradient is (ŷ − y)x
Now the gradient, by the chain rule (lesson 1.7). For one example with and , use lesson 1.7's sigmoid derivative, :
The cancels completely. Then and , so
averaged over the examples. That's the same form as linear regression's gradient, with : error times input. And it's why lesson 3.9's squared error failed. With squared error, the stays in the gradient, and it's nearly 0 when the model is confidently wrong. With cross-entropy it cancels, so the push is : biggest exactly when the model is most wrong.
Check it, as always:
Train it in NumPy
Lesson 3.9's bad start (), now trained on cross-entropy:
By step 500 it has turned round from −8 to 3.61 and reached 0.879, the same accuracy as LogisticRegression with this one feature. Squared error, from the same start, was still stuck at 0.627 after 2,000 steps.
With all 30 measurements, standardised with the training set's means and spreads, and lesson 3.4's vectorised gradient:
Your 15 lines of NumPy score 0.953 on the test tumours, exactly what scikit-learn's LogisticRegression scores. scikit-learn uses a cleverer optimiser and adds a small ridge penalty (lesson 3.8) by default, but the model and the loss are the ones you just wrote.
Wrong way: log(σ(z)) gives -inf
Computing the loss as written, np.log(sigmoid(z)), breaks for large negative :
At , np.exp(800) overflows to infinity, so comes out as exactly 0, and is -inf. One such example makes the whole loss infinite, and its gradient nan. And large happens exactly when a model is confidently wrong, which is when the loss matters most.
The fix is to never compute and then take its log. Algebra gives , and NumPy's logaddexp(a, b) computes without overflowing:
The right answer, −800, every time. Libraries do this for you: scikit-learn internally, and PyTorch's loss functions take the raw values (called logits) for exactly this reason. From Stage 7, in PyTorch, you’ll pass logits to the loss, never probabilities.
Squared error is a likelihood too
Maximum likelihood also explains lesson 3.1's squared error. Suppose each label is the line's prediction plus random noise from a normal distribution (lesson 1.10): . The normal distribution's density has in it, so the log-likelihood of all the labels is a constant minus
Maximising it means minimising the sum of squared errors. So squared error is maximum likelihood for numbers with normal noise, and cross-entropy is maximum likelihood for yes-or-no labels. Choosing a loss is choosing what you believe about the noise in your labels.
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- Goodfellow, Bengio and Courville, Deep Learning, chapter 5: Machine Learning Basics: maximum likelihood estimation, and why squared error is maximum likelihood under Gaussian noise (5.5)
- Goodfellow, Bengio and Courville, Deep Learning, chapter 6: Deep Feedforward Networks: why a sigmoid output should be trained with cross-entropy, not squared error (6.2.2)
- NumPy: numpy.logaddexp: log(eˣ + eʸ) without overflow