Lesson 8 of 116 min
Entropy
An outcome's surprise is how many yes/no questions it takes, in bits; entropy is the average surprise, and it measures how unsure a guess is.
After this lesson you can measure uncertainty in bits.
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.
Add up the surprise
Each possible outcome contributes its chance times its surprise in bits. Add those terms to get −Σ p log₂(p). A zero-chance outcome contributes zero, so you can leave it out before taking the log.
import numpy as np
def bits(chances):
p = np.asarray(chances)
p = p[p > 0]
return -(p * np.log2(p)).sum()
print(f"Biased coin: {bits([0.9, 0.1, 0]):.3f} bits")Biased coin: 0.469 bits
Convert nats to bits
PyTorch's Categorical uses the natural log. Its entropy comes out in nats. Divide by the natural log of two to read the same result in bits.
import torch
coin = torch.distributions.Categorical(probs=torch.tensor([0.9, 0.1]))
nats = coin.entropy().item()
print(f"{nats:.3f} nats = {nats / np.log(2):.3f} bits")0.325 nats = 0.469 bits
Ask about several tosses together
Even a 90% coin needs one whole yes-or-no question to name one toss. Group ten tosses and give each string a code of ceil(−log₂(p)) bits. Such lengths allow a code you can read without gaps. More likely strings get shorter codes, bringing the average per toss closer to 0.469.
from itertools import product
tosses = 10
tails = np.array([sum(row) for row in product((0, 1), repeat=tosses)])
chance = 0.9**(tosses - tails) * 0.1**tails
length = np.ceil(-np.log2(chance))
print(f"{(chance @ length) / tosses:.3f} questions per toss")
print(f"Entropy: {bits(chance) / tosses:.3f} bits per toss")0.507 questions per toss Entropy: 0.469 bits per toss
Guess a penguin's species
Pick a penguin uniformly from the dataset. Count how often each species comes up and feed those shares into the same function. Equal shares across three species would give a little more entropy.
import pandas as pd
url = "https://raw.githubusercontent.com/allisonhorst/palmerpenguins/main/inst/extdata/penguins.csv"
shares = pd.read_csv(url).species.value_counts(normalize=True)
print(f"Penguin species: {bits(shares):.3f} bits")
print(f"Three equal shares: {bits([1 / 3] * 3):.3f} bits")Penguin species: 1.514 bits Three equal shares: 1.585 bits
Group answers by meaning
“Paris” and “The capital is Paris” can go in the same group. Farquhar and colleagues sample answers, group them by meaning and measure the spread over groups. Here the groups are marked by hand. High entropy means answers disagree in meaning. Agreement alone can still be wrong.
from collections import Counter
phrases = ["Paris", "The capital is Paris", "Paris, France", "Lyon"]
meaning = ["Paris", "Paris", "Paris", "Lyon"]
for labels in (phrases, meaning):
p = np.array(list(Counter(labels).values())) / len(labels)
print(f"{len(p)} groups: {bits(p):.3f} bits")4 groups: 2.000 bits 2 groups: 0.811 bits
Run on Python 3.13.3, NumPy 2.5.5, pandas 3.1.1 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: Random variables and distributions
You ask a chatbot the same thing twice, and some words of its two answers differ. Nothing in the model changed. Where does the difference come from?
2 of 3
Model A picks its next word from four words, each with a chance of 0.25. Model B knows ten thousand words, and gives one of them 0.99. Which model is more unsure?
3 of 3
A model picks its next word from three. "Time" has a chance of 0.5, and two other words have 0.25 each. What is its entropy, in bits?
The ideas in this lesson
- Surprise
- How surprising an outcome is, in bits: how many times you halve 1 to reach its chance.
- Entropy
- The average surprise of a distribution, in bits: how unsure a guess is. Evenly spread chances give the most.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
How unsure?
Here's a challenge. Some guesses are easy. Some are hard.
Heads or tails is hard to guess. A chatbot's next word can be easy. Or it can be hard. So how do you measure how unsure a guess is?
Your guess
Try this. A fair coin. Or a wheel with a thousand parts, where one part comes up ninety-nine times in a hundred. Which one is harder to guess?
A bit
Start with a game: find something with yes or no questions. To find out how a fair coin landed, you ask, "Heads?"
One question settles it. Now eight cards, each just as likely. "Is it one of the four on the left?"
Then once more, and once more. Three questions. Each good question halves what's left.
Each yes or no question... is worth one bit. And each bit doubles the choices. One bit, two cards. Two bits, four. Three bits, eight.
Surprise
Now look at one card. Its chance is one in eight. Start from one, and cut it in half. How many halvings to get to an eighth?
Three. So finding that card is worth three bits. Three halvings is the log of an eighth, without its minus sign. That number of bits is called the card's surprise. A chance of a half: one bit. A sure thing: zero bits, no surprise at all.
Most chances fall between these. Zero point nine is more than a half, so it takes less than one halving: zero point one five bits. Zero point one is less than an eighth, so it takes more than three halvings: three point three two bits. So the rarer the outcome... the more bits it's worth.
The average surprise
And when the chances aren't equal?
An unfair coin lands heads nine times in ten. Heads surprises you a little: zero point one five bits. Tails surprises you a lot: three point three two. But tails only comes up one time in ten. So count each surprise as often as it comes up, and add them up. You get zero point four seven bits.
The average surprise... is called the entropy.
Part of a question
Zero point four seven of a question?
One toss still takes one whole question. But you can guess two tosses at once. First ask, "Both heads?" Both tosses come up heads eighty-one times in a hundred, and then one question settles both. When the answer is no, one or two more questions settle it. On average, that's about one point three questions for two tosses: zero point six five a toss. Guess more tosses together, and good questions get down to zero point four seven a toss.
Now slide the coin from fair toward sure.
One bit falls all the way to zero.
The wheel
Now the wheel from the start. A thousand parts, and one comes up ninety-nine times in a hundred. Harder to guess than a coin?
Its entropy is zero point one eight bits. That's less than one fair coin. A thousand outcomes, and it's easier to guess than a coin toss.
Now give all thousand parts the same chance.
About ten bits, because ten halvings take one down to about a thousandth. So the more evenly the chances spread, the bigger the entropy, no matter how many outcomes there are.
A real model
Does a real model show this?
Here's a small open language model, the kind chatbots are built on. After "Once upon a", it gives "time" a chance of almost one. Its entropy is zero point zero one bits. It's sure.
After "The cat sat on the", it spreads its chances: floor, grass, mat, bed, sofa, and many more. Seven point three bits.
Each bit doubles the choices, so that's as unsure as a fair pick from about a hundred and sixty words.
In code
Now in real code. The unfair coin, in one line of NumPy. For each chance: the chance, times its log in halvings.
Add those up, and put a minus in front. What will it print?
Zero point four six nine: the zero point four seven from before.
SciPy, a Python library of tools for math and statistics, has it built in: the same zero point four six nine.
And the model's two beginnings give the same numbers as before: zero point zero one bits, and seven point three. Researchers use this to spot answers a model made up. They ask it the same question several times. If its answers mean different things, the entropy of those meanings is high. That's a warning: the model may be making the answer up.
How unsure
So a bit is one yes or no question. An outcome's surprise is its bits.
And the entropy is the average surprise: how unsure a guess is.
Evenly spread chances give the most.
How unsure, in bits
Entropy measures how unsure a guess is, in bits. Now try it on this lesson's page, and take the quiz. Find a coin that's half as unsure as a fair one.
You use this lesson in Lab 3: Score a language model's guesses, after Cross-entropy and KL divergence.
Facts last checked on .
