Lesson 6.3 · 10 min read · about 1 h to master at a very slow pace
Softmax and Cross-entropy
Softmax turns class scores into probabilities; cross-entropy scores those probabilities. A worked example, the numerical-stability trick, and the derivation of the famously simple gradient: predicted minus target.
Softmax: scores to probabilities
The last layer of a -class classifier produces raw scores , called logits. Softmax turns them into probabilities:
Every is positive and they sum to 1. The target is one-hot: 1 for the correct class, 0 for the rest.
Cross-entropy
With a one-hot target only one term survives: .
Worked example
Logits for classes A, B, C; the correct class is A.
- , , ; sum .
- Softmax: .
- Loss: .
- Gradient (below): . It pushes A's score up and the others down.
For comparison, a probability of 0.5 on the correct class costs , 0.95 costs , and 0.01 costs . Confident mistakes are punished hard.
Deriving the gradient
First the softmax derivative. For : ; for : . Both cases: . Then:
using . So
Predicted probability minus target. The softmax derivative is already folded in; there is no extra activation-derivative factor. Sigmoid with binary cross-entropy gives the same result, .
Numerical stability
overflows for large logits. Subtract the largest logit first: . The common factor cancels, so the probabilities are unchanged: and give the same softmax.
Stuck? Common doubts
Questions real learners asked while studying this lesson. They stay closed so they don't spoil your own thinking: open only the ones you need.
First passWhy is cross-entropy better than MSE for classification?
Two reasons. It punishes confident wrong answers heavily (), and with a softmax or sigmoid output its gradient is simply , so it doesn't vanish when the output unit saturates. MSE through a sigmoid has an extra factor that goes to zero exactly when the model is confidently wrong.
Going deeperWhere did the go in the derivation?
, and the softmax derivative contributes a factor , so they cancel. That cancellation is why the softmax–cross-entropy pair is so convenient, and why frameworks compute them together.
Cheatsheet
Softmax and cross-entropy
Stable softmax
Check your understanding
Score 75% or more to master this lesson and earn XP. Answer first, then check.