Boss lesson · Unit 03
From scores to probabilities
Softmax, logs and the cross-entropy loss
What you practise
- Softmax turns scores into a distribution, logs turn products into sums, maximum likelihood, cross-entropy as the price of a wrong belief
Try a question from this lesson
Pick one
A model scores three answers: cat 2, dog 1, eel -1. You need probabilities: positive numbers that sum to 1. Why not just divide each score by the total?
Hint
Try it: the total is 2, so what "probability" would eel get?
Correct answer
A score can be negative, and the total can be zero
Why
Eel would get -1/2, and a probability cannot be negative. Scores like [1, -1] would even divide by zero. The scores must be made positive first, without changing their order.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Softmax
Softmax turns any scores into a distribution in two steps.
First raise e (about 2.718) to the power of each score: np.exp. The result is always positive, and bigger scores stay bigger.
Then divide by the total so everything sums to 1.
The raw scores a model produces before softmax are called logits.
import numpy as np
z = np.array([2.0, 1.0, -1.0])
e = np.exp(z)
p = e / e.sum()
print(p.round(2)) # [0.71 0.26 0.04]Concept
Logarithms
The logarithm undoes the exponential: np.log(np.exp(3)) is 3. So log(1) = 0, and the log of a probability (a number below 1) is negative.
Its most useful property: the log of a product is the sum of the logs. Multiplying many probabilities becomes adding many logs.
import numpy as np
print(np.log(1.0)) # 0.0
print(np.log(np.exp(3.0))) # 3.0
a = np.log(0.5 * 0.2)
b = np.log(0.5) + np.log(0.2)
print(np.isclose(a, b)) # TrueConcept
Cross-entropy
How wrong is a predicted distribution? Look at the probability p it gave to the answer that turned out to be true, and take minus its log.
Confident and right: p near 1, loss near 0. Unsure: a moderate loss. Confident and wrong: p near 0, and the loss shoots up.
This loss is called cross-entropy. Almost every classifier and language model is trained with it.
import numpy as np
for p in [0.99, 0.5, 0.01]:
print(p, round(-np.log(p), 2))
# 0.99 0.01
# 0.5 0.69
# 0.01 4.619 more exercises in the app
- 2× type the answer
- 4× multiple choice
- 1× fill the blanks
- 1× order the lines
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.