Probability, Statistics & Information Theory
A model never knows the answer; it holds a belief about it. This module builds the language for beliefs from scratch: events and random variables, Bayes' rule, the Gaussian and its multivariate cousin, then maximum likelihood, priors and regularization, and finally entropy, cross-entropy and . By the end you'll see why mean squared error and cross-entropy aren't arbitrary choices but the negative log-likelihood of a model, and what the temperature knob on an LLM actually does.
How to use this module
- Watch, then play. Chapters link to the best videos on each idea. Watch, then come back and drag the figure until it feels obvious.
- Questions get harder as you go: Warm-up Practice Think Challenge. Pick one answer, press Check answer, and the worked solution opens.
- Code it: Python runs in your browser and is graded by test cases. The first run downloads Python (internet needed once).
- Your progress is saved in this browser. Tick "mark as done" at the end of each chapter.
Probability basics: outcomes, events and random variables
Watch: Random variables (Khan Academy) Watch: The main ideas behind probability distributions (StatQuest)A probability is a number between 0 and 1 attached to an event, which is just a set of possible outcomes. A random variable turns each outcome into a number, and its distribution says how likely each number is. Everything else in this module is built from these pieces.
Start with something you can do: roll two dice. Before you roll, you can't say what will come up, but you can list everything that could come up. That list is the sample space, usually written . For two dice it has 36 outcomes: (1, 1), (1, 2), …, (6, 6).
An event is any set of outcomes you care about. "The dice sum to 7" is the event . "Doubles" is another. Events are sets, so you can combine them: ("A and B"), ("A or B, or both"), and the complement ("not A").
A probability assigns each event a number, following three rules (Kolmogorov's axioms, though you don't need the name):
- for every event: no negative chances.
- : something happens.
- If and can't both happen (they're disjoint), then .
Everything else follows. The complement rule comes from splitting into and not-. When events can overlap, adding counts the overlap twice, so you subtract it once:
When all outcomes are equally likely (fair dice, a well-shuffled deck), probability is just counting: . Sum to 7 has 6 outcomes out of 36, so .
What does "probability 1/6" even mean? Two readings, both useful. The frequency view: repeat the experiment many times and the fraction of times the event happens settles near 1/6. The belief view: 1/6 measures how confident you should be before rolling. ML uses both: a classifier saying "0.9 cat" is expressing a belief, and we check it against frequencies on real data.
Random variables
A random variable is a rule that turns each outcome into a number. For two dice, = "the sum" maps (2, 5) to 7. The name is misleading: it's not a variable and it's not random; it's a function, and the randomness lives in which outcome happens. Once you have , you can ask about events like or .
For a random variable with a list of possible values (a discrete one), its probability mass function (PMF) says how likely each value is. The PMF of the two-dice sum rises from to and falls back to . The values are never negative and always add to 1. That list of probabilities is the distribution of , and most of this module is about distributions.
Independence
Two events are independent when knowing one happened tells you nothing about the other. In symbols, . Separate dice are independent: . Independence is what lets you multiply, and it's the reason "at least one" questions are easiest through the complement: the chance of at least one 6 in two rolls is .
Worked exampleThree questions about two dice
- Sum = 7: 6 favourable cells of 36, so .
- At least one 6: the complement "no 6" has cells, so . Check by counting: the last row and last column have 6 + 6 cells, minus the shared (6, 6), giving 11 ✓.
- Sum = 7 or doubles: these are disjoint (a double always has an even sum), so . Compare "sum = 8 or doubles": they overlap at (4, 4), so .
Watch outCommon misconceptions
- "After five reds, black is due." The gambler's fallacy. A fair wheel has no memory: independent spins mean the next one is still a fresh draw. Frequencies settle in the long run because the early streak gets diluted, not corrected.
- "Disjoint means independent." Almost the opposite. If and are disjoint and both possible, learning happened tells you definitely didn't, so they are strongly dependent: .
- "P(A or B) = P(A) + P(B)." Only for disjoint events. Otherwise the overlap is counted twice and you can even get answers above 1.
- "A random variable is a random number." It's a fixed function of the outcome. Its randomness is borrowed entirely from the experiment.
In ML & deep learningWhere this shows up
Machine learning treats data as outcomes of a random experiment: each training example is a draw from some unknown distribution over inputs and labels. The standard assumption that examples are i.i.d. (independent and identically distributed) is exactly this chapter's independence, and it's why the loss on a dataset is a sum over examples. A classifier's output layer is a PMF over classes: non-negative numbers that add to 1. Data augmentation, dropout, weight initialisation, shuffling mini-batches: all are random variables you choose on purpose.
Practice (pick one answer per question)
You roll one fair six-sided die. What is the probability the result is even?
- 1/2
- 1/3
- 1/6
- 2/3
The event is {2, 4, 6}: 3 of 6 equally likely outcomes, so .
A spam filter says for an email. What is ?
- 0.7
- 0.3
- 1.3
- It can't be known without more information
Complement rule: . "Spam" and "not spam" split the sample space, so their probabilities add to 1.
Two fair dice. What is ?
- 5/36
- 1/6
- 1/9
- 8/36
The pairs are (2, 6), (3, 5), (4, 4), (5, 3), (6, 2): 5 outcomes of 36. Note (3, 5) and (5, 3) are different outcomes, but (4, 4) appears once.
, and . What is ?
- 0.7
- 0.9
- 0.2
- 0.5
. Adding alone gives 0.9, which counts the overlap twice. (Here , so and also happen to be independent.)
Flip a fair coin 3 times and let = number of heads. What is ?
- 3/8
- 1/3
- 2/3
- 1/4
There are equally likely sequences. Exactly two heads: HHT, HTH, THH, so 3 of 8. ( takes 4 values, but they are not equally likely, which is why 1/4 is wrong.)
Events and are disjoint, with and . Which statement is true?
- They are dependent, because but
- They are independent, because they don't overlap
- They are independent, because
- Nothing can be said without more information
Independence needs . Disjoint means , but . Knowing happened rules out completely, which is about as dependent as events get.
You roll a fair die 4 times. What is the probability of at least one 6?
"At least one" is easiest through the complement. No 6 in 4 independent rolls has probability , so the answer is . Adding four times double-counts runs with several 6s (and would exceed 1 after 7 rolls). The 0.482 option is the complement itself.
Code it (optional: real Python runs in your browser and is graded by test cases)
Conditional probability and Bayes' rule
Watch: Bayes theorem, the geometry of changing beliefs (3Blue1Brown) Watch: The medical test paradox (3Blue1Brown)Conditioning on evidence means zooming in on the part of the world where the evidence is true and re-measuring. Bayes' rule turns "how likely is this evidence if my hypothesis is true?" into "how likely is my hypothesis now that I've seen the evidence?", and the base rate matters enormously.
Learning something changes the odds. The chance a random person has a rare disease is small; the chance given that they tested positive is larger. We write that as , read "probability of sick given positive".
The definition is a zoom: throw away every outcome where the evidence didn't happen, and ask what fraction of what's left is in :
Rearranging gives the multiplication rule , which is how you build probabilities step by step: "the chance of B, then the chance of A once B has happened." Independence, from chapter 1, is the special case : learning doesn't move your belief in .
If some hypotheses cover every possibility without overlapping, the law of total probability adds up the routes to the evidence:
Bayes' rule
The multiplication rule works in both orders, . Divide by and you get Bayes' rule:
- The prior is what you believed before the evidence.
- The likelihood is how well the hypothesis predicts the evidence.
- The posterior is your updated belief.
- The denominator , from the law of total probability, just rescales so the posteriors add to 1.
The cleanest way to see it is to imagine a population. Of 1000 people, put the ones with the hypothesis on one side; the evidence picks out a slice of each side; the posterior is the fraction of the evidence slice that sits on the hypothesis side. That's what the figure below draws.
The medical test paradox
A disease affects 1% of people. A test catches 90% of real cases (its sensitivity, ) and correctly clears 95% of healthy people (its specificity, ). You test positive. How worried should you be? Most people, including many doctors in surveys, guess about 90%. The real answer is about 15%. In a town of 10 000: 100 are sick and 90 of them test positive; 9900 are healthy and 5% of them, 495 people, test positive anyway. Of the 585 positives, only 90 are sick: .
The test is good, but the healthy group is so much bigger that its small error rate still produces most of the positives. That's base-rate neglect: ignoring the prior.
The odds form makes repeated updates easy. Odds are . Each piece of evidence multiplies the odds by its likelihood ratio (Bayes factor), . For a positive test that's : prior odds 1 : 99 become 18 : 99, which is . A second, independent positive test multiplies by 18 again: 324 : 99, about 77%.
Worked exampleA spam word
40% of your email is spam. The word "winner" appears in 20% of spam emails and 1% of real ones. An email contains "winner". Is it spam?
- Prior: , .
- Likelihoods: , .
- Total: .
- Posterior: .
Odds check: prior odds 0.4 : 0.6, likelihood ratio 20, posterior odds 8 : 0.6, so ✓. A naive Bayes spam filter does exactly this for every word, assuming the words are independent given the class, and adds up the log likelihood ratios.
Watch outCommon misconceptions
- "P(A | B) and P(B | A) are about the same." They can be wildly different. Most professional basketball players are tall; very few tall people are professional basketball players. Swapping them is called the prosecutor's fallacy.
- "The test is 95% accurate, so a positive means 95% likely sick." That ignores the prior. Accuracy describes ; you want .
- "Conditioning makes events independent." It can create or destroy dependence. Two independent causes of an alarm become dependent once you know the alarm went off ("explaining away").
In ML & deep learningWhere this shows up
A classifier is trying to estimate the posterior : the probability of each label given the input. Generative classifiers such as naive Bayes model and and apply Bayes' rule; discriminative ones like logistic regression and neural networks learn directly. Base rates matter in practice too: with 1% fraud, a model that flags everything at 95% specificity buries the real cases under false alarms, which is why we look at precision (that's , a posterior!) and not just accuracy. Chapter 9 uses Bayes' rule on a model's parameters, which is where regularization comes from.
Practice (pick one answer per question)
and . What is ?
- 0.3
- 0.048
- 0.12
- 0.52
. Among the outcomes where happens, 30% also have .
Which quantity equals ?
That's the multiplication rule: the chance of , times the chance of once has happened, is the chance of both.
A factory has two machines. Machine A makes 60% of the parts and 2% of its parts are defective; machine B makes 40% and 5% of its parts are defective. What fraction of all parts is defective?
- 0.032
- 0.035
- 0.07
- 0.020
Total probability: . (0.035 is the unweighted average of 2% and 5%, which ignores how many parts each machine makes.)
Same factory. A part is defective. What is the probability it came from machine B?
- 0.625
- 0.4
- 0.05
- 0.375
Bayes: . The defect is evidence for B, so the 40% prior rises to 62.5%. (0.375 is the posterior for A.)
A bag holds two fair coins and one coin with heads on both sides. You pick a coin at random, flip it, and see heads. What is the probability you picked the two-headed coin?
- 1/2
- 1/3
- 2/3
- 1
. Then . Heads is twice as likely from the trick coin, which doubles its odds from 1 : 2 to 1 : 1.
A disease affects 2% of people. A test has sensitivity 99% and specificity 99%. You test positive. About how likely are you to be sick?
- About 67%
- About 99%
- About 2%
- About 50%
Per 10 000 people: 200 sick, 198 test positive; 9800 healthy, 98 test positive. . Even a 99% test leaves a one-in-three chance of a false alarm when the condition is rare.
The prior is 1%, and a positive test has likelihood ratio . You take two independent tests and both are positive. What is the posterior probability of being sick?
- About 0.77
- About 0.15
- About 0.36
- About 0.97
Odds form: prior odds . Each positive multiplies the odds by 18, so two give , and the odds become . As a probability, . (0.15 is the answer after one test; 0.36 doubles it, which is not how evidence combines.)
Code it (optional: real Python runs in your browser and is graded by test cases)
Discrete distributions: Bernoulli, binomial and categorical
Watch: Binomial distributions | Probabilities of probabilities (3Blue1Brown) Watch: The binomial distribution, clearly explained (StatQuest)Three distributions cover most of the discrete randomness in ML. A Bernoulli is one yes/no trial, a binomial counts the yeses in n independent trials, and a categorical picks one of K classes. Every classifier outputs one of these.
Bernoulli: one coin flip
A Bernoulli random variable takes the value 1 ("success") with probability and 0 with probability . Click or no click, spam or not, the pixel is on or off. One compact formula covers both cases:
Plug in and you get ; plug in and you get . This trick of using the exponent as a switch looks like a gimmick now, but its logarithm, , is the binary cross-entropy loss you'll meet in chapter 12.
Binomial: counting successes
Repeat a Bernoulli trial times independently and count the successes. That count is binomial, . Any particular sequence with successes, like SSF…S, has probability by independence, and there are such sequences, so
Its mean is and its variance is (chapter 4 shows why: a binomial is a sum of independent Bernoullis, and means and variances of independent pieces add). As grows the histogram gets wider in absolute terms, about , but narrower relative to , and it starts to look like a bell curve. That's the central limit theorem knocking (chapter 6).
3Blue1Brown's video asks a lovely question with this: a seller with 10 reviews, all positive, versus one with 48 positive out of 50. Which is better? The binomial tells you how likely each record is for each possible true rate , which turns the question around into "what should I believe about ?" We'll answer that in chapters 8 and 9.
Categorical: one of K classes
A categorical distribution generalises the Bernoulli to outcomes: class has probability , with and . Writing the outcome as a one-hot vector (all zeros except a 1 in position ) gives the same exponent trick:
Only the factor for the actual class survives; all the others are raised to the power 0. The count version, "how many of each class in draws", is the multinomial, which is to the categorical what the binomial is to the Bernoulli.
Worked exampleA model answers 10 questions
A model gets each question right with probability 0.95, independently. Let be the number right out of 10.
- . Even a 95% model gets a perfect score only 60% of the time.
- .
- .
- Mean , variance , standard deviation .
Watch outCommon misconceptions
- "The most likely count is the only likely count." For Binomial(100, 0.5), the single most likely value, 50, has probability only about 8%. Each exact value is unlikely; ranges are what carry the probability.
- "Binomial works for any repeated trials." It needs a fixed , independent trials and the same every time. Drawing cards without replacement breaks independence.
- "Categorical labels are numbers, so class 3 is 'more' than class 1." The indices are names. That's why we one-hot encode them rather than feeding 1, 2, 3 to a model as if they were measurements.
In ML & deep learningWhere this shows up
A binary classifier with a sigmoid output is a Bernoulli model: it outputs . A multi-class classifier with a softmax output is a categorical model: it outputs . A language model is a categorical distribution over a vocabulary of maybe 100 000 tokens, produced once per position. Dropout zeroes each unit with an independent Bernoulli draw. And the binomial tells you how much an accuracy measured on test examples can wobble: its standard deviation is , so 1000 test examples pin a 90% accuracy down only to about ±1%.
Practice (pick one answer per question)
is Bernoulli with . What is ?
- 0.7
- 0.3
- 0
- 0.21
. From the formula: .
A categorical distribution over 4 classes has , , . What is ?
- 0.4
- 0.25
- 0.6
- It can be any number between 0 and 1
The probabilities must add to 1: .
. What is ?
- 0.375
- 0.5
- 0.25
- 0.0625
. (0.0625 is one particular sequence, forgetting the 6 ways to arrange it.)
. What are its mean and variance?
- 5 and 3.75
- 5 and 5
- 5 and 0.1875
- 0.25 and 3.75
Mean ; variance . (0.1875 is the variance of a single trial.)
Each incoming email is spam with probability 0.1, independently. In a batch of 10 emails, what is the probability that none is spam?
"None spam" means all 10 independent emails are not spam: . It's the term of Binomial(10, 0.1).
For which is the variance of a Bernoulli() largest, and what is that variance?
- , variance 0.25
- , variance 1
- , variance 0.5
- Every gives the same variance
is a downward parabola with its peak at , where it equals 0.25. At or the outcome is certain and the variance is 0: maximum uncertainty is a fair coin.
A model gets each of 5 questions right with probability 0.8, independently. What is the probability it gets at least 4 right?
- 0.737
- 0.410
- 0.328
- 0.800
, and . Add them: . The other options are each piece on its own, or the per-question rate.
Code it (optional: real Python runs in your browser and is graded by test cases)
Expectation, variance and covariance
Watch: Expected values, main ideas (StatQuest) Watch: Covariance, clearly explained (StatQuest)The expectation is a distribution's balance point, the variance measures how far it spreads from that point, and the covariance measures whether two random variables move together. These three numbers summarise most of what ML needs from a distribution.
Expectation: the balance point
The expected value (or mean) of a discrete random variable is the probability-weighted average of its values:
Picture the PMF as weights hung on a ruler at positions . The expectation is where you'd put your finger to balance it. It need not be a value can actually take: a fair die has . And it's the long-run average: roll many times and the average of your rolls settles near 3.5.
The single most useful fact about expectation is linearity:
and it holds always, whether or not and are independent. For example, a Binomial() count is a sum of Bernoullis each with mean , so its mean is with no algebra at all. For a function of , weight the function's values: . Careful: in general ; for instance .
Variance: the spread
The variance is the expected squared distance from the mean, and the standard deviation is its square root, which brings it back to the original units:
Shifting doesn't change spread and scaling multiplies it: . Notice the square: doubling quadruples its variance and doubles its standard deviation.
Covariance and correlation: moving together
For two random variables, the covariance asks: when is above its mean, is usually above its mean too?
Positive: they rise together. Negative: one up, the other down. Its size depends on units, so we often divide by both standard deviations to get the correlation , which always lies between −1 and 1. Covariance also fixes the variance of a sum:
If and are independent their covariance is 0, so variances simply add. The converse is false: zero covariance only rules out a straight-line relationship.
Worked exampleA fair die
- .
- .
- , so .
- The total of two dice: , and since the dice are independent .
- The average of two dice, : mean 3.5, variance . Averaging keeps the mean and shrinks the spread, the idea behind chapter 6.
Watch outCommon misconceptions
- "The expected value is the most likely value." That's the mode. A die's expected value, 3.5, is impossible to roll.
- "Var(X − Y) = Var(X) − Var(Y)." Variances of independent variables add even when you subtract: , because . Uncertainty never cancels by subtraction.
- "Zero covariance means independent." Take uniform on {−1, 0, 1} and . is completely determined by , yet .
In ML & deep learningWhere this shows up
The training loss is an expectation, over the data distribution, and a mini-batch average is an estimate of it; the stochastic gradient is an unbiased estimate of the true gradient because expectation is linear. Variance explains why bigger batches give smoother training (the batch-mean's variance falls like ). Weight initialisation schemes (Xavier, He) are chosen so each layer's output has about the same variance as its input. Batch norm and layer norm subtract a mean and divide by a standard deviation. And the covariance matrix of your features, coming in chapter 7, is the starting point of PCA.
Practice (pick one answer per question)
is 0 with probability 0.5 and 10 with probability 0.5. What is ?
- 5
- 10
- 0
- 0.5
, a value never takes.
. What is ?
- 14
- 12
- 36
- It depends on the distribution of
Linearity: . No other information about is needed.
. What is ?
- 12
- 6
- 11
- 17
. Adding 5 shifts the distribution without changing its spread; the factor 2 is squared.
takes values 1, 2, 3 with probabilities 0.2, 0.5, 0.3. What is ?
- 0.49
- 2.1
- 4.9
- 0.7
and . So , and .
, and . What is ?
- 7
- 13
- 10
- 19
. Negative covariance means the two tend to cancel, so their sum varies less than either alone would suggest. (13 forgets the covariance; 19 adds it with the wrong sign.)
is uniform on {−1, 0, 1} and . Which is true?
- , but and are dependent
- , so they are independent
- , because grows with
- , because is a function of
and , so the covariance is 0. But knowing tells you exactly, so they're as dependent as can be. Covariance only sees straight-line trends, and this relationship is a symmetric U.
You average independent measurements, each with standard deviation 2. What is the standard deviation of the average?
- 0.2
- 0.02
- 2
- 0.04
The sum has variance ; dividing by 100 divides variance by , giving . The standard deviation is . (0.04 is the variance, not the standard deviation.)
Code it (optional: real Python runs in your browser and is graded by test cases)
Continuous distributions and the Gaussian
Watch: Why π is in the normal distribution (3Blue1Brown) Watch: The normal distribution, clearly explained (StatQuest)For a continuous quantity, single values have probability zero; probability lives in areas under a density curve. The Gaussian (normal) density, a bell set by a centre μ and a width σ, is the most important of them all.
How likely is someone to be exactly 170 cm tall, to infinitely many decimal places? Zero. There are uncountably many possible heights, and if each had a positive probability they'd add to infinity. So for a continuous random variable we stop asking about single values and ask about ranges.
A probability density function (PDF) is a curve whose area gives probability:
The density itself is not a probability. It's probability per unit length, so is roughly the probability of landing in a tiny window of width around . Densities can be bigger than 1 (a narrow spike must be tall to have area 1); they just can't be negative. The cumulative distribution function is the running area, and .
Expectation and variance work as before, with integrals in place of sums: . The simplest example is the uniform distribution on : a flat density of height , mean , variance .
The Gaussian
The Gaussian or normal distribution has density
Read it from the inside out. measures how many standard deviations is from the centre. Squaring and negating gives a downward parabola, and turns that into a bell that falls off very fast: 3σ out, the density is of its peak. The front factor is just whatever makes the total area 1.
Where does π come from? The area under is . 3Blue1Brown's video gives a beautiful reason: the 2D function depends only on the distance from the origin, so it's perfectly round, and circles bring π with them. The Gaussian is the only shape where "independent in x and y" and "the same in every direction" both hold.
Some numbers worth knowing (the 68–95–99.7 rule): a Gaussian puts about 68.3% of its probability within 1σ of the mean, 95.4% within 2σ, and 99.7% within 3σ. To use them for any Gaussian, standardise: is , the standard normal.
Worked exampleHeights
Suppose adult heights are roughly in cm.
- : that's , so about 0.683.
- : . Half of the 4.6% outside ±2σ is above, so about 0.023.
- : , and a table or calculator gives 0.067.
- The peak density is per cm: about a 4% chance of landing within a 1 cm window around 170.
Watch outCommon misconceptions
- "f(x) is the probability that X = x." It's a density. for every single ; only areas are probabilities.
- "A density can't be above 1." Uniform on [0, 0.5] has density 2 everywhere on that interval. Its area is 1.
- "Everything is normally distributed." Incomes, file sizes and word frequencies have long, heavy tails where extreme values are far more common than a Gaussian allows. Assuming normality there badly underestimates the extremes.
In ML & deep learningWhere this shows up
Gaussians are everywhere in ML. Weights are initialised with Gaussian noise. Regression models usually assume Gaussian noise around their prediction, and chapter 12 shows that this one assumption is mean squared error. VAEs and diffusion models (the engines behind many image generators) work by adding Gaussian noise and learning to remove it, and the "reparameterisation trick" writes a Gaussian sample as with so gradients can flow through and . Standardising features to z-scores, , is a standard preprocessing step.
Practice (pick one answer per question)
is uniform on [0, 4]. What is the height of its density?
- 0.25
- 4
- 1
- 0.5
A flat density over a length-4 interval needs height so the area is 1.
is a continuous random variable. What is ?
- 0
- It depends on the distribution
- , the area to its left
The probability is the area over a single point, which has zero width, so it's 0 for every continuous distribution. is a density, and is an area to the left of 2.5, not a single point.
. Approximately what is ?
- 0.683
- 0.954
- 0.5
- 0.997
Within one standard deviation of the mean: about 68.3%. (95.4% is within 2σ, 99.7% within 3σ.)
is uniform on [0, 0.5]. What is its density on that interval, and is that allowed?
- 2, and yes: densities can exceed 1 as long as the area is 1
- 0.5, because a density can't exceed 1
- 2, but that's not a valid density
- 1, because all uniform densities have height 1
Height × width = area: . Densities are probability per unit length, so they can be as large as they like over short intervals.
IQ-style scores are . About what fraction score above 130?
- About 2.3%
- About 5%
- About 16%
- About 0.1%
. About 95.4% is within ±2σ, leaving 4.6% in the two tails, half of it above: about 2.3%. (16% is the tail beyond 1σ; 0.1% is beyond 3σ.)
What is the variance of the uniform distribution on [0, 6]?
- 3
- 6
- 36
- 12
. Check with ✓.
What is the peak height of the density, at ?
- About 3.99
- About 0.399
- 1, since nothing can be more likely than certain
- About 0.04
. A narrow bell must be tall so its area stays 1, which is another case of a density above 1. (0.399 is the peak of the standard normal.)
Code it (optional: real Python runs in your browser and is graded by test cases)
Sums of random variables, convolution and the central limit theorem
Watch: But what is the Central Limit Theorem? (3Blue1Brown) Watch: Convolutions | Why X+Y in probability is a beautiful mess (3Blue1Brown) Watch: A pretty reason why Gaussian + Gaussian = Gaussian (3Blue1Brown)The distribution of a sum of independent random variables is the convolution of their distributions. Means add and variances add, and if you add up many independent pieces, the result looks Gaussian almost no matter what the pieces looked like. That's the central limit theorem, and it's why bell curves are everywhere.
Convolution: the distribution of X + Y
Roll two dice. To get a total of , the first must show some and the second . Add up every way that can happen:
This operation on two lists of probabilities is called convolution, written . One way to picture it: flip one distribution around, slide it along the other, and at each offset multiply the overlapping entries and add. For two dice it turns two flat distributions into the triangle that peaks at 7. For continuous variables, the sum becomes an integral: .
Convolution is messy in general, but two summaries behave beautifully for independent and :
Standard deviations do not add; they combine like the sides of a right triangle, . And one family is closed under addition: the sum of independent Gaussians is exactly Gaussian, . 3Blue1Brown's "pretty reason" uses the round 2D bell from chapter 5: the event is a line, and rotating the round bell doesn't change it.
The central limit theorem
Now add up many independent copies of the same random variable, each with mean and finite variance , and look at their average . From the rules above, and . That's the law of large numbers in action: the average homes in on , with typical error .
The central limit theorem (CLT) says something much stronger about the shape: as grows,
whatever the original distribution looked like: skewed, lumpy, two-humped, or just 0s and 1s. Repeated convolution smooths every shape into a bell. That's why measurement errors, test scores and heights, each the sum of many small independent effects, so often look Gaussian.
The fine print: the pieces need to be independent (or not too dependent), and their variance must be finite. Some heavy-tailed distributions, like the Cauchy, never settle down: averaging a thousand Cauchy draws gives another Cauchy, just as wild as one draw.
Worked exampleFrom two dice to a hundred
- Convolution by hand: .
- One die: , .
- Average of 100 dice: mean 3.5, variance , standard deviation .
- CLT estimate: is about , since . One die is flat, but the average of 100 is a tight bell.
Watch outCommon misconceptions
- "The CLT says the data become normal if I collect enough." No: your individual measurements keep whatever shape they have. It's the average (or sum) of many of them whose distribution becomes bell-shaped.
- "Standard deviations add." Variances add (for independent variables). The sum of two independent variables with σ = 3 and σ = 4 has σ = 5, not 7.
- "30 samples is always enough." It depends on the shape. Strongly skewed or heavy-tailed sources need far more, and infinite-variance ones never converge.
In ML & deep learningWhere this shows up
A mini-batch gradient is an average of per-example gradients, so by the CLT it's roughly the true gradient plus Gaussian noise with variance shrinking like ; that's the usual mental model for SGD noise. Error bars on a test-set accuracy come from the CLT too. A neuron's pre-activation adds many roughly independent terms, so at initialisation it's approximately Gaussian, which is why initialisation schemes only need to control its variance (and why very wide networks behave like "Gaussian processes"). Convolution itself, flip-slide-multiply-add, is the very operation that gives convolutional neural networks their name.
Practice (pick one answer per question)
and are independent with and . What is ?
- 5
- 6
- It depends on their variances
Means always add: (this doesn't even need independence).
Independent and have and . What is the standard deviation of ?
- 3
- 5
- 2
Variances add: , so . Adding the standard deviations (1 + 2 = 3) is the classic mistake.
is uniform on {0, 1} and is uniform on {0, 1, 2}, independent. What is ?
- 1/3
- 1/6
- 1/2
- 1/4
The ways are (0, 1) and (1, 0), each with probability . Total: .
and are independent (the second number is the variance). What is the distribution of ?
- Not Gaussian: a sum of Gaussians is a convolution
Independent Gaussians add to a Gaussian, with means adding (3) and variances adding (13). would come from adding the standard deviations 2 + 3 and squaring.
You flip a fair coin 100 times. What is the standard deviation of the number of heads?
- 5
- 25
- 10
- 0.5
Each flip is Bernoulli(0.5) with variance 0.25; 100 independent flips have variance 25, so . By the CLT the count is about : 95% of the time between 40 and 60.
Individual measurements have . What is the standard deviation of the mean of 25 of them?
- 2
- 0.4
- 10
- 4
. (0.4 is , dividing by instead of ; 4 is the variance.)
Your validation accuracy estimate is too noisy. To cut its standard error in half, how many more validation examples do you need?
- 4 times as many
- 2 times as many
- times as many
- 8 times as many
The standard error is . Halving it needs to double, so must quadruple. Precision is expensive: each extra decimal place costs 100× the data.
Code it (optional: real Python runs in your browser and is graded by test cases)
The multivariate Gaussian and covariance matrices
Watch: Multivariate Gaussian distributions (Alexander Ihler) Watch: Covariance, clearly explained (StatQuest)A Gaussian in many dimensions is set by a mean vector and a covariance matrix. Its contours are ellipses (ellipsoids in higher dimensions) whose axes point along the eigenvectors of the covariance matrix, with lengths given by the square roots of its eigenvalues.
Real data has many features at once: a house has a size, an age and a price; an image has thousands of pixels. Stack random variables into a random vector . Its centre is the mean vector , and its shape is captured by the covariance matrix, the table of every pairwise covariance:
The diagonal holds the variances ; the off-diagonal entries say how pairs move together. is always symmetric () and positive semi-definite: for any direction , the variance of the projection is . That last formula is worth remembering: the covariance matrix tells you the variance in every direction.
The density
The multivariate Gaussian has density
It's the 1D formula with each piece upgraded: becomes the quadratic form , whose square root is the Mahalanobis distance, "how many standard deviations away, accounting for the shape". And becomes : from Linear Algebra, the determinant is how much stretches volume.
Ellipses are eigenvectors
Points of equal density have equal Mahalanobis distance, so the contours are the curves . Which shape is that? Because is symmetric, the spectral theorem (Linear Algebra, chapter 14) says it has perpendicular eigenvectors with eigenvalues :
In the eigenvector coordinates, is just diagonal: the data is spread with variance along and along , independently. So the contours are ellipses with axes along the eigenvectors and semi-axis lengths (times ). The biggest eigenvalue's eigenvector is the direction of greatest variance; that's exactly what PCA finds.
This also tells you how to sample: draw independent standard normals , then set for any with , because a linear map transforms covariance as . The figure uses : stretch a round cloud along the eigenvectors. In code people use the Cholesky factor.
Worked exampleΣ = [[3, 1], [1, 3]]
- Variances 3 and 3, covariance 1, so the correlation is .
- Eigenvalues: trace 6, determinant , so gives , .
- Eigenvectors: (check: ✓) and .
- So the cloud is tilted at 45°, with standard deviation along the diagonal and across it. The variance along is , between the two extremes, as it must be.
Watch outCommon misconceptions
- "Any symmetric matrix can be a covariance matrix." It must also be positive semi-definite. [[1, 2], [2, 1]] has eigenvalue −1, which would mean a direction with negative variance.
- "Uncorrelated features are independent." True for jointly Gaussian variables (diagonal Σ means the density factors), but false in general, as chapter 4 showed.
- "Euclidean distance is the natural distance." In a stretched cloud, a point 2 units along the long axis can be more typical than one 1 unit along the short axis. Mahalanobis distance accounts for that.
In ML & deep learningWhere this shows up
PCA is literally the eigendecomposition of the data's covariance matrix: keep the top eigenvectors, the directions of greatest variance. Whitening transforms data so that its covariance becomes . Gaussian mixture models, Gaussian discriminant analysis and Kalman filters all carry around mean vectors and covariance matrices. Gaussian processes put a multivariate Gaussian over function values. VAEs use diagonal-covariance Gaussians in their latent space, and the Adam optimiser can be seen as a cheap diagonal estimate of gradient scale. And the "" sampling trick is exactly the reparameterisation trick from chapter 5 in many dimensions.
Practice (pick one answer per question)
. What is the standard deviation of ?
- 2
- 4
- 1
- 16
The diagonal entry is the variance, 4, so the standard deviation is .
What do the off-diagonal entries of a covariance matrix tell you?
- How each pair of features varies together
- The variance of each feature
- The mean of each feature
- The eigenvalues of the matrix
for . The diagonal holds the variances.
. What are its eigenvalues, and along which direction is the ellipse longest?
- 3 and 1; along (1, 1)
- 3 and 1; along (1, −1)
- 2 and 2; it's a circle
- 2 and 1; along (1, 0)
and , so the eigenvalues are 3 and 1. The larger one belongs to (1, 1): positive covariance tilts the cloud up and to the right.
. What is the correlation between and ?
- 1/3
- 2
- 2/13
- 1/18
.
in 2D and with . What is ?
. Rows of are (2, 0) and (1, 1): their dot products give . ( gives the second option, which is the wrong order.)
Which of these cannot be a covariance matrix?
[[1, 2], [2, 1]] has determinant −3, so one eigenvalue is negative (they're 3 and −1): the direction (1, −1) would have variance −1. Equivalently, the implied correlation is above 1. The others are positive semi-definite (the diagonal one is a flat, degenerate Gaussian, which is allowed).
With and , what is the Mahalanobis distance of the point (2, 1)?
- 2
, so the distance is . The point is 1σ out in each direction. Its Euclidean distance is , but 2 units along the wide axis is only one standard deviation.
Code it (optional: real Python runs in your browser and is graded by test cases)
Maximum likelihood estimation
Watch: Maximum likelihood, clearly explained (StatQuest) Watch: Probability is not likelihood (StatQuest) Watch: Maximum likelihood for the normal distribution (StatQuest)The likelihood turns the question around: instead of "how probable is this data under these parameters?", it asks "which parameters make this data most probable?" Maximising it, or equivalently minimising the negative log-likelihood, is how almost every ML model is trained.
So far we've had a distribution and asked about data. In practice it's the other way round: you have data and you want the distribution. Flip a coin of unknown bias ten times and see 7 heads. What's your best guess for ?
For any candidate , the probability of exactly this sequence of flips is . Read as a function of with the data held fixed, that's the likelihood:
The product comes from independence (chapter 1). The maximum likelihood estimate (MLE) is the that makes the observed data most probable. For the coin you can see on the figure that peaks at 0.7.
Important: is not a probability distribution over . It doesn't integrate to 1 over (here the area is ), and it doesn't tell you "the probability that ". It only ranks parameter values by how well they explain the data. Turning it into beliefs about needs a prior: that's chapter 9.
Take the log
Products of many small numbers are awful to work with: probabilities of about 0.5 multiply to , on the edge of what a computer can store. So we take logs. The log is increasing, so it doesn't move the peak, and it turns the product into a sum:
ML libraries minimise, so they use the negative log-likelihood (NLL), . Minimising NLL and maximising likelihood find the same .
Two classic answers
Coin. With heads and tails, . Setting the derivative to zero, , gives
the fraction of heads, as you'd hope.
Gaussian. For data from , each point contributes . Maximising over means minimising , a sum of squared errors, which is solved by the sample mean. Then maximising over gives the average squared deviation:
Notice the , not the you might have met in statistics. The MLE variance is slightly biased low (it measures spread around the data's own mean, which is always a bit too close to the data); the version corrects that. For large the difference vanishes.
Worked example7 heads in 10 flips
- .
- .
- Ratio: . The data favour over a fair coin, but only by a factor of about 2: ten flips aren't much evidence.
- NLL at the peak: nats.
Watch outCommon misconceptions
- "The likelihood is the probability of the parameter." It's the probability of the data, viewed as a function of the parameter. It doesn't add up to 1 over θ.
- "Maximum likelihood is always sensible." With little data it overfits: 3 heads in 3 flips gives , a coin that can never land tails. A word that never appeared in training gets probability 0. Priors (chapter 9) fix this.
- "Taking the log changes the answer." The log is strictly increasing, so the peak is in the same place. It only changes the curve's shape, making it easier to optimise and to compute without underflow.
In ML & deep learningWhere this shows up
Training a neural network is (almost always) maximum likelihood. The network with weights defines a distribution , and the loss is the average NLL of the training labels: . Gradient descent then hunts for the MLE. Chapter 12 shows that choosing the distribution fixes the loss: Gaussian gives mean squared error, categorical gives cross-entropy. Language models are trained by maximising the likelihood of the next token, and the "loss" printed during LLM training is the per-token NLL in nats.
Practice (pick one answer per question)
A coin lands heads 12 times in 20 flips. What is the MLE of ?
- 0.6
- 0.5
- 12
- 0.4
.
Why do we usually maximise the log-likelihood instead of the likelihood?
- It turns a product into a sum, avoids numerical underflow, and has the same maximiser
- It gives a different, more accurate answer
- The likelihood can be negative, the log can't
- The log-likelihood is a probability distribution over the parameters
The log is increasing, so the argmax is unchanged. Sums are easier to differentiate and don't underflow the way products of thousands of small probabilities do.
You fit a Gaussian by maximum likelihood to the data 2, 4, 9. What is ?
- 5
- 4
- 15
- 4.5
The MLE of the mean is the sample mean: . (4 is the median.)
Same data, 2, 4, 9. What is the MLE of the variance, ?
- 26/3 ≈ 8.67
- 13
- 26
Deviations from 5 are −3, −1, 4; squares 9, 1, 16; sum 26. The MLE divides by : . (13 divides by ; 2.94 is .)
With 7 heads in 10 flips, how many times more likely is the data under than under ?
- About 2.28
- 1.4
- About 0.44
- About 7
. (1.4 is just 0.7/0.5; 0.44 is the ratio upside down.)
A word appears 0 times in 10 000 training words. What does maximum likelihood estimate for its probability, and what's the problem?
- 0, so any text containing the word gets probability 0 (infinite NLL)
- 1/10 000, which is a fine estimate
- The MLE doesn't exist when a count is 0
- 0, which is harmless because the word is rare
The MLE of a categorical probability is count / total = 0. Then any test sentence containing the word has likelihood 0 and NLL . That's maximum likelihood overfitting; smoothing, which is a prior, fixes it.
Waiting times are modelled as exponential with density for . You observe 1, 2 and 3 minutes. What is the MLE of ?
- 0.5 per minute
- 2 per minute
- 6 per minute
- 3 per minute
. Setting gives : one over the average waiting time of 2 minutes. (2 is the average itself.)
Code it (optional: real Python runs in your browser and is graded by test cases)
Priors, MAP estimation and regularization
Watch: Bayesian linear regression (ritvikmath) Watch: Regularization part 1: ridge (L2) regression (StatQuest) Watch: Regularization part 2: lasso (L1) regression (StatQuest)Apply Bayes' rule to a model's parameters: posterior ∝ likelihood × prior. The most probable parameters under the posterior (the MAP estimate) minimise the negative log-likelihood plus a penalty, and that penalty is regularization. A Gaussian prior gives L2 (weight decay); a Laplace prior gives L1 (sparsity).
Maximum likelihood trusts the data completely. Three heads in three flips, and it declares the coin can never land tails. You know better: most coins are close to fair. That knowledge, held before seeing the data, is a prior, and chapter 2 already told us how to combine it with evidence. Treat the parameter itself as uncertain and apply Bayes' rule:
The denominator doesn't depend on , so for finding the best we can ignore it. The maximum a posteriori (MAP) estimate is the peak of the posterior. Take logs and negate, just as for the MLE:
That's the whole idea: MAP = maximum likelihood + a penalty, and the penalty is the negative log of the prior.
A coin with a prior
A convenient prior for a probability is the Beta(a, b) distribution, with density proportional to . Multiply by the likelihood and the posterior has the same form, : it's Beta(). So the prior acts like imaginary heads and imaginary tails added to the data, and
With the flat prior Beta(1, 1), MAP equals the MLE. With Beta(1, 1) the posterior mean is , Laplace's "rule of succession", which is a principled answer to 3Blue1Brown's review puzzle from chapter 3: 10 out of 10 positive reviews gives , while 48 out of 50 gives .
As data piles up, and swamp and , and MAP converges to the MLE. Priors matter most when data is scarce, exactly when the MLE is least trustworthy.
Regularization is a prior
Now the payoff for ML. Take a linear model with Gaussian noise, with . The NLL is plus a constant: squared error (chapter 12 says more).
- Gaussian prior : . Multiply everything by and MAP minimises That's ridge regression, or L2 regularization, called weight decay in deep learning. A tighter prior (smaller ) means a bigger .
- Laplace prior : , giving the lasso or L1 regularization, .
Why does L1 produce sparse weights (many exactly zero) while L2 doesn't? The Laplace prior has a sharp peak at 0, so its penalty has a kink there. In one dimension, minimising gives : shrunk, but never zero unless is. Minimising gives , the soft threshold: whenever the data's pull is weaker than , the kink wins and snaps to exactly 0.
Worked exampleThree heads in three flips
- MLE: . Absurdly confident.
- Prior Beta(2, 2), gently favouring fairness (like 1 imaginary head and 1 imaginary tail): MAP .
- Posterior mean .
- After 300 heads in 300 flips, MAP : the data has overwhelmed the prior.
Watch outCommon misconceptions
- "Regularization is just a hack against overfitting." It's a statement of belief: "before seeing data, I think small weights are more likely." That view tells you how to choose it and what it means.
- "MAP is fully Bayesian." MAP keeps only the posterior's peak. A fully Bayesian answer keeps the whole posterior, and with it the uncertainty, and averages predictions over it.
- "L1 and L2 do the same thing with different numbers." L2 shrinks every weight proportionally; L1 subtracts a fixed amount and zeroes out small weights, which performs feature selection.
In ML & deep learningWhere this shows up
Weight decay in AdamW and SGD is a Gaussian prior on the weights. Lasso is used for sparse, interpretable models and feature selection. Label smoothing and add-one (Laplace) smoothing in n-gram language models are priors that stop the model from putting probability 0 on anything. Early stopping, dropout and data augmentation act as regularizers too, though less directly as priors. Fully Bayesian ideas show up in uncertainty estimation, Bayesian optimisation for hyperparameter search, and in the KL term of a VAE, which pulls the posterior over latents toward a Gaussian prior (chapter 11).
Practice (pick one answer per question)
Up to a constant, the posterior over parameters is proportional to…
- likelihood × prior
- likelihood + prior
- likelihood ÷ prior
- the likelihood alone
Bayes' rule: . In logs this becomes a sum, which is where "loss + penalty" comes from.
With a completely flat prior, the MAP estimate equals…
- the MLE
- the prior mean
- 0
- the posterior mean
A flat prior adds a constant to the log-posterior, which doesn't move the peak, so MAP = MLE.
Prior Beta(3, 3), data 8 heads and 2 tails. What is the MAP estimate of ?
- 10/14 ≈ 0.714
- 0.8
- 11/16 ≈ 0.688
- 0.5
. (0.8 is the MLE; 11/16 is the posterior mean.)
Adding to a squared-error loss corresponds to which prior on the weights?
- A zero-mean Gaussian
- A Laplace distribution
- A uniform distribution
- No prior: it's just a penalty
of a Gaussian density is a quadratic, + const, so a Gaussian prior gives the L2 penalty (ridge / weight decay).
You want a model where most weights are exactly zero. Which prior should you put on the weights?
- Laplace, giving an L1 penalty
- Gaussian, giving an L2 penalty
- A very wide Gaussian
- A flat prior
The Laplace prior's penalty has a kink at 0, so small weights get snapped exactly to 0 (soft thresholding). An L2 penalty is smooth at 0 and only shrinks weights proportionally.
Minimise with . What is ?
- 1
- 1.5
- 3
- 0
Derivative: , so . L2 shrinks by the factor .
Minimise with . What is ?
- 0
- 0.2
- −0.1
- 0.4
For the derivative is , zero at , which isn't positive, so there's no minimum with . Similarly none with . So the minimum is at the kink, . Soft threshold: . (−0.1 is what you get by ignoring the kink.)
Code it (optional: real Python runs in your browser and is graded by test cases)
Entropy and information
Watch: Solving Wordle using information theory (3Blue1Brown) Watch: Entropy (for data science), clearly explained (StatQuest)The information in an event is how surprising it is, −log₂ p bits. Entropy is the average surprise of a distribution: how many yes/no questions you need, on average, to pin down the outcome. It's largest when everything is equally likely and zero when the outcome is certain.
Some news tells you a lot, some tells you almost nothing. "The sun rose today" carries no information; "it snowed in the Sahara" carries a lot. Claude Shannon's insight in 1948 was to measure information by surprise: rarer events are more informative. The information content (or surprisal) of an outcome with probability is
Why the log? Because information from independent events should add: two independent coin flips carry twice the information of one, while their probabilities multiply, . The log turns multiplication into addition: bits. A fair coin flip is 1 bit, an event with probability 1/8 is 3 bits, and a certain event is 0 bits.
Another way to see it: an outcome with probability is like one of equally likely options, and you'd need yes/no questions, each halving the options, to identify it.
Entropy
Entropy is the expected information, the average surprise you get per draw from a distribution:
(Outcomes with contribute 0, since they never happen.) Entropy measures uncertainty:
- It's 0 when one outcome is certain: no surprise ever.
- It's at most for outcomes, reached only by the uniform distribution: maximum uncertainty.
- For a coin with bias , , which peaks at 1 bit for a fair coin and drops to 0 at or 1.
Shannon's source coding theorem makes this concrete: you can't compress draws from into fewer than bits each on average, and you can get arbitrarily close. Common symbols get short codes, rare ones long codes, about bits each.
Units: with you get bits; with the natural log, nats (1 nat ≈ 1.443 bits). ML code almost always uses natural logs, so losses are in nats.
Information gain: Wordle and decision trees
3Blue1Brown's Wordle solver picks the guess with the highest expected information. Each guess splits the remaining possible words into groups by the colour pattern you'd see. If a pattern leaves a fraction of the words, seeing it gives bits; averaging over patterns gives the entropy of the pattern distribution. A guess that splits the list evenly into many groups is worth many bits; one that usually tells you nothing is worth few.
Decision trees do exactly the same thing with data: they pick the split that most reduces the entropy of the labels, the information gain . This is a special case of mutual information, : how much knowing reduces your uncertainty about .
Worked exampleFour symbols
A source emits A, B, C, D with probabilities 1/2, 1/4, 1/8, 1/8.
- Surprises: 1, 2, 3 and 3 bits.
- Entropy: bits.
- A code that achieves it: A = 0, B = 10, C = 110, D = 111. Average length bits, better than the 2 bits a fixed-length code needs.
- If all four were equally likely, the entropy would be bits: the uneven source is more predictable.
Watch outCommon misconceptions
- "Information means meaning." Shannon information is only about probability. A random string of letters has more entropy per character than English text, because it's less predictable.
- "More outcomes always means more entropy." A 1000-sided die that almost always lands on 1 has lower entropy than a fair coin. Entropy depends on how the probability is spread.
- "Entropy is a property of a single outcome." A single outcome has a surprise. Entropy is the average over the whole distribution.
In ML & deep learningWhere this shows up
Decision trees and random forests split on information gain (or the closely related Gini impurity). Active learning picks the unlabelled examples where the model's prediction has the highest entropy. Reinforcement learning adds an entropy bonus to keep a policy exploring. The entropy of a language model's next-token distribution measures how unsure it is, and it's what temperature (chapter 12) turns up and down. Mutual information drives feature selection and contrastive learning objectives. And entropy is the baseline for the next chapter: cross-entropy and KL divergence measure how many extra bits a wrong model costs you.
Practice (pick one answer per question)
An event has probability 1/8. How much information (surprise) does seeing it carry?
- 3 bits
- 8 bits
- 1/8 bit
- −3 bits
bits: it's like identifying one of 8 equally likely options.
What is the entropy of a fair coin flip?
- 1 bit
- 0.5 bits
- 2 bits
- 0 bits
bit.
What is the entropy of a uniform distribution over 32 outcomes?
- 5 bits
- 32 bits
- 1/32 bit
- 16 bits
bits: five yes/no questions, each halving the options, find any one of 32.
What is the entropy of the distribution (0.5, 0.25, 0.25)?
- 1.5 bits
- 1.585 bits
- 1 bit
- 2 bits
bits. (1.585 = would be the uniform distribution over 3, the maximum.)
A coin lands heads 90% of the time. What is its entropy?
- About 0.469 bits
- About 0.9 bits
- About 0.152 bits
- About 0.1 bits
bits. The rare tails is very surprising but happens rarely. (0.152 is only the surprise of heads.)
In a guessing game with 1000 equally likely answers, a question splits them into groups of 800 and 200 (you learn which group). What is the expected information?
- About 0.72 bits
- 1 bit
- About 2.32 bits
- About 0.32 bits
You land in the 800 group with probability 0.8 (gaining bits) or the 200 group with probability 0.2 (gaining bits). The average is bits. An even 500/500 split would give the full 1 bit.
A node of a decision tree has 50% class A and 50% class B. A split sends half the data to a child that is 90% A and half to a child that is 90% B. What is the information gain?
- About 0.531 bits
- About 0.469 bits
- 1 bit
- 0.8 bits
Parent entropy 1 bit. Each child has entropy , and they're weighted ½ each, so the average child entropy is 0.469. Gain bits. (0.469 is what's left, not what's gained.)
Code it (optional: real Python runs in your browser and is graded by test cases)
Cross-entropy and KL divergence
Watch: A short introduction to entropy, cross-entropy and KL-divergence (Aurélien Géron) Watch: Intuitively understanding the KL divergence (Adian Liusie)Cross-entropy H(p, q) is the average surprise when reality follows p but you predict with q. It's never less than the entropy H(p), and the gap is the KL divergence, D_KL(p‖q): the price of believing the wrong distribution. KL is zero only when q = p, and it isn't symmetric.
Chapter 10 measured the surprise of a distribution against itself. In ML there are always two distributions: the true one, (where the data really comes from), and the model's, (what we predict). When an outcome happens, we are surprised by , because is what we believed. Averaging over what actually happens gives the cross-entropy:
In coding terms: if you design a code that's optimal for (about bits for symbol ) but the symbols actually come from , then is your average code length.
You can never do better than coding for the truth: , with equality only when (this is called Gibbs' inequality). The extra cost is the Kullback–Leibler divergence:
KL measures how different is from , in a specific sense: the expected extra surprise (or extra bits) from using when the truth is .
Three properties worth remembering
- It's zero exactly when the distributions match, and positive otherwise.
- It isn't symmetric: in general. So it's a "divergence", not a true distance. The two directions ask different questions: averages over , so it heavily punishes for being small where is large; averages over , so it punishes for putting mass where has little.
- It can be infinite. If for an outcome that says can happen, then : you said it was impossible, and it happened. That's why models should never assign exactly zero probability.
The asymmetry matters when you fit to . Minimising forward KL makes "cover" everywhere has mass, spreading out if it must (mode-covering). Minimising reverse KL makes avoid places doesn't go, so it may lock onto a single peak (mode-seeking).
Why cross-entropy is the classification loss
When we train a model , the truth is fixed, so is a constant. Therefore
Minimising cross-entropy is minimising KL from the truth to the model. And when is the empirical distribution of the training data, is exactly the average negative log-likelihood from chapter 8. Three names, one objective: minimise cross-entropy = minimise KL = maximise likelihood.
Worked exampleA fair coin, modelled badly
Truth , model , in bits.
- bit.
- bits.
- bits.
- The other direction: bits. Different, as promised.
Watch outCommon misconceptions
- "KL divergence is a distance." It's not symmetric and doesn't satisfy the triangle inequality. Always say which direction you mean.
- "Cross-entropy and KL are different objectives." For a fixed target they differ by the constant , so they have the same minimiser and the same gradients with respect to the model.
- "A cross-entropy loss of 0 is the goal." Only if the labels are certain (one-hot). With genuinely noisy labels the best possible cross-entropy is .
In ML & deep learningWhere this shows up
The cross-entropy loss of every classifier and language model is this chapter. Knowledge distillation trains a small student to match a big teacher's soft predictions by minimising KL between them. VAEs add a KL term keeping the encoder's distribution close to a Gaussian prior. RLHF and related fine-tuning methods add a KL penalty that stops the tuned model from drifting too far from the original. Policy-gradient methods like TRPO and PPO limit how much KL each update may change the policy. And variational inference, which approximates intractable posteriors, works by minimising a reverse KL.
Practice (pick one answer per question)
What is ?
- 0
- 1
- It depends on
Every term is . A distribution doesn't diverge from itself.
Which inequality always holds?
Coding with the wrong distribution can only cost extra bits: with .
The true label is one-hot, , and the model predicts . What is the cross-entropy in bits?
- 2 bits
- 0.415 bits
- 0.25 bits
- 0.811 bits
Only the true class counts: bits. With a one-hot target, cross-entropy is just the surprise of the correct answer. (0.415 is , the surprise of the wrong class.)
and . What is in bits?
- About 0.208
- About 0.189
- About 1.208
- 0
. (1.208 is the cross-entropy ; 0.189 is the other direction.)
Same and . What is in bits?
- About 0.189
- About 0.208, the same as
- About −0.208
- About 0.811
. Close to, but not equal to, the forward direction: KL isn't symmetric, and it's never negative. (0.811 is .)
A model assigns probability exactly 0 to an outcome that actually happens 10% of the time. What is ?
- Infinite
- 0.1 times something finite
- 0, because the outcome is rare
- Undefined but treated as 0
That outcome contributes . The model said "impossible" and was wrong, so its expected surprise is unbounded. This is why softmax outputs are never exactly 0.
Soft targets (say, a teacher's predictions in distillation). Among all model outputs , which minimises the cross-entropy , and what is the minimum?
- , and the minimum is bits
- , and the minimum is 0
- , and the minimum is
- , and the minimum is 0
, and KL is zero only at . The minimum is bits, not 0, because the targets themselves are uncertain. would give infinite cross-entropy.
Code it (optional: real Python runs in your browser and is graded by test cases)
Why MSE and cross-entropy are the losses we use
Watch: Neural networks part 6: cross entropy (StatQuest) Watch: Transformers, the tech behind LLMs (3Blue1Brown; softmax and temperature near the end)A loss function is a negative log-likelihood in disguise. Assume Gaussian noise around your prediction and maximum likelihood becomes mean squared error; assume a categorical distribution from a softmax and it becomes cross-entropy. An LLM is a categorical distribution over tokens, and temperature reshapes it before sampling.
Every chapter so far has been building to this. A model doesn't just output a number; it outputs a distribution over possible answers, . Training is maximum likelihood (chapter 8): minimise the average NLL of the true labels. So the only real design decision is which distribution, and the loss follows.
Regression: Gaussian noise gives mean squared error
Suppose the target is the model's prediction plus Gaussian noise: , with . Then , and the NLL of one example is
With fixed, the last two terms are constants and is a positive scale, so minimising the average NLL is exactly minimising the mean squared error . MSE isn't an arbitrary choice: it's what you get when you believe the errors are Gaussian. This explains its known weakness too: Gaussian tails are thin, so a big outlier is "nearly impossible" and gets a huge penalty. If you assume Laplace noise instead, , the NLL becomes the mean absolute error, which is far more forgiving of outliers (and predicts the median instead of the mean).
Classification: softmax + categorical gives cross-entropy
For classes, a network outputs real numbers called logits . The softmax turns them into a categorical distribution (chapter 3):
Exponentiating makes everything positive, dividing makes it add to 1, and bigger logits get exponentially more probability. Adding the same constant to every logit changes nothing, which is why code subtracts the maximum first to avoid overflow. The NLL of the true class is
and that is the cross-entropy of chapter 11 with a one-hot target . For two classes with a sigmoid output it becomes binary cross-entropy, : the log of chapter 3's Bernoulli formula.
This pairing has a beautiful gradient. The derivative of the loss with respect to the logits is simply
prediction minus target. Push up the true class's logit by how much probability it's missing, push down every other logit by how much probability it wrongly took. No vanishing gradient however wrong the model is, which is a big reason cross-entropy trains better than MSE on probabilities.
A note on LLMs: sampling and temperature
A language model is a classifier whose classes are tokens. At each step it outputs logits for every token in its vocabulary, and the softmax turns them into a categorical distribution over the next token. It was trained by minimising cross-entropy against the actual next token, so the "loss" in an LLM training log is average NLL in nats per token, and is the perplexity: the effective number of equally likely choices the model is torn between.
To generate text, you sample a token from that distribution, append it, and repeat. Temperature divides the logits before the softmax, :
- : the distribution the model learned.
- : differences between logits are magnified, the distribution sharpens and its entropy drops. As it becomes greedy decoding: always the top token.
- : the distribution flattens toward uniform, entropy rises, and the text gets more varied (and more error-prone).
Top-k and top-p (nucleus) sampling are further tweaks: throw away all but the most likely tokens, renormalise, then sample.
Worked exampleLogits (2, 1, 0)
- ; total . Softmax .
- If the true class is the first, the loss is nats. If it's the third, nats.
- Gradient (true class first): . It sums to zero, as it always does.
- At the logits become (4, 2, 0) and the top probability rises to ; at they become (1, 0.5, 0) and it falls to about 0.506.
Watch outCommon misconceptions
- "Loss functions are chosen because they work." They work because they're likelihoods of sensible noise models. Changing the noise model (Gaussian → Laplace → Poisson) changes the loss in a principled way.
- "Softmax outputs are calibrated probabilities." They add to 1, but a model trained to overconfidence may say 0.99 and be right 80% of the time. Calibration has to be checked (and can be fixed, for instance with a learned temperature).
- "Temperature 0 means 'the most accurate' output." It means the single most likely token at each step, which can still produce repetitive or globally unlikely text.
In ML & deep learningWhere this shows up
This is the whole training loop of modern deep learning: a network outputs the parameters of a distribution (a mean for regression, logits for classification, a full next-token distribution for an LLM), and the loss is the NLL of the data under it. Need uncertainty in regression? Output both and and minimise the full Gaussian NLL. Mixture density networks, Poisson regression for counts, and diffusion models' denoising losses all come from the same recipe. Label smoothing replaces the one-hot target with a slightly softened one, a prior again (chapter 9). And when you choose a sampling temperature in an LLM API, you're choosing how much entropy (chapter 10) to allow in its categorical distribution.
Practice (pick one answer per question)
Minimising mean squared error is maximum likelihood under which noise assumption?
- Gaussian noise with a fixed variance
- Laplace noise
- Uniform noise
- No noise at all
The Gaussian NLL is + constant, so minimising it is minimising squared error. Laplace noise would give mean absolute error.
What is ?
- (0.25, 0.25, 0.25, 0.25)
- (0, 0, 0, 0)
- (1, 1, 1, 1)
- It's undefined
Each entry is . Equal logits give a uniform distribution.
A classifier gives the correct class probability 0.25. What is its cross-entropy loss on this example, in nats?
- 2
- 0.25
- 0.75
nats. (2 would be the answer in bits.)
What happens to sampling from as the temperature ?
- It always picks the token with the largest logit (greedy decoding)
- It becomes uniform over all tokens
- It becomes uniform over the top two tokens
- Nothing changes; temperature only rescales the loss
Dividing by a tiny blows up the gaps between logits, so the largest one takes almost all the probability. Large does the opposite and flattens toward uniform.
A 3-class model outputs and the true class is the second. What is the gradient of the cross-entropy loss with respect to the logits?
- (0.7, −0.8, 0.1)
- (−0.3, 0.2, 0.1)
- (0.7, 0.2, 0.1)
- (−0.7, 0.8, −0.1)
The gradient is with : . Gradient descent moves the opposite way, raising the true logit and lowering the others. (The second option uses the wrong true class; the last has the sign flipped.)
Logits (2, 1, 0) at temperature . About what probability goes to the first class?
- 0.867
- 0.665
- 0.506
- 1.0
Divide by 0.5 to get (4, 2, 0); then . (0.665 is and 0.506 is .)
A language model's average cross-entropy on held-out text is 2 nats per token. What is its perplexity, and what does it mean?
- : it's as unsure as if choosing uniformly among about 7 tokens
- 4: it's as unsure as choosing among 4 tokens
- 2: it gets 2 tokens wrong in every sentence
- bits of error per token
Perplexity is when the NLL is in nats: . A uniform distribution over tokens has cross-entropy , so a loss of 2 nats is like hesitating between about 7.4 equally likely options. ( would apply if the loss were 2 bits.)
Code it (optional: real Python runs in your browser and is graded by test cases)
Final tests
3 full-length tests covering the whole module, with single-concept and multi-concept questions and Python problems graded by test cases. You get a score, a chapter-by-chapter breakdown and the worked answer to every question. Your best score is saved in this browser.
One-page cheat sheet
Everything from the 12 chapters, compressed. On paper, it prints on its own (figures hidden).
Rules of probability
, ,
Independent:
Conditioning & Bayes
; odds × likelihood ratio = posterior odds
Discrete distributions
Bernoulli: ; mean , var
Binomial: ; mean , var
Categorical: with one-hot
Expectation, variance, covariance
(always)
,
,
Continuous & Gaussian
; densities can exceed 1
: ;
±1σ: 68.3%, ±2σ: 95.4%, ±3σ: 99.7%
Sums & the CLT
(convolution)
Independent: means add, variances add; Gaussian + Gaussian = Gaussian
: error shrinks like
Multivariate Gaussian
, symmetric, PSD;
Contours: ellipses along eigenvectors of , semi-axes
; sample ,
Maximum likelihood
Coin: . Gaussian: ,
Priors & MAP
posterior ∝ likelihood × prior; MAP = argmin [NLL − log prior]
Beta(a, b) prior: MAP , mean
Gaussian prior → L2 (ridge, weight decay); Laplace prior → L1 (lasso, sparse)
Information
Surprise bits; entropy
; 1 nat = 1.443 bits
Information gain =
Cross-entropy & KL
; not symmetric
min cross-entropy = min KL = max likelihood
Losses & LLMs
Gaussian noise → MSE; Laplace noise → MAE
; loss ; gradient
Temperature: ; perplexity
Glossary
- Bayes' rule
- : how to update a belief (the prior) into a posterior after seeing evidence. (Ch 2, 9)
- Bernoulli distribution
- A single yes/no trial: 1 with probability , 0 otherwise. (Ch 3)
- Beta distribution
- A distribution over a probability , with density ∝ ; the standard prior for a coin. (Ch 9)
- Binomial distribution
- The number of successes in independent Bernoulli() trials. (Ch 3)
- Categorical distribution
- One of outcomes, with probabilities adding to 1. A softmax output is one. (Ch 3, 12)
- Central limit theorem
- The average of many independent draws with finite variance is approximately , whatever the original distribution. (Ch 6)
- Conditional probability
- : the probability of once you know happened. (Ch 2)
- Convolution
- The operation that gives the distribution of a sum of independent random variables: . (Ch 6)
- Correlation
- Covariance divided by both standard deviations; always between −1 and 1. (Ch 4)
- Covariance
- : whether two variables move together. (Ch 4)
- Covariance matrix
- The matrix of all pairwise covariances of a random vector; symmetric and positive semi-definite. (Ch 7)
- Cross-entropy
- : the average surprise when outcomes follow but you predict with . The standard classification loss. (Ch 11, 12)
- Density (PDF)
- A curve whose area over an interval is the probability of landing in it. Not itself a probability. (Ch 5)
- Entropy
- : the average surprise, or uncertainty, of a distribution. (Ch 10)
- Event
- A set of outcomes. (Ch 1)
- Expectation
- The probability-weighted average ; the balance point of a distribution. (Ch 4)
- Gaussian (normal) distribution
- The bell curve . (Ch 5)
- Independence
- : learning one tells you nothing about the other. (Ch 1)
- KL divergence
- : the extra cost of using when the truth is . Non-negative and not symmetric. (Ch 11)
- L1 / L2 regularization
- Penalties and ; MAP estimation with Laplace and Gaussian priors. (Ch 9)
- Likelihood
- , viewed as a function of the parameters. (Ch 8)
- Logits
- The raw scores a network outputs before the softmax. (Ch 12)
- Mahalanobis distance
- : distance measured in standard deviations, accounting for the shape of the distribution. (Ch 7)
- MAP estimate
- The parameters that maximise the posterior: maximum likelihood plus a penalty from the prior. (Ch 9)
- Maximum likelihood (MLE)
- The parameters that make the observed data most probable. (Ch 8)
- Negative log-likelihood (NLL)
- ; the loss that training minimises. (Ch 8, 12)
- Perplexity
- : the effective number of equally likely choices a language model is torn between. (Ch 12)
- PMF
- Probability mass function of a discrete random variable. (Ch 1)
- Posterior / prior
- Beliefs after and before seeing the evidence. (Ch 2, 9)
- Random variable
- A function that turns each outcome into a number. (Ch 1)
- Sample space
- The set of all possible outcomes. (Ch 1)
- Softmax
- : turns logits into a categorical distribution. (Ch 12)
- Standard deviation
- The square root of the variance; spread in the original units. (Ch 4)
- Temperature
- Dividing logits by before the softmax: sharpens, flattens. (Ch 12)
- Variance
- : the average squared distance from the mean. (Ch 4)