Logarithms, entropy, cross-entropy and KL divergence
AI classifiers and language models learn by making a loss called "cross-entropy" smaller. The idea behind it is surprise. When something you did not expect happens, you are very surprised. The logarithm is the tool that turns that surprise into a number. Move the probabilities and see for yourself.
Short answer. The less you expected something, the bigger the surprise when it happens, and we measure it as −log(probability). Entropy is the average surprise: how hard the outcome is to predict. Cross-entropy is the average surprise when you look at reality through your own prediction. It is the loss used to train AI classifiers and language models. KL divergence is the gap between the two: how far the prediction is from reality.
Click or drag sideways on the picture to change the probability p. The green bar at the bottom is p, and the black curve is the surprise −log₂ p. The purple staircase shows that each time p is cut in half (across), the surprise grows by 1 bit (up).
Definitions
The text below explains with bars and areas. The textbook definitions are as follows. p = (p₁, …, pₙ) and q = (q₁, …, qₙ) are probability distributions over the same n outcomes (pᵢ ≥ 0 and qᵢ ≥ 0 for every i, and each adds up to 1). The base of log is 2 (unit: bit) or e (unit: nat, ), and one formula uses one base throughout. The hand calculations on this page use base 2, and the AI loss in section 9 uses the natural log. By convention .
- self-information
- The information of an event with probability p > 0 when it happens. It is the "surprise" in the text. With base 2 it grows by 1 bit each time the probability halves.
- entropy
- The expected self-information of an outcome that follows the distribution p. It is 0 or more, and it is largest, log n, when all n outcomes are equally likely.
- cross-entropy
- The expected information measured with q when the outcomes really follow p. If some i has pᵢ > 0 but qᵢ = 0, it is ∞.
- Kullback-Leibler divergence
- The cross-entropy minus the entropy. It is always 0 or more, and 0 only when p = q (Gibbs' inequality). Usually KL(p‖q) ≠ KL(q‖p), so it is not a distance.
- one-hot label, cross-entropy loss
- When the right class is c, the answer distribution is the one-hot vector y with and for the rest. The cross-entropy loss against the model's predicted distribution q leaves only minus the log of , the chance given to the right answer.
- perplexity
- The cross-entropy loss turned back through the exponential. If the loss used the natural log, use e as the base. If it used base 2, use 2. The value is the same, and with one right answer it is 1 over the chance given to that answer.
1. Logarithms: how many times did you multiply?
A logarithm answers the question "how many times did you multiply?" Multiply 2 three times and you get 8 (2 × 2 × 2 = 8). Asked the other way round, "8 is 2 multiplied how many times?" The answer, 3, is written log₂ 8 = 3. The small 2 is called the base. It is the number being multiplied.
The count does not have to be a whole number. Three 2s make 8 and four make 16, so 10 is somewhere in between: log₂ 10 ≈ 3.32. Numbers below 1 come from dividing instead of multiplying, so their logarithm is negative: log₂ 0.5 = −1, log₂ 0.25 = −2. A probability is between 0 and 1, so its logarithm is 0 or less. That is why we put a minus sign in front and write −log p.
| Base | Written | Unit of surprise | Where it is used |
|---|---|---|---|
| 2 | log₂ | bit | Information theory, compression. One fair coin flip = 1 bit |
| e (about 2.718) | ln (natural log) | nat | Loss in AI training. Its slope formulas come out clean |
| 10 | log₁₀ | hartley | Counting digits. log₁₀ 1000 = 3 |
e is a number, 2.718…, whose digits go on forever. Changing the base only multiplies every value by the same number. log₂ x = ln x ÷ ln 2, so 1 nat is about 1.443 bits. Same meaning, different ruler.
The most useful thing about logarithms is that they turn multiplying into adding.
Example: log₂(4 × 8) = log₂ 32 = 5 = 2 + 3. 4 is two 2s multiplied and 8 is three, so their product is five 2s multiplied.
2. Surprise: −log(probability)
When something with probability p happens, we measure the surprise like this.
Why a logarithm? We want three things from a surprise number.
- Something certain (p = 1) is not surprising at all.
−log 1 = 0. - The rarer it is, the more surprising. The smaller p is, the bigger
−log p, and it grows without limit as p gets close to 0. - When two unrelated things both happen, their surprises add. Their chances multiply (coin heads ½ × die shows 6 ⅙ = 1/12), so we need something that turns a product into a sum. That is the logarithm.
With base 2, each time p is cut in half, the surprise grows by 1 bit. Heads on a fair coin (½) is 1 bit, two coins both heads (¼) is 2 bits, three coins (⅛) is 3 bits. One bit is the amount of information in the answer to one yes-or-no question with even odds.
Try this. ① At the start, p = 0.25 and the surprise is 2 bits. Each press of "Halve" adds 1 bit: 0.125 (3 bits), 0.0625 (4 bits). ② Set p to 0.1 and the surprise is 3.32 bits. At 0.001 it is 9.97 bits. Something that happens once in 1000 times is about as surprising as ten coins all landing heads (1/1024, 10 bits). ③ Look at the third line of the readout. Multiplying p by the coin's ½ adds 1 to the surprise. With p = 0.1: 0.1 × 0.5 = 0.05, and the surprise is 3.32 + 1 = 4.32 bits.
3. Entropy: the average surprise
There are several possible outcomes, and each has a probability. This list of probabilities is called a probability distribution (it adds up to 1). Each outcome has its own surprise, so we take the average, weighting each one by its probability. That gives "how surprised you are on average". This is the entropy. It tells you how hard the outcome is to predict.
Σ means "add them all up", and pᵢ is the probability of outcome number i. An outcome with probability 0 never happens, so its term counts as 0 (0 × log 0 = 0).
Work it out by hand: three coins
- Fair coin (heads 0.5, tails 0.5). Both surprises are
−log₂ 0.5 = 1bit.H = 0.5 × 1 + 0.5 × 1 = 1 bit. - Biased coin (heads 0.9, tails 0.1). Surprise of heads
−log₂ 0.9 ≈ 0.152, surprise of tails−log₂ 0.1 ≈ 3.322.H = 0.9 × 0.152 + 0.1 × 3.322 ≈ 0.137 + 0.332 ≈ 0.47 bits. - Coin that always lands heads (1, 0).
H = 1 × 0 = 0 bits. You already know the result, so there is nothing to be surprised about.
The same working, written as formulas. The base is 2 and the unit is bits.
The biased coin usually lands heads, so it is easy to guess, and its entropy is small. With n possible outcomes, the entropy is largest when all of them are equally likely (1/n each), and then it equals log₂ n. With four outcomes, that is 2 bits.
4. Cross-entropy: the average surprise through your prediction
Things really happen with probabilities p, but you do not know them. You hold a prediction q instead. The surprise you feel when you see an outcome comes from your prediction. You thought it had probability qᵢ, so your surprise is −log qᵢ. In reality it happens a share pᵢ of the time. The average is:
It is the entropy formula with the p inside the surprise swapped for q. The weights come from reality p, and the surprises come from the prediction q. If the prediction matches reality (q = p), it equals the entropy. Otherwise it is always bigger.
To see this formula built step by step out of bar areas, go to 6. How the formula is built.
When q is 0. If the prediction gave 0 to something that really happens (pᵢ above 0), then the surprise when it happens is −log 0 = ∞ (infinity). So the cross-entropy is infinite too. Say "this never happens", be wrong, and the penalty has no limit. On the other hand, an outcome with pᵢ = 0 never happens, so its term is 0 whatever q gave it.
Drag the bars of real p and prediction q up or down, or type numbers. When you change one bar, the others grow or shrink, keeping their ratios, so the total stays 1. The orange KL bar sits exactly where the cross-entropy bar goes past the entropy, and has the same length. A striped bar means infinity.
Try this. ① At the start, the real weather is p = (0.5, 0.25, 0.125, 0.125) and the "even guess" is q = (0.25, 0.25, 0.25, 0.25). Entropy 1.75 bits, cross-entropy 2 bits, KL 0.25 bits. ② Press "Prediction matches reality". Both become 1.75 and KL becomes 0. ③ "Confident and wrong" puts 0.97 on snow. The cross-entropy jumps to 5.82 bits. ④ Pull the "sun" bar of prediction q down to 0. The cross-entropy and KL become ∞.
5. KL divergence: how far the prediction is from reality
Cross-entropy mixes two things: how hard reality is to predict in the first place (the entropy), and the extra surprise caused by your wrong prediction. The KL divergence is that extra part on its own. Reality goes before the ‖ and the prediction after it.
- It is 0 or more. It is 0 only when the prediction matches reality. A wrong prediction can never make you less surprised.
- Swap the two and the value changes. If the real coin is biased, p = (0.9, 0.1), and you predict a fair coin, q = (0.5, 0.5), then
KL(p‖q) ≈ 0.53bits, but the other way roundKL(q‖p) ≈ 0.74bits. A real distance from Seoul to Busan is the same as from Busan to Seoul. So KL measures "how different", but it is not a distance in the everyday sense. - Making cross-entropy smaller = making KL smaller. Reality p is fixed, so H(p) stays the same however you change the prediction. When you adjust q to lower the cross-entropy, the only thing that goes down is the KL. When AI training lowers the cross-entropy, it is pulling the predicted distribution toward the real one.
Try this. ① Press "Biased coin". Entropy 0.47, cross-entropy 1, KL 0.53 bits. The last line of the readout shows the swapped KL(q‖p) = 0.74. ② At the start (weather, even guess), both directions happen to be 0.25. With "Confident and wrong" they are very different: 4.07 and 2.73. ③ From "Even guess", lower the "sun" bar of real p to 0.25. p spreads out to (0.25, 0.375, 0.1875, 0.1875), the entropy rises to 1.94, and the KL drops to 0.06. As reality gets closer to the prediction, KL gets smaller.
6. How the formula is built: cross-entropy and KL
Let's build the cross-entropy H(p, q) = −Σ pᵢ × log qᵢ and KL(p‖q) = H(p, q) − H(p) one step at a time, as the area of bars. The numbers are the starting state of lab ②: the real weather p = (0.5, 0.25, 0.125, 0.125) and the even-guess forecast q = (0.25, 0.25, 0.25, 0.25). A bar's height is the surprise in bits, and its width is how often that weather really comes.
Press "Next" to go one step at a time. A piece is added to the formula at the top (the orange background marks the new piece), the bars change to match, and the reason appears below. The number above a bar is its height (the surprise), and the number inside is its area (share × surprise). Numbers that do not fit in a narrow bar are in the text below. Blue is the surprise through the forecast q, green is the surprise through the real p, orange is extra surprise caused by the wrong forecast, and purple stripes are reduced surprise.
Written as formulas only, the steps above are:
- Surprise:
−log qᵢ. The forecast gave all four kinds of weather 0.25, so whatever comes, the surprise is−log₂ 0.25 = 2bits. Why: the surprise you feel comes from the prediction you were holding, not from the real chance (section 4). - Weigh by the real share:
pᵢ × (−log qᵢ). Each bar's width becomes its real share: 0.5, 0.25, 0.125, 0.125. The areas become 1, 0.5, 0.25, 0.25. Why: sun comes every other day, so you feel the sun surprise on half of the days. A surprise you feel more often should count more in the average. - Add it up:
H(p, q) = Σ pᵢ × (−log qᵢ).1 + 0.5 + 0.25 + 0.25 = 2bits. This is the cross-entropy. You can also move the minus sign to the front and write−Σ pᵢ × log qᵢ. Why: the widths add up to 1, so the total area is "how many bits of surprise per day, on average". Level the bars flat and that is the height you get (the dashed line across). - Swap the prediction for reality:
H(p) = −Σ pᵢ × log pᵢ. Measure the surprise with the real shares and the heights become 1, 2, 3, 3 bits. The areas add up to0.5 + 0.5 + 0.375 + 0.375 = 1.75bits, the entropy. The widths are reality, so they stay. Only the heights change. Why: even a perfect prediction cannot stop the weather from being mixed, so this much surprise is always left. This is the floor. No q makes the area smaller than 1.75, and only q = p reaches it. This fact (the information inequality, also called Gibbs' inequality) is not proved here. In lab ②, drag the bars of prediction q around: the cross-entropy never goes below 1.75. - The gap:
KL(p‖q) = Σ pᵢ × log(pᵢ ÷ qᵢ). For each kind of weather, take the area seen through q minus the area seen through p:pᵢ × (−log qᵢ) − pᵢ × (−log pᵢ) = pᵢ × log(pᵢ ÷ qᵢ). Sun0.5 × (2 − 1) = 0.5, clouds 0, rain and snow0.125 × (2 − 3) = −0.125each. Why: a single part can be negative. The forecast gave rain and snow more than they really get (0.25 instead of 0.125), so a rainy day actually surprises you less. But the chances must add up to 1, so what goes to one place is taken from another. Sun lost chance, and the extra surprise there is bigger. The total is0.5 + 0 − 0.125 − 0.125 = 0.25. - Done:
H(p, q) = −Σ pᵢ × log qᵢ = H(p) + KL(p‖q). The orange area 0.5 minus the purple area 0.25 leaves 0.25, and it sits on top of the floor.2 = 1.75 + 0.25. Cross-entropy is the floor (the entropy) with the KL on top. SoKL(p‖q) = H(p, q) − H(p), and because of the floor in step 4 it is never below 0. When training adjusts q to lower the cross-entropy, the floor stays and only the KL goes down (section 5).
7. Work it through by hand: a weather forecast
Say the real weather in a city is sun 0.5, clouds 0.25, rain 0.125, snow 0.125. The forecast does not know this and predicts 0.25 for each. This is the starting state of the lab above.
- Surprise using the real chances.
−log₂ 0.5 = 1,−log₂ 0.25 = 2,−log₂ 0.125 = 3,−log₂ 0.125 = 3bits. - Entropy.
H(p) = 0.5×1 + 0.25×2 + 0.125×3 + 0.125×3 = 0.5 + 0.5 + 0.375 + 0.375 = 1.75 bits. - Surprise using the forecast. The forecast said 0.25 for everything, so whatever the weather, the surprise is
−log₂ 0.25 = 2bits. - Cross-entropy.
H(p, q) = 0.5×2 + 0.25×2 + 0.125×2 + 0.125×2 = 2 bits. - KL divergence.
KL(p‖q) = 2 − 1.75 = 0.25 bits. Working it out directly gives the same:0.5×log₂ 2 + 0.25×log₂ 1 + 0.125×log₂ 0.5 + 0.125×log₂ 0.5 = 0.5 + 0 − 0.125 − 0.125 = 0.25.
The same working, written as formulas, with p = (0.5, 0.25, 0.125, 0.125), q = (0.25, 0.25, 0.25, 0.25) and base 2.
You can also read these numbers as compression. Suppose you send each day's weather as 0s and 1s. A code made for the real chances (sun 0, clouds 10, rain 110, snow 111) needs 1.75 digits per day on average. A code made for the even guess (two digits each) needs 2. The extra 0.25 digits are the cost of the wrong prediction, which is the KL.
8. Properties worth knowing
| Property | In plain words | Example |
|---|---|---|
H(p) ≥ 0 | The average surprise is never negative. It is 0 only when the outcome is certain | Coin that always lands heads: 0 bits |
H(p) ≤ log₂ n | With n outcomes, it is hardest to predict when all are equally likely | Four outcomes: 2 bits |
H(p, q) ≥ H(p), so KL(p‖q) ≥ 0 | Predicting with a different distribution keeps the average surprise the same or makes it bigger. Equal only when q = p | Weather: 2 ≥ 1.75 |
Usually KL(p‖q) ≠ KL(q‖p) | Swap them and the value changes. It is not a distance | Coin: 0.53 and 0.74 |
If pᵢ is above 0 but qᵢ = 0, then H(p, q) = KL = ∞ | Predict "never" for something that happens and the penalty has no limit | Striped bars in lab ② |
9. The loss in AI: when there is one right answer
A classifier looks at a photo and picks cat, dog or bird. It does not give a single answer. It gives a probability for each of the three (for example cat 0.9, dog 0.07, bird 0.03). These probabilities usually come from softmax. If the photo really shows a cat, the real distribution is the list (1, 0, 0): 1 for cat, 0 for the others. A list like this is called one-hot.
Work out the cross-entropy between the one-hot answer and the model's prediction, and every term multiplied by 0 drops out. Only one is left.
Only the chance given to the right answer matters. How the rest is split among the wrong answers does not enter the loss. A one-hot list has entropy 0, so here the cross-entropy and the KL are the same number.
The "model" here is a small toy example where you set the three probabilities by hand. A real classifier works these probabilities out from the photo, and training adjusts the numbers inside the model (the weights) in the direction that lowers this loss. Drag the cat bar or type a number. The rest of the probability is split 2 : 1 between dog and bird.
| Chance given to the right answer | Loss (nats) | Loss (bits) | Perplexity |
|---|---|---|---|
| 0.99 | 0.01 | 0.01 | 1.01 |
| 0.9 | 0.11 | 0.15 | 1.11 |
| 0.5 | 0.69 | 1 | 2 |
| 0.1 | 2.3 | 3.32 | 10 |
| 0.01 | 4.61 | 6.64 | 100 |
As the chance on the right answer falls from 0.99 to 0.5, the loss grows by only 0.68 nats. From 0.1 to 0.01 it grows by 2.3 nats. Cross-entropy loss punishes confident wrong answers hard. The smaller the chance on the right answer, the steeper the loss curve too, so gradient descent makes big fixes to badly wrong predictions.
Perplexity is e^(loss in nats). If you worked in bits, it is 2^(loss in bits), and the value is the same. With one right answer it equals 1 ÷ (chance given to the right answer), so you can read it as "how many options the model was torn between".
Try this. ① At the start, the chance on the right answer is 0.9, the loss is 0.11 nats and the perplexity is 1.11. ② Pull the cat bar down to 0.01. The loss shoots up to 4.61 nats and the perplexity becomes 100. ③ Switch to "Base 2 (bits)". At the same spot it is 6.64 bits. Every number is about 1.443 times bigger, but the curve has the same shape, and the perplexity is still 100. ④ Put the chance at 0.5. The loss is 0.69 nats, which is 1 bit.
Where is it used?
- Loss for classifiers. Models that pick one answer out of several, like photo classifiers or spam filters, often use cross-entropy as their loss. Cross-entropy with two answers (yes or no) is the loss of logistic regression (log loss). Training means making this loss smaller with gradient descent.
- Training loss and perplexity of language models. A language model cuts text into tokens (pieces of words) and guesses the next token. It is a classifier with tens of thousands of possible answers. The training loss is the −log of the chance the model gave to the token that really came next, averaged over every position. Perplexity is
e^(loss). A loss of ln 10 ≈ 2.3 nats means a perplexity of 10, which reads as "about as unsure as picking evenly among 10 options every time". Lower is better. How a model turns scores into next-token probabilities is covered by softmax on the sampling page. - Knowledge distillation. A small model (the student) is trained to lower the cross-entropy against the whole probability list from a big model (the teacher). The teacher's list is fixed, so this is the same as lowering the KL. A list like "cat 0.9, dog 0.07" teaches more than a one-hot answer: it also says what looks like what (Hinton, Vinyals, Dean).
- Compression. Entropy is the lowest possible average number of bits per symbol when you compress data without losing anything. If you compress with a code made for a different distribution q, you need H(p, q) bits on average, and you lose KL bits per symbol (the weather codes in section 7).
Common questions
What is entropy?
It is a number for how surprised you are on average when you see the outcome. In other words, how hard the outcome is to predict. Work out −log(probability) for each outcome, then take the average, weighting each outcome by its probability. A fair coin has 1 bit. A coin that always lands heads has 0 bits.
How is cross-entropy different from KL divergence?
Cross-entropy = entropy + KL divergence. Cross-entropy is the whole average surprise when you look at reality through your prediction. KL divergence is only the extra part caused by the prediction being wrong. When the real distribution is fixed, the entropy does not change, so making the cross-entropy smaller is the same as making the KL divergence smaller.
Is KL divergence a distance?
No. It is 0 or more, and it is 0 only when the two distributions are the same. But if you swap them, the value changes. With a biased coin (0.9, 0.1) as the real p and a fair coin (0.5, 0.5) as the prediction q, KL(p‖q) is about 0.53 bits and KL(q‖p) is about 0.74 bits.
Why use a logarithm?
When two unrelated things both happen, their chances multiply, but it feels natural for their surprises to add. A logarithm turns multiplying into adding. Also, multiplying many tiny probabilities makes a number so small that a computer rounds it to 0. Adding their logarithms avoids that.
What is the difference between bits and nats?
Only the base of the logarithm. Base 2 gives bits, and base e (about 2.718) gives nats. They measure the same thing with a different ruler, so 1 nat is about 1.443 bits. AI training libraries usually use the natural logarithm (nats).
Words
| Word used here | Word used in textbooks |
|---|---|
| how many times you multiply | logarithm. With base e, the natural logarithm (ln) |
| surprise, −log p | self-information, information content, surprisal |
| average surprise | entropy, Shannon entropy |
| average surprise through your prediction | cross-entropy |
| extra surprise from a wrong prediction | KL divergence (Kullback-Leibler divergence), relative entropy |
| list of chances for each outcome | probability distribution |
| list with 1 only for the right answer | one-hot vector |
| −log of the chance given to the right answer | negative log-likelihood (NLL), log loss |
| unit for base 2, unit for base e | bit (also called shannon), nat |
| how many options the model was torn between | perplexity |
| how wrong the model is | loss, loss function |
| turning model scores into probabilities | softmax |
| a small model learning a big model's probabilities | knowledge distillation |
Sources
- Shannon, C. E. (1948). A Mathematical Theory of Communication. Entropy and the limit of compression.
- Kullback, S., Leibler, R. A. (1951). On Information and Sufficiency. KL divergence.
- Thomas M. Cover, Joy A. Thomas, Elements of Information Theory, chapter 2 (entropy, relative entropy) and chapter 5 (data compression).
- Hinton, Vinyals, Dean (2015). Distilling the Knowledge in a Neural Network. Knowledge distillation.
- PyTorch torch.nn.CrossEntropyLoss documentation.
- Hugging Face Transformers documentation: Perplexity of fixed-length models. Perplexity as the exponentiated average negative log-likelihood.