Linear models · lesson 10 of 12
Parts in this lesson
Anp.where(y == 1, p, 1 - p)the probability given to what happened
B-np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))binary cross-entropy
CX.T @ (p - y) / nits gradient
D-np.logaddexp(0, -z)log σ(z), safely

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 (yˆ−y)x, 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 pi 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 pi; for one labelled 0 it said 1−pi. If the examples are independent (lesson 1.9), the probability of all the labels together is the product:

likelihood=∏i=1npiyi(1−pi)1−yi

The powers are a trick to write both cases at once: when yi=1 the second factor is (1−pi)0=1, and when yi=0 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.

likelihood.ipynb

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 n to get a mean. That's the loss:

ℒ=−1n∑i=1n[yilog⁡pi+(1−yi)log⁡(1−pi)]

This is binary cross-entropy, lesson 1.11's cross-entropy between the labels and the model's probabilities. Each example's term is −log⁡ of the probability the model gave the truth: its surprise.

likelihood.ipynb

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:

Surprise barseach penguin's loss: −log(probability of the truth)
024632.1A136.4A137.9A139.6A140.9C0.0241.1A0.9845.9C0.7146A0.2748.1C0.9650.2C0.9951.4C158C1mmp(truth)

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 p=σ(z) and z=w⋅x+b, use lesson 1.7's sigmoid derivative, σ′(z)=p(1−p):

∂ℒ∂z=−[yp−1−y1−p]p(1−p)=−[y(1−p)−(1−y)p]=p−y.

The p(1−p) cancels completely. Then ∂z/∂wj=xj and ∂z/∂b=1, so

∂ℒ∂w=(p−y)x,∂ℒ∂b=p−y,

averaged over the examples. That's the same form as linear regression's gradient, with yˆ=p: error times input. And it's why lesson 3.9's squared error failed. With squared error, the p(1−p) stays in the gradient, and it's nearly 0 when the model is confidently wrong. With cross-entropy it cancels, so the push is p−y: biggest exactly when the model is most wrong.

Check it, as always:

gradient.ipynb

Train it in NumPy

Lesson 3.9's bad start (w=−8), now trained on cross-entropy:

crossentropy.ipynb

By step 500 it has turned w 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:

crossentropy.ipynb

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 z:

stable.ipynb

At z=−800, np.exp(800) overflows to infinity, so σ(z) comes out as exactly 0, and log⁡0 is -inf. One such example makes the whole loss infinite, and its gradient nan. And large z happens exactly when a model is confidently wrong, which is when the loss matters most.

The fix is to never compute σ(z) and then take its log. Algebra gives log⁡σ(z)=−log⁡(1+e−z), and NumPy's logaddexp(a, b) computes log⁡(ea+eb) without overflowing:

stable.ipynb

The right answer, −800, every time. Libraries do this for you: scikit-learn internally, and PyTorch's loss functions take the raw z 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): yi=yˆi+εi. The normal distribution's density has e−(yi−yˆi)2/2σ2 in it, so the log-likelihood of all the labels is a constant minus

12σ2∑i=1n(yi−yˆi)2.

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

A model gives probability 0.2 to an example whose true label is 0. What’s that example’s binary cross-entropy?
Predict, then check with the surprise bars: which kind of penguin makes the tallest bar?
Why does cross-entropy train logistic regression better than squared error?

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.

All sources for Simple Machine Learning