Two friends send you a message. One says, “the sun rose this morning.” The other says, “it snowed in the desert this morning.” Only the second message feels like news. Both are true, yet the first one tells you almost nothing, because you expected it. The second tells you a lot, because it was unlikely.
That feeling has a number behind it. Here is a puzzle that shows it. I pick a number from to at random. You may ask yes/no questions. How many do you need? Each good question halves the candidates, so ten questions are enough, because . A one-in- event is worth ten yes/no questions.
This lesson turns “how surprising was that?” into a formula, shows why the formula has to use a logarithm, and then points at the place where it shows up in machine learning: the loss of a classifier is the surprise the model felt at the right answer.
What makes an event surprising
Take an outcome with probability (P1.D1). Call its surprise (the formal name is self-information). Three requirements are hard to argue with.
- Rarer means more surprising. If goes down, goes up.
- Certain means no surprise. If , then . Surprise is not negative.
- Independent events add. Flip a coin and roll a die, and let the two not affect each other (P1.D5). The surprise of seeing both results should be the surprise of the first plus the surprise of the second, the way two separate news items carry two portions of news.
The third requirement is the one that decides the formula. For independent events the probabilities multiply (P1.D5): . So we need a function with
A function that turns a product into a sum is the logarithm (P1.A3): . The log of a probability is negative or zero, and requirement 1 asks for a larger number when is smaller, so put a minus sign in front:
A check on requirement 2: . A check on requirement 3 with a fair coin () and a fair die (): the pair has probability , and , which is bits.
Go deeper Why only the logarithm works
Suppose a function on probabilities satisfies , is decreasing, and changes smoothly (it is continuous). Then it must be a positive multiple of . This is a classical result about the equation . A sketch for a fair coin shows the idea. Applying the rule times gives . So for , a probability of has surprise . Roots follow the same way (), so for every positive rational , and continuity extends it to every real . Writing gives .
The number is a free choice. It is the unit. Choosing gives bits. Choosing it as gives nats. The logarithmic measure was proposed for information by Hartley in 1928 and became the basis of information theory in Claude Shannon’s 1948 paper “A Mathematical Theory of Communication”.
Units: bits, nats and bans
The base of the logarithm only changes the unit, like measuring a length in metres or in feet.
| Base | Unit | Surprise of a fair coin flip | Where it is common |
|---|---|---|---|
| bit | coding, compression, yes/no questions | ||
| nat | calculus, NumPy and PyTorch (log is the natural log), most loss functions | ||
| ban (also hartley) | older literature |
Changing units is a multiplication by a constant (change of base, P1.A2):
So nat is bits, and bit is nats. A ban is bits. Because the units differ only by a constant factor, the ranking of surprises does not depend on the base: the rarer event is more surprising in bits, in nats and in bans.
A word about words. The unit name “bit” is short for “binary digit”, and Shannon’s 1948 paper credits the short form to John W. Tukey. A “bit” of storage is a or a in memory. A “bit” of information is a measurement of surprise, and it does not have to be a whole number. A stored bit holds one bit of information when and are equally likely.
Here is a first table, with every value computed.
| Event | Surprise in bits | Surprise in nats | |
|---|---|---|---|
| a certain event | |||
| a fair coin lands heads | |||
| a fair die shows a | |||
| one in five | |||
| four in five | |||
| one in | |||
| one in a hundred | |||
| ninety-nine in a hundred | |||
| an impossible event | infinite | infinite |
An impossible event has , which is infinite: as gets closer to the surprise grows without limit. (Software shows inf.) That infinite value matters later, because a model that gives the true answer probability gets an infinite loss.
The surprise curve
Move the probability and watch the surprise. The curve is . The slider is linear in bits, so equal slider distances are equal changes in surprise (on an ordinary probability scale, most of the action happens in a tiny stretch near ). With the dot focused, Page Up and Page Down move exactly one bit, which doubles or halves . The plot stops at (about ) so that the numbers stay readable. The real curve keeps rising past the left edge.
What to try:
- Fair coin. Press “Fair coin”: bit. Then press Page Down once: and the surprise is exactly bits. Each halving of adds one bit.
- Certain event. Press End: and the surprise is .
- Edge. Press Home: and the surprise is bits, as many as ten fair coin flips all landing as guessed.
- Units. Switch between bits and nats: the shape stays the same and only the vertical scale changes, by the factor .
- Model right, model wrong. A model that gave the true answer is barely surprised ( bits). One that gave it is surprised by bits.
- Two events. Open the second panel. With two fair coin flips the two bars are and , and the pair is bits. Set the first probability to (a certain event): it adds nothing.
Bits as yes/no questions
A bit has a concrete meaning when the outcomes are equally likely. With equally likely items, each question can cut the list in half: “is it in the first ?”, and so on. Ten questions find the item, which is the bits of surprise of one particular item. For a million equally likely items, , so twenty well-chosen questions are enough (). That is why the game “twenty questions” works.
Where the picture stops. A fair die has bits, but you cannot ask questions. One die needs three questions in the worst case. The fraction shows up when you ask about several dice together: outcomes of ten dice need questions in the worst case ( is too few and is enough), which is per die, and the per-die cost approaches as the number of dice grows. And an event with probability has bits, less than one question: a likely answer teaches you little. So read “bits are yes/no questions” as exact for probabilities that are powers of , and as a guide for the rest.
Surprise adds for independent events
Take a coin that lands heads with probability and flip it three times, getting H, H, T. If the flips do not affect each other, the probability of the sequence is . The surprises add:
The first H costs , the second H costs again, and the T costs (all in nats). The sum equals the surprise of the whole sequence:
The number is the one from the likelihood table of P1.D10: the log-likelihood of H, H, T at was , so the negative log-likelihood is the total surprise. In bits the same sequence is bits. The tail is by far the largest part, because it was the unlikely result.
Independence is needed. If the events depend on each other, the probability of both is (the chain rule, P1.D5), and the surprise splits the same way:
The second term is the surprise of after is known. Example: it rains with probability ( bits), and given rain, someone carries an umbrella with probability ( bits). The surprise of “rain and an umbrella” is bits, which is . Adding the surprise of the umbrella without the rain information would use the wrong probability.
Surprise of a model’s prediction
Now the connection to machine learning. A classifier outputs a probability for each class. After the true class is revealed, look at the probability the model had given to it. The model’s surprise at the truth is . P1.D3 already showed these numbers as losses: a spam model that said for spam has loss when the email is spam, and if the email is not spam the truth had probability , so the loss is . This is the log loss, and it is the surprise in nats.
| given to the truth | ||||
|---|---|---|---|---|
| Loss in nats, | ||||
| Bits, |
A model that was confident and right () has a loss of . A model that was confident and wrong () has , about times as much. The loss grows like the log of how unlikely the model thought the truth was, with no upper limit as approaches .
Surprise belongs to an outcome and a model together. Suppose it rains. A forecaster who said is unsurprised, bits. A forecaster who said is surprised by bits. The event is the same, and the surprise differs, because the surprise is measured with the probability a particular model gave. A model with probabilities that are far from the real frequencies will be surprised more often than a well-calibrated model on the same data.
Surprise also depends on how the event is described. Any exact sequence of ten fair coin flips, such as H T T H H H T H T T, has probability and surprise bits. But the event “some sequence of ten flips happened” has probability and surprise . A rare-looking detail is not news when everything has a rare-looking detail.
Surprise of a sequence, and tokens
A language model reads text token by token and gives a probability to each next token, given the tokens before it (P1.D5, chain rule). The probability of a text is the product of those probabilities, so the surprise of the text is the sum of the surprises of its tokens:
Here is the token at position and stands for all the tokens before it.
Dividing by the number of tokens gives the average surprise per token, reported as nats per token or bits per token. When a library reports a training loss for a language model, it is this average, in nats for the usual frameworks (PyTorch’s cross-entropy uses the natural log). To compare numbers from two sources, check the unit: bits per token is nats per token divided by .
Example: a model gives three tokens the probabilities , and . The surprises are , and bits, adding to bits ( nats). The average is bits per token, or nats per token. The number (equivalently ) is the perplexity: the model is about as unsure as a fair choice between four options at each step. P1.E5 develops it.
Why software adds log-probabilities
The product of many probabilities is a very small number. A thousand tokens, each with probability , have a product of , which a computer stores as 0.0 (P1.D10). The sum of the surprises is an ordinary number: nats, or bits. So training code keeps log-probabilities, adds them, and returns a loss that never needs the tiny product. Frameworks go one step further and compute the log-probabilities directly from the model’s raw scores (the logits) with a stable formula, instead of computing a probability and taking its log (P1.G2). That also avoids taking the log of an exact .
What comes next
Surprise is about one outcome. Four later lessons average it, compare it and combine it.
- Entropy (P1.E2): the average surprise of a source. A fair coin averages bit. A coin that lands heads with probability averages only bits per flip, because the common result is rarely surprising.
- Cross-entropy (P1.E3): the average surprise of the true outcomes under the model’s probabilities. That is the classification loss, and the average of the numbers in the table above.
- KL divergence (P1.E4): the extra average surprise a model has beyond the best possible.
- Mutual information and perplexity (P1.E5): how much knowing one variable reduces the surprise of another, and perplexity as the effective number of choices.
Go deeper Surprise for continuous values
The definition needs an outcome with a probability, so it fits discrete outcomes such as a class or a token. For a continuous quantity, a single exact value has probability (P1.D2). The negative log of a density is sometimes used, but a density can be larger than , which makes of it negative, and its value changes with the units of . P1.D10 had the same issue when comparing log-likelihoods. So for continuous data, surprise is meaningful for ranges of values (an interval has a probability), and for comparing models on the same data. This lesson stays with discrete events.
Go deeper Surprise is not importance
Shannon’s measure counts how unlikely an outcome was under a model. It does not say whether the outcome matters or what it means. A long string of random letters is highly surprising and carries no meaning. “The server is down” may be a likely message on a bad day and still be the most useful message you read. Information theory measures the cost of describing an outcome, and judging value takes more than that.
Try it
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The first block prints bits for the certain event, bit for the coin, for the die, for one in , and and bits for the model that gave the truth and (the same values in nats are and ). The sum of surprises for H, H, T is bits or nats, equal to the surprise of the product. The three tokens give bits and nats per token and a perplexity of . The thousand-token product prints 0.0, while the total surprise is nats, which is bits. The last line prints inf. Challenge: change the coin’s to and check that every flip adds exactly bit.
Intuition, math and code at a glance
Intuition
Surprise is how unexpected an outcome was under your model. A likely outcome is hardly surprising, and a rare one is very surprising. Taking the log makes surprises add when events are independent, like adding the lengths of two ropes. Each halving of the probability adds one bit: ten halvings take you from certainty to one in .
Math
Adding surprises, and changing units:
The first sum holds for independent events and the second holds in general.
Facts to remember:
- , and is larger when is smaller
- a fair coin is bit, a fair die is bits, and is bits
- the loss is the model’s surprise at the truth, in nats
Code
Compute surprise in bits and nats with NumPy.
import numpy as np
p = np.array([0.5, 1 / 6, 0.01])
print(np.log2(1 / p)) # about [1, 2.585, 6.644] bits
print(np.log(1 / p)) # about [0.693, 1.792, 4.605] natsCommon mistakes
Check your understanding
A fair six-sided die lands on . How surprising is this, in bits?
The probability is , so the surprise is bits. The number counts the outcomes and is not a surprise. The value is , the surprise in bans, not in bits. The value is , the surprise in nats, so calling it bits mixes up the units.
Two independent events have surprises of bits and bits. How surprising is it that both happen?
The probabilities are and . For independent events they multiply to , a surprise of bits, which is also the sum . The product multiplies the surprises, and the surprise adds. The value is the average of the two. The value is only the larger of the two, as if the smaller event added nothing.
A classifier gave the true class probability on one example and on another. How many more nats of surprise did the second example cause?
The surprises are and , and the difference is . The value is a ratio of probabilities minus one, not a difference of logs. The value is the difference of the two probabilities, which is not a surprise. The value is the whole surprise of the second example, without subtracting the first.
Which property of the logarithm makes it the right function for the surprise of independent events?
For independent events the probabilities multiply, and the log of a product is the sum of the logs. With a minus sign, rarer events get a larger surprise, not a smaller one. The log of most probabilities is not a whole number: is . And grows without limit as approaches , so an impossible event has infinite surprise.
A language model reports an average loss of nats per token. About how many bits per token is that?
One nat is bits, so nats is bits. The value multiplies by and goes in the wrong direction. The value ignores the change of units. The value divides by , which converts to bans, not to bits.
Exercises
- Find the surprise in bits and in nats of an event with probability , one with probability , and one with probability .
Show answer
For : bits and nats. For : bits and nats. For : bits and nats. - A lottery ticket wins with probability in . How surprising is a win in bits and nats, and about how many fair coin flips in a row is that?
Show answer
bits and nats. It is as surprising as about fair coin flips all landing as guessed. - An item is chosen at random from equally likely items. What is its surprise in bits, and how many yes/no questions do you need in the worst case?
Show answer
bits. Seven questions are needed, because is less than and is enough. The is not a whole number of questions, so the picture of questions fits only roughly. - A card drawn from a deck is a heart (), and a separate fair die shows a (). Assume the two do not affect each other. Find each surprise and the surprise of both.
Show answer
Heart: bits. Six: bits. Both: , so bits, which is the sum . - It rains. Forecaster A had said and forecaster B had said . Find each one’s surprise in bits and in nats.
Show answer
A: bits and nats. B: bits and nats. The event is the same, and the surprises differ because the models gave different probabilities. - It rains with probability , and given rain an umbrella appears with probability . What is the surprise of rain and an umbrella, in bits?
Show answer
, and bits. Equivalently bits. - A language model gives three tokens the probabilities , and . Give the total surprise and the surprise per token in bits and nats, and the perplexity.
Show answer
The bits are , , , adding to bits, or nats. Per token: bits or nats. Perplexity: . - A model gives independent examples a probability of each. What is the total surprise in nats and in bits, and why does the product of the probabilities fail on a computer?
Show answer
nats, or bits. The product is about , below the smallest positive float (about ), so it is stored as . - A model’s average loss is nats per token. How many bits per token is that, and what does it say about the model’s choices?
Show answer
bit per token, the surprise of a fair coin flip (perplexity ): on average the model is as unsure as a fair choice between two options. - Explain why a specific sequence of ten fair coin flips has bits of surprise and “some sequence of ten flips” has .
Show answer
One particular sequence has probability , so its surprise is bits. The event “some sequence” covers all sequences and has probability , so its surprise is . Surprise depends on how finely the event is described.
Next: P1.E2 averages the surprise over a source and calls it entropy, which is also a limit on how far lossless compression can go. P1.E3 averages the surprise of the true labels under a model’s probabilities and gets cross-entropy, the classification loss. P1.E4 measures the extra surprise from using the wrong model, and P1.E5 covers mutual information and perplexity.