EVERYTHING AIAI engineering, made visual
0/23 complete
LESSON 09 · MATHEMATICS × AI · LEARN

Unlikely things carry
the most information.

I(p) = −log₂ p turns probability into surprise: a fair coin is 1 bit, a 1-in-1000 event is 9.97 bits. Average that surprise over a distribution and you have entropy — the quantity every loss function is built on.

60 MIN · 8 CHAPTERSPREREQ · LESSON 06
FIG. 09 / THE SURPRISE OF AN EVENT
p = 0.500 · 1.00 BITS I(p) curve current event
LESSON 09TYPE · LEARN~60 MINPREREQ · LESSON 06ORIGINAL LESSON ↗
THE 60-SECOND VERSIONThen show me how ↓
01 / RARE EVENTS CARRY MORE BITS

Surprise is −log p.

An event with probability p carries I(p) = −log₂p bits. A fair coin is 1 bit, a six on a die is 2.58 bits, a 1-in-1000 event is 9.97 bits, and a certainty is 0 bits. Use the natural log instead and the same quantity is measured in nats (1 nat = 1.4427 bits).

I(0.5) = 1 bit · I(0.001) = 9.97 bits
02 / ENTROPY IS THE AVERAGE

Average surprise across the outcomes.

H(P) = −Σ p log p is the expected surprise of a distribution. A fair coin carries exactly 1 bit; a coin that lands heads 99% of the time carries only 0.081 bits, because you already know the answer. A uniform distribution over K outcomes maximizes entropy at log₂K bits.

H(coin) = 1 bit · H(0.99 coin) = 0.081 bits
03 / CROSS-ENTROPY = ENTROPY + KL

The loss is a price for being wrong.

Cross-entropy H(P,Q) = −Σ p log q is the average surprise when reality is P but the model believes Q. It splits cleanly: H(P,Q) = H(P) + D_KL(P‖Q). The true distribution is fixed during training, so minimizing the loss is exactly minimizing the extra bits wasted by the wrong model.

H(P,Q) = H(P) + D_KL(P‖Q)
MENTAL MODEL IN ONE SENTENCE

An unlikely event is surprising, and surprise is measured by −log p. Average surprise is entropy. The extra surprise you suffer by believing the wrong distribution is KL divergence, and cross-entropy — the loss you call every day — is entropy plus that extra surprise.

By the end you will be able to compute surprise, entropy, cross-entropy, KL divergence and perplexity from a handful of numbers, explain why minimizing cross-entropy is the same as minimizing KL, read a perplexity score like a practitioner, and see information theory behind classification losses, decision trees and language models.

INFORMATION IS SURPRISE

A rare event is a
loud message.

When something unlikely happens, it tells you more than something you expected. Information theory makes that instinct exact with one formula: I(p) = −log p.

A coin landing heads is barely news. A lottery win is a headline. The difference is probability, and the information content of an event with probability p is I(p) = −log p. Log base 2 measures the answer in bits — the number of yes/no questions it would take to pin the event down. Log base e measures the same quantity in nats, and 1 nat = 1.4427 bits.

Plain English: take the probability, ask how many times you would have to halve it to reach 1, and that count is the surprise. A certainty never needs a question, so it carries 0 bits. A 1-in-1000 event needs almost ten.

I(p) = −log₂ p (bits) = −ln p (nats) event p −log₂ p fair coin heads 0.5 1.000 bit one yes/no answer rolling a six 1/6 2.585 bits 1-in-1000 event 0.001 9.966 bits certain event 1.0 0.000 bits no news at all

The surprise of one event

Drag the probability and watch the curve point and the bar. Halving a probability adds exactly one bit of surprise.

I(0.17) = −log₂ 0.17 = 2.585 bits = 1.792 nats interpreting the bits: ≈ 2.58 yes/no questions to pin the event down. p = 1 → 0 bits: you already knew it.

Base 2 gives bits; base e gives nats. The two answers are the same surprise in different units: 1 nat = 1.4427 bits.

Derivation: why surprise must be −log p

Ask what any reasonable measure of surprise should do, then find the only function that does it.

  1. A certain event carries no surprise: I(1) = 0.
  2. Rarer means more surprising, so I decreases as p grows.
  3. Two independent events happening together should surprise you by the sum of their surprises: I(p·q) = I(p) + I(q). Learning both pieces of news tells you the two things, no more.
  4. The only continuous function that turns a product into a sum is a logarithm, I(p) = c·log p. Positive and decreasing forces c < 0; choosing base 2 and c = −1 makes the unit the bit. So I(p) = −log p, forced by the three requirements.
numeric checks: I(0.5) = −log₂ 0.5 = 1.000 bits = 0.693 nats I(1/6) = −log₂ 0.1667 = 2.585 bits I(0.001) = −log₂ 0.001 = 9.966 bits = 6.908 nats I(1) = 0 bits the product property, checked: I(0.5 · 0.001) = I(0.0005) = 10.966 bits I(0.5) + I(0.001) = 1.000 + 9.966 = 10.966 bits ✓

The logarithm is not decoration. It is exactly what turns “two independent things happened” into “add the surprises”.

Quick check

The forecast said 90% rain, and it rained. Your friend's app said 10% rain, and it rained. Whose correct prediction carried more information?

ENTROPY IS AVERAGE SURPRISE

Average the news
over every outcome.

A distribution is a whole family of possible events. Entropy is the expected surprise of one draw from it — the uncertainty you cannot remove, no matter how clever your encoder.

Entropy takes the surprise of every outcome and weights it by how often that outcome happens:

H(P) = Σ p(x) · I(x) = −Σ p(x) · log p(x)

Plain English: entropy is the average number of yes/no questions a draw from the distribution costs. A fair coin is exactly 1 bit per flip. A coin that lands heads 99% of the time is only 0.081 bits, because you already know the answer. A fair six-sided die is log₂6 = 2.585 bits.

Entropy of a four-outcome distribution

Slide the weights of the four outcomes. Only their shape matters: uniform is the most uncertain distribution, and a certain outcome has zero entropy.

p = [0.250, 0.250, 0.250, 0.250] H(P) = −Σ p log₂ p = 2.000 bits = 1.386 nats max possible = log₂ 4 = 2.000 bits redundancy = 2.000 − 2.000 = 0.000 bits 2^H ≈ 4.00 equally likely choices

Zero-weight outcomes contribute nothing: 0·log 0 is defined as 0. Entropy counts the surprise of what can actually happen.

Worked check: the biased coin, term by term
P = [0.99, 0.01] H(P) = −(0.99 · log₂ 0.99 + 0.01 · log₂ 0.01) = −(0.99 · (−0.0145) + 0.01 · (−6.6439)) = 0.0144 + 0.0664 = 0.0808 bits sanity checks: fair coin [0.5, 0.5] → H = 1.0000 bits (maximum for two outcomes) biased coin [0.99, 0.01] → H = 0.0808 bits almost sure [0.999, 0.001] → H = 0.0114 bits certain [1, 0] → H = 0 bits

The two terms are the two outcomes’ contributions. The rare outcome is individually surprising (6.64 bits), but it almost never happens, so its contribution is multiplied by 0.01 and the average collapses. This is why entropy is sometimes read as the amount of randomness: it is the uncertainty of the source, not of one dramatic outcome.

Two conventions worth fixing now. A term with probability zero contributes nothing — 0·log 0 is defined as 0, because an impossible outcome can never surprise you. And entropy is a property of the distribution’s shape: relabeling the outcomes does not change it.

Quick check

A coin is so biased that it lands heads 999 times out of 1000. Roughly how much entropy does each flip carry?

ONE SHAPE MAXIMIZES IT

Same outcomes.
Different uncertainty.

Entropy depends on how probability is spread, not on how many labels there are. Among all distributions over K outcomes, the uniform one always wins — and that ceiling is worth memorizing.

The uniform distribution over K outcomes has entropy log₂K: every draw is maximally hard to predict. At the other extreme, a distribution that puts all its mass on one outcome has entropy 0 — that draw is free. Real distributions live in between, and the interesting ones are usually far closer to certainty than to uniform.

uniform
H = 2.000 bits
uneven text
H = 1.750 bits
almost certain
H = 0.242 bits
certain
H = 0.000 bits
Four distributions over four outcomes. The uniform shape reaches the maximum log₂4 = 2 bits; any concentration of probability lowers the average surprise.

Plain English: entropy is the fair price of uncertainty. A model that knows the next word pays almost nothing to encode it; a model choosing among a uniform vocabulary of 50,000 tokens pays log₂50000 = 15.61 bits per token.

Derivation: why uniform maximizes entropy

Write entropy as H(P) = Σ p·log(1/p) and apply Jensen’s inequality. Because log curves downward (it is concave), E[log X] ≤ log E[X]. Use the probabilities themselves as the weights and let X = 1/p:

H(P) = Σ p(x) · log(1/p(x)) ≤ log( Σ p(x) · 1/p(x) ) = log( Σ 1 ) = log K equality exactly when 1/p(x) is the same for every x → p(x) = 1/K (the uniform distribution)

Numeric checks with K = 4:

uniform [0.25, 0.25, 0.25, 0.25] → 2.000 bits = log₂ 4 (max) dyadic [0.50, 0.25, 0.125, 0.125] 0.5·1 + 0.25·2 + 0.125·3 + 0.125·3 = 0.5 + 0.5 + 0.375 + 0.375 → 1.750 bits almost sure [0.97, 0.01, 0.01, 0.01] 0.0426 + 3 · 0.0664 → 0.242 bits certain [1, 0, 0, 0] → 0.000 bits K = 26 (letters): max = log₂ 26 = 4.700 bits K = 50 000 (tokens): max = log₂ 50 000 = 15.610 bits

The dyadic example makes the rule visible: halving a probability adds exactly one bit of surprise, so probabilities of 1/2, 1/4, 1/8, 1/8 contribute 1, 2, 3 and 3 bits weighted by their own mass.

THE LOSS YOU CALL EVERY DAY

Cross-entropy prices
a model that is wrong.

Reality follows P; your model believes Q. The average surprise of reality under the model’s beliefs is cross-entropy — and for a one-hot label it collapses to one clean number.

Cross-entropy uses the true probabilities to weight the model’s surprise:

H(P, Q) = −Σ p(x) · log q(x)

Plain English: events really come from P, but you encode them with Q. You pay −log q(x) whenever x happens, and it happens with probability p(x). If Q = P you pay exactly the entropy. Any mismatch makes the average bill larger. For classification, P is a one-hot vector, so every term with p = 0 vanishes and only the true class survives:

H(P, Q) = −log q(true class) ← the whole loss

The model’s raw scores are logits z; softmax turns them into probabilities, q = softmax(z). Then the loss is just the surprise of the correct answer, in nats. Three viewpoints agree that this is the right objective: it counts wasted bits (information), it is the negative log-likelihood of the data (statistics), and its gradient with respect to the logits is the beautifully simple p − y (optimization).

Softmax to cross-entropy loss

Move the logits, pick the true class, and change the temperature. The loss depends only on the probability the model gives the correct class: −ln p(true).

0.659z = 2.0cat ✓ true0.242z = 1.0dog0.099z = 0.1bird0p
z / T = [2.000, 1.000, 0.100] subtract max 2.000 → exp → Σe = 1.5174 p = [0.6590, 0.2424, 0.0986] loss = −ln p(cat) = −ln 0.6590 = 0.417 nats = 0.602 bits perplexity = 1 / p(true) = 1.52 H(prediction) = 1.222 bits gradient p − y = [-0.34, 0.24, 0.10] unsure: moderate loss

Temperature only rescales the logits: T > 1 flattens the distribution and raises its entropy; T < 1 sharpens it. With a one-hot label, the loss is exactly the surprise of the correct answer.

Worked check: from logits to loss, twice

Softmax subtracts the largest logit before exponentiating. The shift cancels in the normalization, so it changes nothing mathematically and prevents overflow.

example A — logits [2.0, 1.0, 0.1], true class 0 shift by max 2 → [0, −1, −1.9] exp → [1, 0.367879, 0.149569] Σe = 1.517448 q = [0.659001, 0.242433, 0.098566] loss = −ln 0.659001 = 0.417030 nats = 0.417030 · 1.4427 = 0.601647 bits perplexity = 1/0.659001 = 1.517
example B — logits [5.0, 2.0, 0.5], true class 1 shift by max 5 → [0, −3, −4.5] exp → [1, 0.049787, 0.011109] Σe = 1.060896 q₁ = 0.049787 / 1.060896 = 0.046929 loss = −ln 0.046929 = 3.059 nats = 4.413 bits perplexity = 1/0.046929 = 21.31 the model gave the truth only 4.7% of its belief, so it pays 21× the surprise of a certain answer.

Notice how fast the bill grows when the true class is unlikely. Predicting 0.01 for the right answer costs 4.605 nats, more than ten times the 0.417-nat loss of a model that is on the right track.

Derivation: the gradient with respect to the logits is p − y

Write the loss for true class t using the log-sum-exp form of softmax:

L = −log softmax(z)ₜ = −zₜ + log Σⱼ e^zⱼ ∂(−zₜ)/∂zₖ = −1 if k = t, else 0 = −yₖ ∂ log Σⱼ e^zⱼ / ∂zₖ = e^zₖ / Σⱼ e^zⱼ = pₖ so ∂L/∂zₖ = pₖ − yₖ numeric check: q = [0.7, 0.2, 0.1], true class 0 gradient = [0.7−1, 0.2−0, 0.1−0] = [−0.3, 0.2, 0.1] push logit 0 up, the others down — by exactly how wrong each probability is.

The gradient is bounded, smooth, and needs no exponentials beyond the forward pass. That is why softmax and cross-entropy are always paired, and why frameworks fuse them into a single numerical function.

Quick check

A classifier gives the correct class probability 0.01. What is the cross-entropy loss in nats, and in bits?

EXTRA BITS FROM A WRONG MODEL

Being wrong has
a measurable price.

If reality is P and your model believes Q, the extra surprise over perfect knowledge is the KL divergence. It is the piece of the loss training actually pushes on.

Cross-entropy measures the total bill. Entropy is the part you would pay even with perfect beliefs. The difference is the price of the wrong beliefs:

D_KL(P ‖ Q) = Σ p(x) · log( p(x) / q(x) ) = H(P, Q) − H(P)

Plain English: for each outcome, compare what you paid (−log q) with the best possible price (−log p). The gap is extra bits wasted by using Q. Weight the gaps by how often each outcome happens, and you have KL divergence. It is zero exactly when Q matches P, and positive otherwise — but it is not symmetric: D(P‖Q) ≠ D(Q‖P) in general, so it is a divergence, not a distance.

Two distributions, three numbers

Shape the truth P and the model Q. The cross-entropy bar splits into the entropy of the truth plus the extra bits KL charges for the wrong beliefs — and swapping P and Q shows the price is not symmetric.

truth P weights

model Q weights

P = [0.700, 0.200, 0.100] Q = [0.600, 0.250, 0.150] H(P) = 1.157 bits (the truth's own uncertainty) H(P,Q) = 1.190 bits (average surprise believing Q) D(P‖Q) = 0.033 bits (extra bits from Q) D(Q‖P) = 0.035 bits (the other direction) in nats: H(P,Q) = 0.825 D(P‖Q) = 0.023 (× 0.6931) perplexity 2^H(P,Q) = 2.28 equally likely classes

KL is zero only when Q matches P, and it is infinite when Q gives zero probability to an outcome P allows. Swapping shows it is not a distance.

Worked check: two models, one truth, exact numbers

Take truth P = [0.7, 0.2, 0.1] and two models: a good Q = [0.6, 0.25, 0.15] and a bad Q = [0.1, 0.1, 0.8]. Everything in bits, base 2.

H(P) = 1.1568 bits (0.8018 nats) good model: H(P, Q) = 0.7·(−log₂0.6) + 0.2·(−log₂0.25) + 0.1·(−log₂0.15) = 0.5159 + 0.4000 + 0.2737 = 1.1896 bits D(P‖Q) = 1.1896 − 1.1568 = 0.0328 bits (0.0227 nats) bad model: H(P, Q) = 0.7·(−log₂0.1) + 0.2·(−log₂0.1) + 0.1·(−log₂0.8) = 2.3253 + 0.6644 + 0.0322 = 3.0219 bits D(P‖Q) = 3.0219 − 1.1568 = 1.8651 bits (1.2928 nats) the same truth, 57× the wasted bits when the model is bad.

Why KL can never be negative. Use ln x ≤ x − 1 for every positive x, with equality only at x = 1 (the line is the tangent to the concave log curve at 1, so log lies below it). Put x = q/p:

D_KL(P‖Q) = −Σ p·ln(q/p) ≥ −Σ p·(q/p − 1) = −Σ (q − p) = −(1 − 1) = 0

Equality needs q/p = 1 everywhere, i.e. Q = P. So cross-entropy is always at least the entropy, and minimizing cross-entropy is exactly minimizing KL — perfect knowledge is the floor the loss is trying to reach.

Quick check

Which statement about D_KL(P‖Q) is true?

KNOWING ONE TELLS YOU THE OTHER

How much does one
variable leak about another?

Joint entropy, conditional entropy and mutual information measure dependence itself — including the curved, non-monotonic relationships correlation misses. Decision trees run on this idea.

Joint entropy H(X,Y) is the entropy of the pair. Conditional entropy H(Y|X) = H(X,Y) − H(X) is how much uncertainty is left about Y after you observe X. Mutual information is the reduction:

I(X;Y) = H(X) − H(X|Y) = H(Y) − H(Y|X) = H(X) + H(Y) − H(X,Y) = Σ Σ p(x,y) · log( p(x,y) / (p(x)·p(y)) )

Plain English: how many bits of uncertainty about one variable disappear when someone tells you the other. If X and Y are independent, knowing one tells you nothing: I = 0. If X completely determines Y (Celsius and Fahrenheit), H(Y|X) = 0 and mutual information equals H(Y). It is symmetric, never negative, and I(X;X) = H(X) — a variable shares everything with itself.

H(X|Y)I(X;Y)sharedH(Y|X)H(X)H(Y)whole shaded area = H(X, Y) = H(X) + H(Y) − I(X;Y)I(X;Y) = H(X) − H(X|Y)I(X;Y) = H(Y) − H(Y|X)I(X;Y) = H(X)+H(Y)−H(X,Y)I(X;Y) ≥ 0I(X;X) = H(X)
The information Venn diagram. Independent variables have no overlap; perfectly dependent ones overlap completely. Every identity in this chapter is a statement about these areas.
Derivation: mutual information is a KL divergence

The fourth formula above compares the true joint distribution p(x,y) with the “pretend they are independent” product p(x)·p(y). That is exactly a KL divergence — and since KL is never negative, I ≥ 0, with equality precisely when p(x,y) = p(x)p(y), the definition of independence.

independent [[0.25, 0.25], [0.25, 0.25]] every p(x,y) = p(x)·p(y) = 0.25, so the ratio is 1 and log 1 = 0 → I = 0 bits dependent [[0.45, 0.05], [0.05, 0.45]] marginals are p(x) = p(y) = 0.5 p(x,y)/(p(x)p(y)) is 1.8 or 0.2 depending on the cell I = 2·0.45·log₂1.8 + 2·0.05·log₂0.2 = 0.7632 − 0.2322 = 0.5310 bits cross-check: H(X) = H(Y) = 1.0000 bit H(X,Y) = 1.4690 bits I = 1 + 1 − 1.469 = 0.531 bits ✓ H(Y|X) = 1.469 − 1 = 0.469 bits

Mutual information detects any statistical dependence, linear or not. Pearson correlation only sees straight lines; a U-shaped relationship can have correlation near zero while mutual information is high. That difference is why MI is used to rank features and why decision trees ask which feature removes the most uncertainty.

Which split teaches the tree the most?

Eight examples, four labels “yes” and four “no”, so the label entropy starts at exactly 1 bit. Pick a split and watch how much uncertainty each branch leaves behind.

SPLIT A · IG 0.000 bits
SPLIT B · IG 0.549 bits · best here
SPLIT C · IG 0.500 bits

Information gain is the drop in label entropy: IG = H(Y) − H(Y|X). A good split leaves branches that are nearly pure.

H(Y) = −(0.5 log₂ 0.5 + 0.5 log₂ 0.5) = 1.000 bit split B on "humidity": high 3 yes / 0 no n=3 H=0.000 weight=0.375 low 1 yes / 4 no n=5 H=0.722 weight=0.625 H(Y|B) = 0.375·0.000 + 0.625·0.722 = 0.451 bits IG = H(Y) − H(Y|B) = 1.000 − 0.451 = 0.549 bits best of the three: split B with 0.549 bits
#labelskyhumiditywind
1yessunnyhighnone
2yessunnyhighnone
3nosunnylowlight
4nosunnylowlight
5yescloudyhighstrong
6nocloudylowstrong
7yescloudylowgale
8nocloudylowgale
HOW CONFUSED IS THE MODEL?

Perplexity puts
the loss in plain words.

Cross-entropy is measured in nats; perplexity converts it back into a head-count of equally likely choices. Label smoothing and temperature are the same information story told from the opposite side.

Perplexity is the exponential of cross-entropy. It answers one question: if the model’s uncertainty were spread evenly, over how many choices would it be spread?

Perplexity = e^H(P,Q) when H is in nats = 2^H(P,Q) when H is in bits uniform over K choices → H = ln K → perplexity = K

Plain English: a model with perplexity 50 is, on average, as uncertain as a fair 50-sided die — at every token. Lower is better: perplexity 1 would mean it always knew the answer. GPT-2 reached roughly 30 on common benchmarks, and modern models sit in the single digits on well-represented text. A uniform model over a 50,000-token vocabulary has perplexity 50,000; that is the ceiling to compare against.

Perplexity of a token sequence

Set the probability the model gave each true token. Perplexity is the exponential of the average surprise — the effective number of equally likely tokens it is choosing between.

Lower is better. Perplexity 1 means the model was certain and right; perplexity equal to the vocabulary size means it was guessing uniformly.

per-token surprise −ln p: The p=0.90 −ln p = 0.105 nats cat p=0.95 −ln p = 0.051 nats sat p=0.85 −ln p = 0.163 nats on p=0.90 −ln p = 0.105 nats the p=0.80 −ln p = 0.223 nats average CE = 0.648 / 5 = 0.130 nats = 0.187 bits per token perplexity = e^0.130 = 1.138 = 2^0.187 = 1.138 check: geometric mean of p = 0.879 perplexity = 1 / 0.879 = 1.138
Worked check: temperature and label smoothing through the information lens

Temperature divides the logits before softmax: q = softmax(z / T). It does not change the ranking, only how sharply the probability mass concentrates. Watch the entropy of the prediction move, for z = [2, 1, 0.1]:

T = 0.5 q = [0.8638, 0.1169, 0.0193] H(q) = 0.655 bits T = 1.0 q = [0.6590, 0.2424, 0.0986] H(q) = 1.222 bits T = 2.0 q = [0.5017, 0.3043, 0.1940] H(q) = 1.481 bits T → 0 q → one-hot on the top logit H(q) → 0 bits T → ∞ q → uniform over K classes H(q) → log₂K bits temperature is an entropy dial: up flattens, down sharpens.

Label smoothing works on the target instead of the prediction. With ε = 0.1 and four classes, the hard one-hot [0, 0, 1, 0] becomes:

soft = (1 − ε)·one-hot + ε/K = 0.9·[0,0,1,0] + 0.025 = [0.025, 0.025, 0.925, 0.025] H(soft) = −(3 · 0.025 · log₂0.025 + 0.925 · log₂0.925) = 3 · 0.1330 + 0.1040 = 0.5032 bits (0.3488 nats) compare: H(hard one-hot) = 0 bits, and only infinite logits could ever match it exactly.

The smoothed target has positive entropy, so the model is never asked to be 100% certain — a finite, reachable goal. The loss becomes L = (1−ε)·CE(hard target, q) + ε·H(uniform, q), where the second term is a direct penalty on confident predictions. That is regularization and calibration with an information-theoretic name.

CHECK YOURSELF

Five questions.
Then the terms worth keeping.

Answer before you look. The KL and perplexity questions are the ones that separate having read about the loss from understanding what it charges your model for.

0 / 5 answered · 0 correct

01What does “entropy” measure in information theory?

02What is the cross-entropy loss commonly used for in neural networks?

03Why is minimizing cross-entropy equivalent to minimizing KL divergence during training?

04A language model has perplexity 50 on a test set. What does this mean?

05How does mutual information differ from Pearson correlation for feature selection?

Key terms, demystified

Click a card to swap the lazy description for what it actually means.

Exercises from the lesson

Four short problems. Try first; a worked answer is one click away.

  1. Compute the entropy of the English alphabet assuming all 26 letters are equally likely. Then estimate it from real letter frequencies. Which is higher, and why?
    Show one worked answer

    Uniform: H = log₂ 26 = 4.700 bits — the most uncertainty a 26-letter alphabet can carry. Real English is uneven (E ≈ 12.7%, T ≈ 9.1%, but Z and Q ≈ 0.1%), and published frequencies put the entropy near 4.1 bits. The uniform distribution is higher: uneven probabilities make common letters unsurprising, so the average surprise falls. Small dyadic check: uniform over 4 symbols is 2 bits; moving to [0.5, 0.25, 0.125, 0.125] gives 0.5·1 + 0.25·2 + 0.125·3 + 0.125·3 = 1.75 bits.

  2. A model outputs logits [5.0, 2.0, 0.5] for a sample whose true class is 1. Compute the cross-entropy loss by hand in nats, then in bits. What logits would give zero loss?
    Show one worked answer

    Shift by the max (5) so exponentials stay safe: [0, −3, −4.5]. Σeᶻ = 1 + 0.049787 + 0.011109 = 1.060896, so p₁ = e⁻³/1.060896 = 0.046929. Loss = −ln 0.046929 = 3.059 nats, which is 3.059 × 1.4427 = 4.413 bits. Zero loss would need p₁ = 1, i.e. the true logit infinitely above the other two — a finite gap always leaves some probability mass elsewhere, so training approaches zero but never reaches it.

  3. Show that KL divergence is not symmetric. Take P = [0.9, 0.1] and Q = [0.5, 0.5] and compute both directions in nats.
    Show one worked answer

    D_KL(P‖Q) = 0.9·ln(0.9/0.5) + 0.1·ln(0.1/0.5) = 0.9·ln 1.8 + 0.1·ln 0.2 = 0.5290 − 0.1609 = 0.368 nats (0.531 bits). D_KL(Q‖P) = 0.5·ln(0.5/0.9) + 0.5·ln(0.5/0.1) = −0.2939 + 0.8047 = 0.511 nats (0.737 bits). They differ because the same two log-ratios (ln 1.8 and ln 0.2) are weighted by different probabilities: P weights the terms by [0.9, 0.1], Q by [0.5, 0.5]. Direction matters — which distribution supplies the weights is exactly what “P‖Q” names.

  4. Compute the perplexity of a three-token sequence with per-token probabilities [0.5, 0.25, 0.25]. Then check the definition with a model that assigns probability 1/50 to every token.
    Show one worked answer

    Per-token NLL: 0.6931 + 1.3863 + 1.3863 = 3.4657 nats; average 1.1552 nats/token; perplexity = e^1.1552 = 3.175. The shortcut is PPL = 1 / (p₁p₂p₃)^(1/3) = 1 / (0.5·0.25·0.25)^(1/3) = 1 / 0.3150 = 3.175. For p = 1/50 everywhere, average NLL = ln 50 = 3.912 nats and PPL = e^3.912 = 50 exactly: the model's uncertainty is the same as choosing uniformly among 50 tokens. In code: ppl = exp(mean(−log(p) for p in probs)).

Terms this lesson borrows from later lessons (or outside)

You do not need to master these here. Each one gets a proper treatment in its own lesson; the one-line meaning is enough to keep reading. Orange dotted underlines in the prose point back to this list.

  • tokenA word or word-piece that a language model reads or writes one at a time. (outside these lessons)
  • language modelA model trained to predict the next token given the previous ones. (outside these lessons)
  • calibratedA model is calibrated when its stated probabilities match reality: events it calls 70% likely happen about 70% of the time. (outside these lessons)
  • featureOne input column: a single measured property of each example (age, pixel value, word count). (Lesson 10)
  • softmaxExponentiate each logit and divide by the sum: any real-valued vector becomes a valid probability distribution. (Lesson 06)
  • PyTorchA deep learning framework: arrays (tensors) with automatic differentiation built in. Its losses are in nats. (outside these lessons)
  • decision treeA classifier that asks a sequence of yes/no questions about features; each split is chosen to reduce uncertainty about the label most. (outside these lessons)
  • inferenceUsing a trained model to make predictions, as opposed to training it. (outside these lessons)
KEEP GOING

A picture is a start.
Practice is the rest.

This lesson is a port of an open course. Everything here traces back to it — and the next step is running the code yourself.

Lesson text adapted from AI Engineering from Scratch (Phase 01, Lesson 09) and the Math Foundations Notebook reference build. Interactive figures, the animated surprise hero, exact numeric checks, worked exercise answers and the entropy, KL, softmax, information-gain and perplexity labs are original to this page. Every lab runs in your browser.