Lesson 3 of 187 min
Softmax and cross-entropy
Softmax turns a network's scores into chances by raising e to each score and dividing by the total, and the loss is the surprise at the right answer: about 2.30 for ten digits before any training.
After this lesson you can turn scores into probabilities and score a prediction.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Softmax, written out
Softmax takes e to the power of each score, then divides each one by their total. Here it is by hand on the ten scores from the video, next to PyTorch's own. Both give the 3 the same chance.
import math
import torch
scores = [-5.9955, -6.0224, -2.0095, 5.6967, -13.4465, -0.5556, -11.7653, -2.8065, -2.9994, 1.8685]
e = [math.exp(s) for s in scores]
total = sum(e)
print(round(total, 1))
print(round(e[3] / total, 4))
print(torch.softmax(torch.tensor(scores), dim=0)[3])305.2 0.9761 tensor(0.9761)
Why the loss takes scores
When one score is far above the others, the small chance rounds to exactly zero, and its log is minus infinity. F.cross_entropy never makes the chances first. It works out the log of softmax in one step (F.log_softmax), so the loss stays a real number.
import torch.nn.functional as F
far = torch.tensor([[0.0, 120.0]])
probs = torch.softmax(far, dim=1)
print(probs)
print(-torch.log(probs[0, 0]))
print(F.cross_entropy(far, torch.tensor([0])))tensor([[0., 1.]]) tensor(inf) tensor(120.)
Two kinds with one score
With only two answers, a network often gives one score. The S-curve of that score is softmax over two scores, with the second held at zero. So F.binary_cross_entropy_with_logits gives the same loss as F.cross_entropy on the two scores.
s = torch.tensor([1.5])
print(torch.sigmoid(s))
print(torch.softmax(torch.tensor([1.5, 0.0]), dim=0))
print(F.binary_cross_entropy_with_logits(s, torch.tensor([1.0])))
print(F.cross_entropy(torch.tensor([[1.5, 0.0]]), torch.tensor([0])))tensor([0.8176]) tensor([0.8176, 0.1824]) tensor(0.2014) tensor(0.2014)
A loss that stops at sure
label_smoothing=0.1 tells the loss that the right digit should get a little less than 100%, with the rest shared by the other digits. A network that is already sure gets a larger loss, so it stops pushing its scores further apart. You will see it in the training code of large models.
x = torch.tensor([scores])
y = torch.tensor([3])
print(F.cross_entropy(x, y))
print(F.cross_entropy(x, y, label_smoothing=0.1))tensor(0.0242) tensor(0.9742)
Run on Python 3.13.3 and PyTorch 2.15.0. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Cross-entropy and KL divergence
Two models guess the next word, and both guess wrong. Model X gave the word that came a chance of 0.01: it was sure of another word. Model Y gave it 0.25. Which pays more?
2 of 3
Before training, F.cross_entropy(model(x), y) prints 2.33 on the digits. After training, the loss stops at about 1.5 and won't go lower. What is the likely bug?
3 of 3
A network gives three scores: 2, 0 and −1. Raised as powers of e, they become about 7.39, 1 and 0.37. What chance does softmax give the first answer, in percent?
The ideas in this lesson
- Scores (logits)
- A network's last layer gives one score for each answer: any size, above or below zero, not yet chances.
- Softmax
- Raise e to the power of each score, then divide by their total: chances between 0 and 1 that add to 1.
- The loss, and where it starts
- The loss is the surprise at the right answer's chance; before training the chances are even, so it starts near 2.30 for ten.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Softmax and cross-entropy
Here's a puzzle. A network reads a picture of a three. It gives ten scores, one for each possible answer. Some of the scores are below zero. How do you turn them into chances?
Keep your guess
Hold on to your guess. Here are the ten scores.
Scores
The digits network reads a picture of a handwritten digit: sixty-four pixels, then a hidden layer of thirty-two. It ends in ten neurons with no bend, no activation function. So each one's number comes out as it is.
Those ten numbers are the scores.
This picture is a three, so three is the right digit. Its score is five point seven. The nine gets almost two, and the four gets about minus thirteen.
The largest score is the network's answer. But does five point seven mean it's sure?
A score alone doesn't tell you. PyTorch calls these scores logits.
Dividing breaks
Chances are between zero and one, and they add up to one. Was your guess to divide each score by their total? Here, the ten scores add up to minus thirty-eight. Spot the problem.
The three, the network's own answer, gets minus fifteen percent. And the four, its lowest score, gets thirty-five percent. As soon as a score is below zero, dividing by the total breaks.
e to the power of each score
A network ends in scores, one for each answer, of any size, above or below zero.
So how do they become chances?
First, make each one above zero, and keep their order.
Take e, a number about two point seven two.
Raise it to the power of each score.
A score of zero gives one.
Each one you add multiplies it by about two point seven.
Each one you take away divides it by the same.
So even minus thirteen gives a tiny number above zero.
A larger score still gives a larger number.
The three now has almost three hundred. The nine has six point five. The other eight are all under one.
Divide by their total: softmax
Then divide each one by their total, three hundred and five.
What chance does the three get?
Split it between the two scores above zero, the three's and the nine's. That would give it seventy-five percent.
Ninety-seven point six percent. Ten chances, each between zero and one, that add up to one. The largest score keeps the largest chance, and the gaps grow.
Those two steps... are called softmax.
The same step in a chatbot
A chatbot does the same thing at its last step. Its model gives one score for every word, or piece of a word, that it knows. How many scores is that? A thousand?
Two hundred and forty-eight thousand. Softmax turns them into the chances of the next word. After "Penguins live in the", the word Antarctic gets forty-one percent.
The surprise at the right digit
Softmax turns a network's scores into chances.
So how good were those chances? Training needs one number for how wrong they were. Look up the chance it gave the right digit, and take its surprise, as in the Probability course: minus its log.
It's small when the network was sure and right, and large when it was sure and wrong. Do that for every picture and take the average: that's the cross-entropy, the loss the network learns from. PyTorch measures it in nats, not bits. For our three, at almost ninety-eight percent, the loss is tiny: about zero point zero two.
The loss at the start
And before any training? The network hasn't learned anything yet. What chance will it give the right digit?
About one in ten. Before training, the scores are all close to zero, so the chances are close to one in ten each. And a chance of one in ten has a loss of two point three. Averaged over all the pictures the network learns from, it's just above two point three. So a first loss far from two point three means something is wrong, before learning even starts.
Softmax twice
What goes wrong in real code?
PyTorch's cross-entropy takes the scores and applies softmax itself. Put softmax at the end of your model too, and it runs twice. The chances are all between zero and one. So the second softmax gets scores that are never more than one apart. Adding one to a score only makes it two point seven times as big. So no digit gets more than twenty-three percent. And the loss never gets below about one and a half. It starts near two point three, like the right code, so the start can't show it. The end does: the right code falls to zero point one two. This one stops at one point five.
In code
In PyTorch, the network gives its scores. Softmax turns each picture's ten scores into chances, and they add up to one. The cross-entropy takes the scores, not the chances, and the right digit. It gives minus the log of the right digit's chance. That's about zero point zero two, the same as working it out from the chances. And before training, what will the loss print?
Just above two point three, right next to the log of ten.
Give the loss the scores, and only use softmax to read the chances.
Three ideas
So, a network ends in scores. Softmax raises e to the power of each one, then divides by their total. The chances add up to one. The loss is the surprise at the right answer. For ten digits, it starts at about two point three.
The lab
That's the end of this unit. In the lab, you use these three lessons to build the digits network, and check its loss before it learns.
Scores into chances
Softmax turns scores into chances that add up to one. Now try it on this lesson's page, and take the quiz. Add the same number to every score, and watch the chances.
You use this lesson in Lab 1: A digit reader, part by part, which comes next.
Facts last checked on .
