Math for ML / Probability, Statistics & Information Theory
0 / 12
Module 3

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 N(μ,σ2)\mathcal N(\mu,\sigma^2) and its multivariate cousin, then maximum likelihood, priors and regularization, and finally entropy, cross-entropy and DKL(p ∥ q)D_{\mathrm{KL}}(p\,\|\,q). 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.
Chapter 1

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 Ω\Omega. 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 {(1,6),(2,5),(3,4),(4,3),(5,2),(6,1)}\{(1,6),(2,5),(3,4),(4,3),(5,2),(6,1)\}. "Doubles" is another. Events are sets, so you can combine them: A∩BA \cap B ("A and B"), A∪BA \cup B ("A or B, or both"), and the complement AcA^c ("not A").

A probability PP assigns each event a number, following three rules (Kolmogorov's axioms, though you don't need the name):

  • P(A)≥0P(A) \ge 0 for every event: no negative chances.
  • P(Ω)=1P(\Omega) = 1: something happens.
  • If AA and BB can't both happen (they're disjoint), then P(A∪B)=P(A)+P(B)P(A \cup B) = P(A) + P(B).

Everything else follows. The complement rule P(Ac)=1−P(A)P(A^c) = 1 - P(A) comes from splitting Ω\Omega into AA and not-AA. When events can overlap, adding counts the overlap twice, so you subtract it once:

P(A∪B)=P(A)+P(B)−P(A∩B).P(A \cup B) = P(A) + P(B) - P(A \cap B).

When all outcomes are equally likely (fair dice, a well-shuffled deck), probability is just counting: P(A)=outcomes in Aall outcomesP(A) = \frac{\text{outcomes in }A}{\text{all outcomes}}. Sum to 7 has 6 outcomes out of 36, so P=1/6P = 1/6.

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, SS = "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 SS, you can ask about events like {S=7}\{S = 7\} or {S≥10}\{S \ge 10\}.

For a random variable with a list of possible values (a discrete one), its probability mass function (PMF) p(x)=P(X=x)p(x) = P(X = x) says how likely each value is. The PMF of the two-dice sum rises from p(2)=1/36p(2) = 1/36 to p(7)=6/36p(7) = 6/36 and falls back to p(12)=1/36p(12) = 1/36. The values are never negative and always add to 1. That list of probabilities is the distribution of SS, 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, P(A∩B)=P(A) P(B)P(A \cap B) = P(A)\,P(B). Separate dice are independent: P(first is 6 and second is 6)=16⋅16=136P(\text{first is 6 and second is 6}) = \frac16 \cdot \frac16 = \frac1{36}. 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 1−P(no 6s)=1−(5/6)2=11/361 - P(\text{no 6s}) = 1 - (5/6)^2 = 11/36.

The 6 × 6 grid is the sample space of two dice; the gold cells are the event you picked (use the buttons and the k slider). Its probability is just gold cells ÷ 36. Press Roll 100 or Keep rolling: the purple line is the fraction of rolls that landed in the event, and it wanders at first, then settles on the dashed blue line, the probability.

Worked exampleThree questions about two dice

  • Sum = 7: 6 favourable cells of 36, so P=6/36=1/6≈0.167P = 6/36 = 1/6 \approx 0.167.
  • At least one 6: the complement "no 6" has 5×5=255 \times 5 = 25 cells, so P=1−25/36=11/36≈0.306P = 1 - 25/36 = 11/36 \approx 0.306. 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 P=6/36+6/36=1/3P = 6/36 + 6/36 = 1/3. Compare "sum = 8 or doubles": they overlap at (4, 4), so P=5/36+6/36−1/36=10/36P = 5/36 + 6/36 - 1/36 = 10/36.

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 AA and BB are disjoint and both possible, learning AA happened tells you BB definitely didn't, so they are strongly dependent: P(A∩B)=0≠P(A)P(B)P(A \cap B) = 0 \ne P(A)P(B).
  • "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 (x,y)(x, y) 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. 1/2
  2. 1/3
  3. 1/6
  4. 2/3

The event is {2, 4, 6}: 3 of 6 equally likely outcomes, so P=3/6=1/2P = 3/6 = 1/2.

A spam filter says P(spam)=0.3P(\text{spam}) = 0.3 for an email. What is P(not spam)P(\text{not spam})?

  1. 0.7
  2. 0.3
  3. 1.3
  4. It can't be known without more information

Complement rule: 1−0.3=0.71 - 0.3 = 0.7. "Spam" and "not spam" split the sample space, so their probabilities add to 1.

Two fair dice. What is P(sum=8)P(\text{sum} = 8)?

  1. 5/36
  2. 1/6
  3. 1/9
  4. 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.

P(A)=0.5P(A) = 0.5, P(B)=0.4P(B) = 0.4 and P(A∩B)=0.2P(A \cap B) = 0.2. What is P(A∪B)P(A \cup B)?

  1. 0.7
  2. 0.9
  3. 0.2
  4. 0.5

0.5+0.4−0.2=0.70.5 + 0.4 - 0.2 = 0.7. Adding alone gives 0.9, which counts the overlap twice. (Here P(A)P(B)=0.2=P(A∩B)P(A)P(B) = 0.2 = P(A \cap B), so AA and BB also happen to be independent.)

Flip a fair coin 3 times and let XX = number of heads. What is P(X=2)P(X = 2)?

  1. 3/8
  2. 1/3
  3. 2/3
  4. 1/4

There are 23=82^3 = 8 equally likely sequences. Exactly two heads: HHT, HTH, THH, so 3 of 8. (XX takes 4 values, but they are not equally likely, which is why 1/4 is wrong.)

Events AA and BB are disjoint, with P(A)=0.3P(A) = 0.3 and P(B)=0.2P(B) = 0.2. Which statement is true?

  1. They are dependent, because P(A∩B)=0P(A \cap B) = 0 but P(A)P(B)=0.06P(A)P(B) = 0.06
  2. They are independent, because they don't overlap
  3. They are independent, because P(A∪B)=P(A)+P(B)P(A \cup B) = P(A) + P(B)
  4. Nothing can be said without more information

Independence needs P(A∩B)=P(A)P(B)P(A \cap B) = P(A)P(B). Disjoint means P(A∩B)=0P(A \cap B) = 0, but 0.3×0.2=0.060.3 \times 0.2 = 0.06. Knowing AA happened rules BB 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?

  1. 1−(5/6)4≈0.5181 - (5/6)^4 \approx 0.518
  2. 4×1/6≈0.6674 \times 1/6 \approx 0.667
  3. (5/6)4≈0.482(5/6)^4 \approx 0.482
  4. (1/6)4≈0.0008(1/6)^4 \approx 0.0008

"At least one" is easiest through the complement. No 6 in 4 independent rolls has probability (5/6)4=625/1296≈0.482(5/6)^4 = 625/1296 \approx 0.482, so the answer is 1−0.482≈0.5181 - 0.482 \approx 0.518. Adding 1/61/6 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)

Chapter 2

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 P(sick∣+)P(\text{sick} \mid +), read "probability of sick given positive".

The definition is a zoom: throw away every outcome where the evidence BB didn't happen, and ask what fraction of what's left is in AA:

P(A∣B)=P(A∩B)P(B).P(A \mid B) = \frac{P(A \cap B)}{P(B)}.

Rearranging gives the multiplication rule P(A∩B)=P(A∣B) P(B)P(A \cap B) = P(A \mid B)\,P(B), 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 P(A∣B)=P(A)P(A \mid B) = P(A): learning BB doesn't move your belief in AA.

If some hypotheses H1,H2,…H_1, H_2, \ldots cover every possibility without overlapping, the law of total probability adds up the routes to the evidence:

P(E)=∑iP(E∣Hi) P(Hi).P(E) = \sum_i P(E \mid H_i)\,P(H_i).

Bayes' rule

The multiplication rule works in both orders, P(H∣E)P(E)=P(E∣H)P(H)P(H \mid E)P(E) = P(E \mid H)P(H). Divide by P(E)P(E) and you get Bayes' rule:

P(H∣E)⏟posterior=P(E∣H)⏞likelihood  P(H)⏞priorP(E).\underbrace{P(H \mid E)}_{\text{posterior}} = \frac{\overbrace{P(E \mid H)}^{\text{likelihood}}\;\overbrace{P(H)}^{\text{prior}}}{P(E)}.
  • The prior P(H)P(H) is what you believed before the evidence.
  • The likelihood P(E∣H)P(E \mid H) is how well the hypothesis predicts the evidence.
  • The posterior P(H∣E)P(H \mid E) is your updated belief.
  • The denominator P(E)P(E), 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, P(+∣sick)P(+ \mid \text{sick})) and correctly clears 95% of healthy people (its specificity, P(−∣healthy)P(- \mid \text{healthy})). 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: 90/585≈15%90/585 \approx 15\%.

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 P/(1−P)P/(1-P). Each piece of evidence multiplies the odds by its likelihood ratio (Bayes factor), P(E∣H)P(E∣not H)\frac{P(E \mid H)}{P(E \mid \text{not }H)}. For a positive test that's 0.90/0.05=180.90/0.05 = 18: prior odds 1 : 99 become 18 : 99, which is 18/117≈15%18/117 \approx 15\%. A second, independent positive test multiplies by 18 again: 324 : 99, about 77%.

Each square is one of 1000 people: red are sick, teal are healthy; solid squares test positive. P(sick | positive) is the share of solid squares that are red. Slide the prior down to 0.1% and watch the red solid squares vanish among the teal false positives; raise specificity to 99.5% and the false positives melt away.

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: P(S)=0.4P(S) = 0.4, P(not S)=0.6P(\text{not }S) = 0.6.
  • Likelihoods: P(w∣S)=0.2P(w \mid S) = 0.2, P(w∣not S)=0.01P(w \mid \text{not }S) = 0.01.
  • Total: P(w)=0.2×0.4+0.01×0.6=0.08+0.006=0.086P(w) = 0.2 \times 0.4 + 0.01 \times 0.6 = 0.08 + 0.006 = 0.086.
  • Posterior: P(S∣w)=0.08/0.086≈0.930P(S \mid w) = 0.08 / 0.086 \approx 0.930.

Odds check: prior odds 0.4 : 0.6, likelihood ratio 20, posterior odds 8 : 0.6, so 8/8.6≈0.9308/8.6 \approx 0.930 ✓. 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 P(result∣status)P(\text{result} \mid \text{status}); you want P(status∣result)P(\text{status} \mid \text{result}).
  • "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 P(y∣x)P(y \mid \mathbf x): the probability of each label given the input. Generative classifiers such as naive Bayes model P(x∣y)P(\mathbf x \mid y) and P(y)P(y) and apply Bayes' rule; discriminative ones like logistic regression and neural networks learn P(y∣x)P(y \mid \mathbf x) 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 P(fraud∣flagged)P(\text{fraud} \mid \text{flagged}), 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)

P(A∩B)=0.12P(A \cap B) = 0.12 and P(B)=0.4P(B) = 0.4. What is P(A∣B)P(A \mid B)?

  1. 0.3
  2. 0.048
  3. 0.12
  4. 0.52

P(A∣B)=0.12/0.4=0.3P(A \mid B) = 0.12 / 0.4 = 0.3. Among the outcomes where BB happens, 30% also have AA.

Which quantity equals P(A∣B) P(B)P(A \mid B)\,P(B)?

  1. P(A∩B)P(A \cap B)
  2. P(B∣A)P(B \mid A)
  3. P(A∪B)P(A \cup B)
  4. P(A)P(A)

That's the multiplication rule: the chance of BB, times the chance of AA once BB 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?

  1. 0.032
  2. 0.035
  3. 0.07
  4. 0.020

Total probability: 0.6×0.02+0.4×0.05=0.012+0.020=0.0320.6 \times 0.02 + 0.4 \times 0.05 = 0.012 + 0.020 = 0.032. (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?

  1. 0.625
  2. 0.4
  3. 0.05
  4. 0.375

Bayes: P(B∣D)=P(D∣B)P(B)P(D)=0.05×0.40.032=0.0200.032=0.625P(B \mid D) = \frac{P(D \mid B)P(B)}{P(D)} = \frac{0.05 \times 0.4}{0.032} = \frac{0.020}{0.032} = 0.625. 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. 1/2
  2. 1/3
  3. 2/3
  4. 1

P(H)=23⋅12+13⋅1=23P(H) = \frac23 \cdot \frac12 + \frac13 \cdot 1 = \frac23. Then P(two-headed∣H)=1⋅1/32/3=12P(\text{two-headed} \mid H) = \frac{1 \cdot 1/3}{2/3} = \frac12. 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?

  1. About 67%
  2. About 99%
  3. About 2%
  4. About 50%

Per 10 000 people: 200 sick, 198 test positive; 9800 healthy, 98 test positive. 198/(198+98)=198/296≈0.669198/(198+98) = 198/296 \approx 0.669. 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 P(+∣sick)/P(+∣healthy)=18P(+\mid\text{sick})/P(+\mid\text{healthy}) = 18. You take two independent tests and both are positive. What is the posterior probability of being sick?

  1. About 0.77
  2. About 0.15
  3. About 0.36
  4. About 0.97

Odds form: prior odds 1:991 : 99. Each positive multiplies the odds by 18, so two give 18×18=32418 \times 18 = 324, and the odds become 324:99324 : 99. As a probability, 324/423≈0.766324 / 423 \approx 0.766. (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)

Chapter 3

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 pp and 0 with probability 1−p1-p. Click or no click, spam or not, the pixel is on or off. One compact formula covers both cases:

P(X=x)=px(1−p)1−x,x∈{0,1}.P(X = x) = p^x (1-p)^{1-x}, \qquad x \in \{0, 1\}.

Plug in x=1x = 1 and you get pp; plug in x=0x = 0 and you get 1−p1-p. This trick of using the exponent as a switch looks like a gimmick now, but its logarithm, xlog⁡p+(1−x)log⁡(1−p)x \log p + (1-x)\log(1-p), is the binary cross-entropy loss you'll meet in chapter 12.

Binomial: counting successes

Repeat a Bernoulli trial nn times independently and count the successes. That count XX is binomial, X∼Binomial(n,p)X \sim \text{Binomial}(n, p). Any particular sequence with kk successes, like SSF…S, has probability pk(1−p)n−kp^k(1-p)^{n-k} by independence, and there are (nk)=n!k!(n−k)!\binom nk = \frac{n!}{k!(n-k)!} such sequences, so

P(X=k)=(nk)pk(1−p)n−k.P(X = k) = \binom nk p^k (1-p)^{n-k}.

Its mean is npnp and its variance is np(1−p)np(1-p) (chapter 4 shows why: a binomial is a sum of nn independent Bernoullis, and means and variances of independent pieces add). As nn grows the histogram gets wider in absolute terms, about n\sqrt{n}, but narrower relative to nn, 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 pp, which turns the question around into "what should I believe about pp?" We'll answer that in chapters 8 and 9.

Categorical: one of K classes

A categorical distribution generalises the Bernoulli to KK outcomes: class kk has probability pkp_k, with pk≥0p_k \ge 0 and ∑kpk=1\sum_k p_k = 1. Writing the outcome as a one-hot vector y\mathbf y (all zeros except a 1 in position kk) gives the same exponent trick:

P(y)=∏k=1Kpk yk.P(\mathbf y) = \prod_{k=1}^K p_k^{\,y_k}.

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 nn draws", is the multinomial, which is to the categorical what the binomial is to the Bernoulli.

Bars show Binomial(n, p). Move n and p: the mean (dashed) sits at np and the spread is √(np(1−p)), widest at p = 0.5. The gold bars are the tail P(X ≥ k). Simulate runs 500 real experiments; the purple dots are how often each count came up, and they sit near the bar tops.

Worked exampleA model answers 10 questions

A model gets each question right with probability 0.95, independently. Let XX be the number right out of 10.

  • P(X=10)=0.9510≈0.599P(X = 10) = 0.95^{10} \approx 0.599. Even a 95% model gets a perfect score only 60% of the time.
  • P(X=9)=(109) 0.959 0.05=10×0.6302×0.05≈0.315P(X = 9) = \binom{10}{9}\,0.95^9\,0.05 = 10 \times 0.6302 \times 0.05 \approx 0.315.
  • P(X≥9)≈0.599+0.315=0.914P(X \ge 9) \approx 0.599 + 0.315 = 0.914.
  • Mean np=9.5np = 9.5, variance np(1−p)=10×0.95×0.05=0.475np(1-p) = 10 \times 0.95 \times 0.05 = 0.475, standard deviation ≈0.69\approx 0.69.

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 nn, independent trials and the same pp 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 p=P(y=1∣x)p = P(y = 1 \mid \mathbf x). A multi-class classifier with a softmax output is a categorical model: it outputs p1,…,pKp_1, \ldots, p_K. 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 nn test examples can wobble: its standard deviation is p(1−p)/n\sqrt{p(1-p)/n}, so 1000 test examples pin a 90% accuracy down only to about ±1%.

Practice (pick one answer per question)

XX is Bernoulli with p=0.3p = 0.3. What is P(X=0)P(X = 0)?

  1. 0.7
  2. 0.3
  3. 0
  4. 0.21

P(X=0)=(1−p)=0.7P(X=0) = (1-p) = 0.7. From the formula: 0.30×0.71=0.70.3^0 \times 0.7^1 = 0.7.

A categorical distribution over 4 classes has p1=0.1p_1 = 0.1, p2=0.2p_2 = 0.2, p3=0.3p_3 = 0.3. What is p4p_4?

  1. 0.4
  2. 0.25
  3. 0.6
  4. It can be any number between 0 and 1

The probabilities must add to 1: 1−0.1−0.2−0.3=0.41 - 0.1 - 0.2 - 0.3 = 0.4.

X∼Binomial(4,0.5)X \sim \text{Binomial}(4, 0.5). What is P(X=2)P(X = 2)?

  1. 0.375
  2. 0.5
  3. 0.25
  4. 0.0625

(42)(0.5)2(0.5)2=6/16=0.375\binom42 (0.5)^2(0.5)^2 = 6/16 = 0.375. (0.0625 is one particular sequence, forgetting the 6 ways to arrange it.)

X∼Binomial(20,0.25)X \sim \text{Binomial}(20, 0.25). What are its mean and variance?

  1. 5 and 3.75
  2. 5 and 5
  3. 5 and 0.1875
  4. 0.25 and 3.75

Mean np=20×0.25=5np = 20 \times 0.25 = 5; variance np(1−p)=5×0.75=3.75np(1-p) = 5 \times 0.75 = 3.75. (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?

  1. 0.910≈0.3490.9^{10} \approx 0.349
  2. 0.90.9
  3. 1−0.1101 - 0.1^{10}
  4. 0.1100.1^{10}

"None spam" means all 10 independent emails are not spam: 0.910≈0.3490.9^{10} \approx 0.349. It's the k=0k = 0 term of Binomial(10, 0.1).

For which pp is the variance of a Bernoulli(pp) largest, and what is that variance?

  1. p=0.5p = 0.5, variance 0.25
  2. p=1p = 1, variance 1
  3. p=0.5p = 0.5, variance 0.5
  4. Every pp gives the same variance

p(1−p)p(1-p) is a downward parabola with its peak at p=0.5p = 0.5, where it equals 0.25. At p=0p = 0 or 11 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?

  1. 0.737
  2. 0.410
  3. 0.328
  4. 0.800

P(X=4)=(54)0.84×0.2=5×0.4096×0.2=0.4096P(X=4) = \binom54 0.8^4 \times 0.2 = 5 \times 0.4096 \times 0.2 = 0.4096, and P(X=5)=0.85=0.32768P(X=5) = 0.8^5 = 0.32768. Add them: 0.73728≈0.7370.73728 \approx 0.737. 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)

Chapter 4

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:

E[X]=∑xx p(x).\mathbb E[X] = \sum_x x\,p(x).

Picture the PMF as weights hung on a ruler at positions xx. The expectation is where you'd put your finger to balance it. It need not be a value XX can actually take: a fair die has E[X]=3.5\mathbb E[X] = 3.5. 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:

E[aX+bY+c]=a E[X]+b E[Y]+c,\mathbb E[aX + bY + c] = a\,\mathbb E[X] + b\,\mathbb E[Y] + c,

and it holds always, whether or not XX and YY are independent. For example, a Binomial(n,pn, p) count is a sum of nn Bernoullis each with mean pp, so its mean is npnp with no algebra at all. For a function of XX, weight the function's values: E[g(X)]=∑xg(x)p(x)\mathbb E[g(X)] = \sum_x g(x)p(x). Careful: in general E[g(X)]≠g(E[X])\mathbb E[g(X)] \ne g(\mathbb E[X]); for instance E[X2]≠(E[X])2\mathbb E[X^2] \ne (\mathbb E[X])^2.

Variance: the spread

The variance is the expected squared distance from the mean, and the standard deviation σ\sigma is its square root, which brings it back to the original units:

Var⁡(X)=E[(X−μ)2]=E[X2]−μ2,σ=Var⁡(X).\operatorname{Var}(X) = \mathbb E\big[(X - \mu)^2\big] = \mathbb E[X^2] - \mu^2, \qquad \sigma = \sqrt{\operatorname{Var}(X)}.

Shifting doesn't change spread and scaling multiplies it: Var⁡(aX+b)=a2Var⁡(X)\operatorname{Var}(aX + b) = a^2\operatorname{Var}(X). Notice the square: doubling XX quadruples its variance and doubles its standard deviation.

Covariance and correlation: moving together

For two random variables, the covariance asks: when XX is above its mean, is YY usually above its mean too?

Cov⁡(X,Y)=E[(X−μX)(Y−μY)]=E[XY]−μXμY.\operatorname{Cov}(X, Y) = \mathbb E\big[(X - \mu_X)(Y - \mu_Y)\big] = \mathbb E[XY] - \mu_X\mu_Y.

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 ρ=Cov⁡(X,Y)σXσY\rho = \frac{\operatorname{Cov}(X,Y)}{\sigma_X\sigma_Y}, which always lies between −1 and 1. Covariance also fixes the variance of a sum:

Var⁡(X+Y)=Var⁡(X)+Var⁡(Y)+2Cov⁡(X,Y).\operatorname{Var}(X + Y) = \operatorname{Var}(X) + \operatorname{Var}(Y) + 2\operatorname{Cov}(X, Y).

If XX and YY are independent their covariance is 0, so variances simply add. The converse is false: zero covariance only rules out a straight-line relationship.

Drag the teal bar tops to reshape a distribution on 0…6 (the others rescale so it still adds to 1). The dashed blue line is the mean, and the purple bar spans μ ± σ. The beam underneath carries the same weights: drag the gold triangle until it balances, or press Balance it. It always balances at the mean.

Worked exampleA fair die

  • E[X]=1+2+3+4+5+66=3.5\mathbb E[X] = \frac{1+2+3+4+5+6}{6} = 3.5.
  • E[X2]=1+4+9+16+25+366=916≈15.17\mathbb E[X^2] = \frac{1+4+9+16+25+36}{6} = \frac{91}{6} \approx 15.17.
  • Var⁡(X)=916−3.52=3512≈2.92\operatorname{Var}(X) = \frac{91}{6} - 3.5^2 = \frac{35}{12} \approx 2.92, so σ≈1.71\sigma \approx 1.71.
  • The total of two dice: E=7\mathbb E = 7, and since the dice are independent Var⁡=2×3512≈5.83\operatorname{Var} = 2 \times \frac{35}{12} \approx 5.83.
  • The average of two dice, (X1+X2)/2(X_1 + X_2)/2: mean 3.5, variance 14×5.83≈1.46\frac14 \times 5.83 \approx 1.46. 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: Var⁡(X−Y)=Var⁡(X)+Var⁡(Y)\operatorname{Var}(X - Y) = \operatorname{Var}(X) + \operatorname{Var}(Y), because (−1)2=1(-1)^2 = 1. Uncertainty never cancels by subtraction.
  • "Zero covariance means independent." Take XX uniform on {−1, 0, 1} and Y=X2Y = X^2. YY is completely determined by XX, yet Cov⁡(X,Y)=E[X3]−0=0\operatorname{Cov}(X, Y) = \mathbb E[X^3] - 0 = 0.

In ML & deep learningWhere this shows up

The training loss is an expectation, E(x,y)[ℓ(x,y)]\mathbb E_{(\mathbf x, y)}[\ell(\mathbf x, y)] 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 1/B1/B). 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)

XX is 0 with probability 0.5 and 10 with probability 0.5. What is E[X]\mathbb E[X]?

  1. 5
  2. 10
  3. 0
  4. 0.5

0×0.5+10×0.5=50 \times 0.5 + 10 \times 0.5 = 5, a value XX never takes.

E[X]=4\mathbb E[X] = 4. What is E[3X+2]\mathbb E[3X + 2]?

  1. 14
  2. 12
  3. 36
  4. It depends on the distribution of XX

Linearity: 3×4+2=143 \times 4 + 2 = 14. No other information about XX is needed.

Var⁡(X)=3\operatorname{Var}(X) = 3. What is Var⁡(2X+5)\operatorname{Var}(2X + 5)?

  1. 12
  2. 6
  3. 11
  4. 17

22×3=122^2 \times 3 = 12. Adding 5 shifts the distribution without changing its spread; the factor 2 is squared.

XX takes values 1, 2, 3 with probabilities 0.2, 0.5, 0.3. What is Var⁡(X)\operatorname{Var}(X)?

  1. 0.49
  2. 2.1
  3. 4.9
  4. 0.7

E[X]=0.2+1.0+0.9=2.1\mathbb E[X] = 0.2 + 1.0 + 0.9 = 2.1 and E[X2]=0.2+2.0+2.7=4.9\mathbb E[X^2] = 0.2 + 2.0 + 2.7 = 4.9. So Var⁡=4.9−2.12=4.9−4.41=0.49\operatorname{Var} = 4.9 - 2.1^2 = 4.9 - 4.41 = 0.49, and σ=0.7\sigma = 0.7.

Var⁡(X)=4\operatorname{Var}(X) = 4, Var⁡(Y)=9\operatorname{Var}(Y) = 9 and Cov⁡(X,Y)=−3\operatorname{Cov}(X, Y) = -3. What is Var⁡(X+Y)\operatorname{Var}(X + Y)?

  1. 7
  2. 13
  3. 10
  4. 19

4+9+2(−3)=74 + 9 + 2(-3) = 7. 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.)

XX is uniform on {−1, 0, 1} and Y=X2Y = X^2. Which is true?

  1. Cov⁡(X,Y)=0\operatorname{Cov}(X, Y) = 0, but XX and YY are dependent
  2. Cov⁡(X,Y)=0\operatorname{Cov}(X, Y) = 0, so they are independent
  3. Cov⁡(X,Y)>0\operatorname{Cov}(X, Y) > 0, because YY grows with ∣X∣|X|
  4. Cov⁡(X,Y)=1\operatorname{Cov}(X, Y) = 1, because YY is a function of XX

E[X]=0\mathbb E[X] = 0 and E[XY]=E[X3]=(−1+0+1)/3=0\mathbb E[XY] = \mathbb E[X^3] = (-1 + 0 + 1)/3 = 0, so the covariance is 0. But knowing XX tells you YY exactly, so they're as dependent as can be. Covariance only sees straight-line trends, and this relationship is a symmetric U.

You average n=100n = 100 independent measurements, each with standard deviation 2. What is the standard deviation of the average?

  1. 0.2
  2. 0.02
  3. 2
  4. 0.04

The sum has variance 100×4=400100 \times 4 = 400; dividing by 100 divides variance by 1002100^2, giving 400/10 000=0.04400/10\,000 = 0.04. The standard deviation is 0.04=0.2=2/100\sqrt{0.04} = 0.2 = 2/\sqrt{100}. (0.04 is the variance, not the standard deviation.)

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 5

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) f(x)f(x) is a curve whose area gives probability:

P(a≤X≤b)=∫abf(x) dx,f(x)≥0,∫−∞∞f(x) dx=1.P(a \le X \le b) = \int_a^b f(x)\,dx, \qquad f(x) \ge 0, \qquad \int_{-\infty}^{\infty} f(x)\,dx = 1.

The density itself is not a probability. It's probability per unit length, so f(x) dxf(x)\,dx is roughly the probability of landing in a tiny window of width dxdx around xx. 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 F(x)=P(X≤x)F(x) = P(X \le x) is the running area, and P(a≤X≤b)=F(b)−F(a)P(a \le X \le b) = F(b) - F(a).

Expectation and variance work as before, with integrals in place of sums: E[X]=∫xf(x) dx\mathbb E[X] = \int x f(x)\,dx. The simplest example is the uniform distribution on [a,b][a, b]: a flat density of height 1b−a\frac1{b-a}, mean a+b2\frac{a+b}2, variance (b−a)212\frac{(b-a)^2}{12}.

The Gaussian

The Gaussian or normal distribution N(μ,σ2)\mathcal N(\mu, \sigma^2) has density

f(x)=1σ2πexp⁡ ⁣(−(x−μ)22σ2).f(x) = \frac{1}{\sigma\sqrt{2\pi}}\exp\!\left(-\frac{(x - \mu)^2}{2\sigma^2}\right).

Read it from the inside out. x−μσ\frac{x-\mu}{\sigma} measures how many standard deviations xx is from the centre. Squaring and negating gives a downward parabola, and e(⋅)e^{(\cdot)} turns that into a bell that falls off very fast: 3σ out, the density is e−4.5≈1%e^{-4.5} \approx 1\% of its peak. The front factor 1σ2π\frac1{\sigma\sqrt{2\pi}} is just whatever makes the total area 1.

Where does π come from? The area under e−x2e^{-x^2} is π\sqrt{\pi}. 3Blue1Brown's video gives a beautiful reason: the 2D function e−x2e−y2=e−(x2+y2)e^{-x^2}e^{-y^2} = e^{-(x^2+y^2)} 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: Z=X−μσZ = \frac{X - \mu}{\sigma} is N(0,1)\mathcal N(0, 1), the standard normal.

Move μ to slide the bell and σ to widen it: as it widens it must also get shorter, because the area stays 1. Drag the two gold handles on the axis to choose an interval; the shaded area is the probability of landing inside it. Try the μ ± 1σ, 2σ, 3σ buttons: the areas are 68%, 95% and 99.7% whatever μ and σ are.

Worked exampleHeights

Suppose adult heights are roughly N(170,102)\mathcal N(170, 10^2) in cm.

  • P(160≤X≤180)P(160 \le X \le 180): that's μ±1σ\mu \pm 1\sigma, so about 0.683.
  • P(X>190)P(X > 190): z=(190−170)/10=2z = (190 - 170)/10 = 2. Half of the 4.6% outside ±2σ is above, so about 0.023.
  • P(X<155)P(X < 155): z=−1.5z = -1.5, and a table or calculator gives Φ(−1.5)≈\Phi(-1.5) \approx 0.067.
  • The peak density is 1102π≈0.040\frac{1}{10\sqrt{2\pi}} \approx 0.040 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. P(X=x)=0P(X = x) = 0 for every single xx; 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 μ+σz\mu + \sigma z with z∼N(0,1)z \sim \mathcal N(0,1) so gradients can flow through μ\mu and σ\sigma. Standardising features to z-scores, (x−μ)/σ(x - \mu)/\sigma, is a standard preprocessing step.

Practice (pick one answer per question)

XX is uniform on [0, 4]. What is the height of its density?

  1. 0.25
  2. 4
  3. 1
  4. 0.5

A flat density over a length-4 interval needs height 1/41/4 so the area is 1.

XX is a continuous random variable. What is P(X=2.5)P(X = 2.5)?

  1. 0
  2. f(2.5)f(2.5)
  3. It depends on the distribution
  4. P(X≤2.5)P(X \le 2.5), 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. f(2.5)f(2.5) is a density, and P(X≤2.5)P(X \le 2.5) is an area to the left of 2.5, not a single point.

Z∼N(0,1)Z \sim \mathcal N(0, 1). Approximately what is P(−1≤Z≤1)P(-1 \le Z \le 1)?

  1. 0.683
  2. 0.954
  3. 0.5
  4. 0.997

Within one standard deviation of the mean: about 68.3%. (95.4% is within 2σ, 99.7% within 3σ.)

XX is uniform on [0, 0.5]. What is its density on that interval, and is that allowed?

  1. 2, and yes: densities can exceed 1 as long as the area is 1
  2. 0.5, because a density can't exceed 1
  3. 2, but that's not a valid density
  4. 1, because all uniform densities have height 1

Height × width = area: 2×0.5=12 \times 0.5 = 1. Densities are probability per unit length, so they can be as large as they like over short intervals.

IQ-style scores are N(100,152)\mathcal N(100, 15^2). About what fraction score above 130?

  1. About 2.3%
  2. About 5%
  3. About 16%
  4. About 0.1%

z=(130−100)/15=2z = (130 - 100)/15 = 2. 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]?

  1. 3
  2. 6
  3. 36
  4. 12

(b−a)212=3612=3\frac{(b-a)^2}{12} = \frac{36}{12} = 3. Check with E[X2]−μ2=16∫06x2 dx−9=12−9=3\mathbb E[X^2] - \mu^2 = \frac{1}{6}\int_0^6 x^2\,dx - 9 = 12 - 9 = 3 ✓.

What is the peak height of the N(0,0.12)\mathcal N(0, 0.1^2) density, at x=0x = 0?

  1. About 3.99
  2. About 0.399
  3. 1, since nothing can be more likely than certain
  4. About 0.04

1σ2π=10.1×2.5066≈3.99\frac{1}{\sigma\sqrt{2\pi}} = \frac{1}{0.1 \times 2.5066} \approx 3.99. 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)

Chapter 6

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 ss, the first must show some kk and the second s−ks - k. Add up every way that can happen:

P(X+Y=s)=∑kP(X=k) P(Y=s−k).P(X + Y = s) = \sum_k P(X = k)\,P(Y = s - k).

This operation on two lists of probabilities is called convolution, written pX∗pYp_X * p_Y. One way to picture it: flip one distribution around, slide it along the other, and at each offset ss 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: fX+Y(s)=∫fX(x) fY(s−x) dxf_{X+Y}(s) = \int f_X(x)\,f_Y(s - x)\,dx.

Convolution is messy in general, but two summaries behave beautifully for independent XX and YY:

E[X+Y]=E[X]+E[Y],Var⁡(X+Y)=Var⁡(X)+Var⁡(Y).\mathbb E[X + Y] = \mathbb E[X] + \mathbb E[Y], \qquad \operatorname{Var}(X + Y) = \operatorname{Var}(X) + \operatorname{Var}(Y).

Standard deviations do not add; they combine like the sides of a right triangle, σX+Y=σX2+σY2\sigma_{X+Y} = \sqrt{\sigma_X^2 + \sigma_Y^2}. And one family is closed under addition: the sum of independent Gaussians is exactly Gaussian, N(μ1,σ12)+N(μ2,σ22)=N(μ1+μ2, σ12+σ22)\mathcal N(\mu_1, \sigma_1^2) + \mathcal N(\mu_2, \sigma_2^2) = \mathcal N(\mu_1 + \mu_2,\ \sigma_1^2 + \sigma_2^2). 3Blue1Brown's "pretty reason" uses the round 2D bell from chapter 5: the event x+y=sx + y = s 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 μ\mu and finite variance σ2\sigma^2, and look at their average Xˉn=1n(X1+⋯+Xn)\bar X_n = \frac1n(X_1 + \cdots + X_n). From the rules above, E[Xˉn]=μ\mathbb E[\bar X_n] = \mu and Var⁡(Xˉn)=σ2/n\operatorname{Var}(\bar X_n) = \sigma^2/n. That's the law of large numbers in action: the average homes in on μ\mu, with typical error σ/n\sigma/\sqrt{n}.

The central limit theorem (CLT) says something much stronger about the shape: as nn grows,

Xˉn≈N ⁣(μ, σ2n),\bar X_n \approx \mathcal N\!\left(\mu,\ \frac{\sigma^2}{n}\right),

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.

Each sample is the mean of n draws from the distribution in the corner (pick it from the menu). The teal histogram collects many such means; the gold curve is the CLT's prediction 𝒩(μ, σ²/n). With n = 1 you just see the original shape. Push n up: even the coin and the two-bump shape turn into a bell, and the bell gets narrower like 1/√n. Press Run to watch it build.

Worked exampleFrom two dice to a hundred

  • Convolution by hand: P(sum=4)=P(1)P(3)+P(2)P(2)+P(3)P(1)=3/36P(\text{sum} = 4) = P(1)P(3) + P(2)P(2) + P(3)P(1) = 3/36.
  • One die: μ=3.5\mu = 3.5, σ2=35/12≈2.917\sigma^2 = 35/12 \approx 2.917.
  • Average of 100 dice: mean 3.5, variance 2.917/1002.917/100, standard deviation 2.917/10≈0.171\sqrt{2.917}/10 \approx 0.171.
  • CLT estimate: P(Xˉ>3.84)P(\bar X > 3.84) is about P(Z>2)≈0.023P(Z > 2) \approx 0.023, since 3.84≈3.5+2×0.1713.84 \approx 3.5 + 2 \times 0.171. 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 1/B1/B; 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 ∑iwixi\sum_i w_i x_i 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)

XX and YY are independent with E[X]=2\mathbb E[X] = 2 and E[Y]=3\mathbb E[Y] = 3. What is E[X+Y]\mathbb E[X + Y]?

  1. 5
  2. 6
  3. It depends on their variances
  4. 13\sqrt{13}

Means always add: 2+3=52 + 3 = 5 (this doesn't even need independence).

Independent XX and YY have Var⁡(X)=1\operatorname{Var}(X) = 1 and Var⁡(Y)=4\operatorname{Var}(Y) = 4. What is the standard deviation of X+YX + Y?

  1. 5≈2.24\sqrt{5} \approx 2.24
  2. 3
  3. 5
  4. 2

Variances add: 1+4=51 + 4 = 5, so σ=5\sigma = \sqrt{5}. Adding the standard deviations (1 + 2 = 3) is the classic mistake.

XX is uniform on {0, 1} and YY is uniform on {0, 1, 2}, independent. What is P(X+Y=1)P(X + Y = 1)?

  1. 1/3
  2. 1/6
  3. 1/2
  4. 1/4

The ways are (0, 1) and (1, 0), each with probability 12⋅13=16\frac12 \cdot \frac13 = \frac16. Total: 2/6=1/32/6 = 1/3.

X∼N(1,4)X \sim \mathcal N(1, 4) and Y∼N(2,9)Y \sim \mathcal N(2, 9) are independent (the second number is the variance). What is the distribution of X+YX + Y?

  1. N(3,13)\mathcal N(3, 13)
  2. N(3,5)\mathcal N(3, 5)
  3. N(3,25)\mathcal N(3, 25)
  4. Not Gaussian: a sum of Gaussians is a convolution

Independent Gaussians add to a Gaussian, with means adding (3) and variances adding (13). N(3,25)\mathcal N(3, 25) 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?

  1. 5
  2. 25
  3. 10
  4. 0.5

Each flip is Bernoulli(0.5) with variance 0.25; 100 independent flips have variance 25, so σ=5\sigma = 5. By the CLT the count is about N(50,25)\mathcal N(50, 25): 95% of the time between 40 and 60.

Individual measurements have σ=10\sigma = 10. What is the standard deviation of the mean of 25 of them?

  1. 2
  2. 0.4
  3. 10
  4. 4

σ/n=10/5=2\sigma/\sqrt{n} = 10/5 = 2. (0.4 is 10/2510/25, dividing by nn instead of n\sqrt{n}; 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?

  1. 4 times as many
  2. 2 times as many
  3. 2\sqrt{2} times as many
  4. 8 times as many

The standard error is p(1−p)/n∝1/n\sqrt{p(1-p)/n} \propto 1/\sqrt{n}. Halving it needs n\sqrt{n} to double, so nn 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)

Chapter 7

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 dd random variables into a random vector x=(X1,…,Xd)\mathbf x = (X_1, \ldots, X_d). Its centre is the mean vector μ=E[x]\boldsymbol\mu = \mathbb E[\mathbf x], and its shape is captured by the covariance matrix, the d×dd \times d table of every pairwise covariance:

Σ=E[(x−μ)(x−μ)⊤],Σij=Cov⁡(Xi,Xj).\Sigma = \mathbb E\big[(\mathbf x - \boldsymbol\mu)(\mathbf x - \boldsymbol\mu)^\top\big], \qquad \Sigma_{ij} = \operatorname{Cov}(X_i, X_j).

The diagonal holds the variances Σii=Var⁡(Xi)\Sigma_{ii} = \operatorname{Var}(X_i); the off-diagonal entries say how pairs move together. Σ\Sigma is always symmetric (Cov⁡(Xi,Xj)=Cov⁡(Xj,Xi)\operatorname{Cov}(X_i, X_j) = \operatorname{Cov}(X_j, X_i)) and positive semi-definite: for any direction u\mathbf u, the variance of the projection u⊤x\mathbf u^\top\mathbf x is u⊤Σu≥0\mathbf u^\top\Sigma\mathbf u \ge 0. That last formula is worth remembering: the covariance matrix tells you the variance in every direction.

The density

The multivariate Gaussian N(μ,Σ)\mathcal N(\boldsymbol\mu, \Sigma) has density

f(x)=1(2π)ddet⁡Σexp⁡ ⁣(−12(x−μ)⊤Σ−1(x−μ)).f(\mathbf x) = \frac{1}{\sqrt{(2\pi)^d \det\Sigma}}\exp\!\Big(-\tfrac12(\mathbf x - \boldsymbol\mu)^\top\Sigma^{-1}(\mathbf x - \boldsymbol\mu)\Big).

It's the 1D formula with each piece upgraded: (x−μ)2/σ2(x-\mu)^2/\sigma^2 becomes the quadratic form (x−μ)⊤Σ−1(x−μ)(\mathbf x - \boldsymbol\mu)^\top\Sigma^{-1}(\mathbf x - \boldsymbol\mu), whose square root is the Mahalanobis distance, "how many standard deviations away, accounting for the shape". And σ\sigma becomes det⁡Σ\sqrt{\det\Sigma}: from Linear Algebra, the determinant is how much Σ\Sigma stretches volume.

Ellipses are eigenvectors

Points of equal density have equal Mahalanobis distance, so the contours are the curves (x−μ)⊤Σ−1(x−μ)=c(\mathbf x - \boldsymbol\mu)^\top\Sigma^{-1}(\mathbf x - \boldsymbol\mu) = c. Which shape is that? Because Σ\Sigma is symmetric, the spectral theorem (Linear Algebra, chapter 14) says it has perpendicular eigenvectors v1,v2\mathbf v_1, \mathbf v_2 with eigenvalues λ1,λ2≥0\lambda_1, \lambda_2 \ge 0:

Σ=λ1v1v1⊤+λ2v2v2⊤.\Sigma = \lambda_1\mathbf v_1\mathbf v_1^\top + \lambda_2\mathbf v_2\mathbf v_2^\top.

In the eigenvector coordinates, Σ\Sigma is just diagonal: the data is spread with variance λ1\lambda_1 along v1\mathbf v_1 and λ2\lambda_2 along v2\mathbf v_2, independently. So the contours are ellipses with axes along the eigenvectors and semi-axis lengths λ1,λ2\sqrt{\lambda_1}, \sqrt{\lambda_2} (times c\sqrt{c}). 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 z\mathbf z, then set x=μ+Az\mathbf x = \boldsymbol\mu + A\mathbf z for any AA with AA⊤=ΣAA^\top = \Sigma, because a linear map transforms covariance as Cov⁡(Az)=A Cov⁡(z) A⊤\operatorname{Cov}(A\mathbf z) = A\,\operatorname{Cov}(\mathbf z)\,A^\top. The figure uses A=[λ1v1  λ2v2]A = [\sqrt{\lambda_1}\mathbf v_1\ \ \sqrt{\lambda_2}\mathbf v_2]: stretch a round cloud along the eigenvectors. In code people use the Cholesky factor.

Drag the green tip to turn and stretch the long axis, the red tip to set the short axis, and the dark centre to move the mean. The readout shows the resulting Σ. The ellipses are the 1σ and 2σ contours, and the arrows are the eigenvectors of Σ scaled by √λ: the ellipse's axes are the eigenvectors. You can also type a symmetric Σ and watch its eigenvectors appear.

Worked exampleΣ = [[3, 1], [1, 3]]

  • Variances 3 and 3, covariance 1, so the correlation is ρ=1/3⋅3=1/3\rho = 1/\sqrt{3 \cdot 3} = 1/3.
  • Eigenvalues: trace 6, determinant 9−1=89 - 1 = 8, so λ2−6λ+8=0\lambda^2 - 6\lambda + 8 = 0 gives λ1=4\lambda_1 = 4, λ2=2\lambda_2 = 2.
  • Eigenvectors: v1=(1,1)/2\mathbf v_1 = (1, 1)/\sqrt{2} (check: Σ(1,1)=(4,4)\Sigma(1,1) = (4, 4) ✓) and v2=(1,−1)/2\mathbf v_2 = (1, -1)/\sqrt{2}.
  • So the cloud is tilted at 45°, with standard deviation 4=2\sqrt{4} = 2 along the diagonal and 2≈1.41\sqrt{2} \approx 1.41 across it. The variance along (1,0)(1,0) is e1⊤Σ e1=3\mathbf e_1^\top\Sigma\,\mathbf e_1 = 3, 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 II. 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 "AzA\mathbf z" sampling trick is exactly the reparameterisation trick from chapter 5 in many dimensions.

Practice (pick one answer per question)

Σ=[4001]\Sigma = \begin{bmatrix}4 & 0\\ 0 & 1\end{bmatrix}. What is the standard deviation of X1X_1?

  1. 2
  2. 4
  3. 1
  4. 16

The diagonal entry is the variance, 4, so the standard deviation is 4=2\sqrt{4} = 2.

What do the off-diagonal entries of a covariance matrix tell you?

  1. How each pair of features varies together
  2. The variance of each feature
  3. The mean of each feature
  4. The eigenvalues of the matrix

Σij=Cov⁡(Xi,Xj)\Sigma_{ij} = \operatorname{Cov}(X_i, X_j) for i≠ji \ne j. The diagonal holds the variances.

Σ=[2112]\Sigma = \begin{bmatrix}2 & 1\\ 1 & 2\end{bmatrix}. What are its eigenvalues, and along which direction is the ellipse longest?

  1. 3 and 1; along (1, 1)
  2. 3 and 1; along (1, −1)
  3. 2 and 2; it's a circle
  4. 2 and 1; along (1, 0)

Σ(1,1)=(3,3)\Sigma(1,1) = (3,3) and Σ(1,−1)=(1,−1)\Sigma(1,-1) = (1,-1), so the eigenvalues are 3 and 1. The larger one belongs to (1, 1): positive covariance tilts the cloud up and to the right.

Σ=[4229]\Sigma = \begin{bmatrix}4 & 2\\ 2 & 9\end{bmatrix}. What is the correlation between X1X_1 and X2X_2?

  1. 1/3
  2. 2
  3. 2/13
  4. 1/18

ρ=Cov⁡σ1σ2=22×3=13\rho = \frac{\operatorname{Cov}}{\sigma_1\sigma_2} = \frac{2}{2 \times 3} = \frac13.

z∼N(0,I)\mathbf z \sim \mathcal N(\mathbf 0, I) in 2D and y=Az\mathbf y = A\mathbf z with A=[2011]A = \begin{bmatrix}2 & 0\\ 1 & 1\end{bmatrix}. What is Cov⁡(y)\operatorname{Cov}(\mathbf y)?

  1. [4222]\begin{bmatrix}4 & 2\\ 2 & 2\end{bmatrix}
  2. [5111]\begin{bmatrix}5 & 1\\ 1 & 1\end{bmatrix}
  3. [2011]\begin{bmatrix}2 & 0\\ 1 & 1\end{bmatrix}
  4. [4011]\begin{bmatrix}4 & 0\\ 1 & 1\end{bmatrix}

Cov⁡(Az)=AIA⊤=AA⊤\operatorname{Cov}(A\mathbf z) = AIA^\top = AA^\top. Rows of AA are (2, 0) and (1, 1): their dot products give 4,2,2,24, 2, 2, 2. (A⊤AA^\top A gives the second option, which is the wrong order.)

Which of these cannot be a covariance matrix?

  1. [1221]\begin{bmatrix}1 & 2\\ 2 & 1\end{bmatrix}
  2. [2112]\begin{bmatrix}2 & 1\\ 1 & 2\end{bmatrix}
  3. [1000]\begin{bmatrix}1 & 0\\ 0 & 0\end{bmatrix}
  4. [5−2−21]\begin{bmatrix}5 & -2\\ -2 & 1\end{bmatrix}

[[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 2/1⋅1=22/\sqrt{1 \cdot 1} = 2 is above 1. The others are positive semi-definite (the diagonal one is a flat, degenerate Gaussian, which is allowed).

With μ=0\boldsymbol\mu = \mathbf 0 and Σ=[4001]\Sigma = \begin{bmatrix}4 & 0\\ 0 & 1\end{bmatrix}, what is the Mahalanobis distance of the point (2, 1)?

  1. 2≈1.41\sqrt{2} \approx 1.41
  2. 5≈2.24\sqrt{5} \approx 2.24
  3. 2
  4. 17≈4.12\sqrt{17} \approx 4.12

x⊤Σ−1x=224+121=1+1=2\mathbf x^\top\Sigma^{-1}\mathbf x = \frac{2^2}{4} + \frac{1^2}{1} = 1 + 1 = 2, so the distance is 2\sqrt{2}. The point is 1σ out in each direction. Its Euclidean distance is 5\sqrt{5}, 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)

Chapter 8

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 θ=P(heads)\theta = P(\text{heads}) ten times and see 7 heads. What's your best guess for θ\theta?

For any candidate θ\theta, the probability of exactly this sequence of flips is θ7(1−θ)3\theta^7(1-\theta)^3. Read as a function of θ\theta with the data held fixed, that's the likelihood:

L(θ)=p(data∣θ)=∏i=1np(xi∣θ).L(\theta) = p(\text{data} \mid \theta) = \prod_{i=1}^n p(x_i \mid \theta).

The product comes from independence (chapter 1). The maximum likelihood estimate (MLE) θ^\hat\theta is the θ\theta that makes the observed data most probable. For the coin you can see on the figure that L(θ)=θ7(1−θ)3L(\theta) = \theta^7(1-\theta)^3 peaks at 0.7.

Important: L(θ)L(\theta) is not a probability distribution over θ\theta. It doesn't integrate to 1 over θ\theta (here the area is 1/13201/1320), and it doesn't tell you "the probability that θ=0.7\theta = 0.7". It only ranks parameter values by how well they explain the data. Turning it into beliefs about θ\theta needs a prior: that's chapter 9.

Take the log

Products of many small numbers are awful to work with: 10001000 probabilities of about 0.5 multiply to 10−30110^{-301}, 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:

ℓ(θ)=log⁡L(θ)=∑i=1nlog⁡p(xi∣θ).\ell(\theta) = \log L(\theta) = \sum_{i=1}^n \log p(x_i \mid \theta).

ML libraries minimise, so they use the negative log-likelihood (NLL), −ℓ(θ)-\ell(\theta). Minimising NLL and maximising likelihood find the same θ^\hat\theta.

Two classic answers

Coin. With hh heads and tt tails, ℓ(θ)=hlog⁡θ+tlog⁡(1−θ)\ell(\theta) = h\log\theta + t\log(1-\theta). Setting the derivative to zero, hθ−t1−θ=0\frac h\theta - \frac t{1-\theta} = 0, gives

θ^=hh+t,\hat\theta = \frac{h}{h+t},

the fraction of heads, as you'd hope.

Gaussian. For data x1,…,xnx_1, \ldots, x_n from N(μ,σ2)\mathcal N(\mu, \sigma^2), each point contributes log⁡p(xi)=−(xi−μ)22σ2−log⁡σ−12log⁡2π\log p(x_i) = -\frac{(x_i-\mu)^2}{2\sigma^2} - \log\sigma - \frac12\log 2\pi. Maximising over μ\mu means minimising ∑i(xi−μ)2\sum_i (x_i - \mu)^2, a sum of squared errors, which is solved by the sample mean. Then maximising over σ\sigma gives the average squared deviation:

μ^=1n∑ixi,σ^2=1n∑i(xi−μ^)2.\hat\mu = \frac1n\sum_i x_i, \qquad \hat\sigma^2 = \frac1n\sum_i (x_i - \hat\mu)^2.

Notice the 1n\frac1n, not the 1n−1\frac1{n-1} 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 n−1n-1 version corrects that. For large nn the difference vanishes.

Set the number of heads and tails, or flip a coin whose true bias is 0.3 one flip at a time. The teal curve is the likelihood θ^h(1 − θ)^t, scaled so its peak is 1; the dashed line marks the MLE h/(h + t). Drag the gold point to compare any θ with the best one. As the data grows the curve gets narrower: more data, more certainty. Tick Log-likelihood to see the same curve as the sum of logs.

Worked example7 heads in 10 flips

  • L(0.7)=0.77×0.33≈0.0823×0.027≈0.00222L(0.7) = 0.7^7 \times 0.3^3 \approx 0.0823 \times 0.027 \approx 0.00222.
  • L(0.5)=0.510≈0.000977L(0.5) = 0.5^{10} \approx 0.000977.
  • Ratio: L(0.7)/L(0.5)≈2.28L(0.7)/L(0.5) \approx 2.28. The data favour θ=0.7\theta = 0.7 over a fair coin, but only by a factor of about 2: ten flips aren't much evidence.
  • NLL at the peak: −7ln⁡0.7−3ln⁡0.3≈2.497+3.612=6.109-7\ln 0.7 - 3\ln 0.3 \approx 2.497 + 3.612 = 6.109 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 θ^=1\hat\theta = 1, 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 w\mathbf w defines a distribution p(y∣x,w)p(y \mid \mathbf x, \mathbf w), and the loss is the average NLL of the training labels: −1n∑ilog⁡p(yi∣xi,w)-\frac1n\sum_i \log p(y_i \mid \mathbf x_i, \mathbf w). 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 θ=P(heads)\theta = P(\text{heads})?

  1. 0.6
  2. 0.5
  3. 12
  4. 0.4

θ^=h/n=12/20=0.6\hat\theta = h/n = 12/20 = 0.6.

Why do we usually maximise the log-likelihood instead of the likelihood?

  1. It turns a product into a sum, avoids numerical underflow, and has the same maximiser
  2. It gives a different, more accurate answer
  3. The likelihood can be negative, the log can't
  4. 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 μ^\hat\mu?

  1. 5
  2. 4
  3. 15
  4. 4.5

The MLE of the mean is the sample mean: (2+4+9)/3=5(2 + 4 + 9)/3 = 5. (4 is the median.)

Same data, 2, 4, 9. What is the MLE of the variance, σ^2\hat\sigma^2?

  1. 26/3 ≈ 8.67
  2. 13
  3. 26
  4. 26/3≈2.94\sqrt{26/3} \approx 2.94

Deviations from 5 are −3, −1, 4; squares 9, 1, 16; sum 26. The MLE divides by n=3n = 3: 26/3≈8.6726/3 \approx 8.67. (13 divides by n−1n - 1; 2.94 is σ^\hat\sigma.)

With 7 heads in 10 flips, how many times more likely is the data under θ=0.7\theta = 0.7 than under θ=0.5\theta = 0.5?

  1. About 2.28
  2. 1.4
  3. About 0.44
  4. About 7

0.77×0.330.510≈0.0022240.000977≈2.28\frac{0.7^7 \times 0.3^3}{0.5^{10}} \approx \frac{0.002224}{0.000977} \approx 2.28. (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?

  1. 0, so any text containing the word gets probability 0 (infinite NLL)
  2. 1/10 000, which is a fine estimate
  3. The MLE doesn't exist when a count is 0
  4. 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 =−log⁡0=∞= -\log 0 = \infty. That's maximum likelihood overfitting; smoothing, which is a prior, fixes it.

Waiting times are modelled as exponential with density λe−λx\lambda e^{-\lambda x} for x≥0x \ge 0. You observe 1, 2 and 3 minutes. What is the MLE of λ\lambda?

  1. 0.5 per minute
  2. 2 per minute
  3. 6 per minute
  4. 3 per minute

ℓ(λ)=∑i(log⁡λ−λxi)=3log⁡λ−6λ\ell(\lambda) = \sum_i(\log\lambda - \lambda x_i) = 3\log\lambda - 6\lambda. Setting ℓ′(λ)=3/λ−6=0\ell'(\lambda) = 3/\lambda - 6 = 0 gives λ^=3/6=0.5\hat\lambda = 3/6 = 0.5: 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)

Chapter 9

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 θ\theta itself as uncertain and apply Bayes' rule:

p(θ∣data)⏟posterior=p(data∣θ)⏞likelihood  p(θ)⏞priorp(data)  ∝  p(data∣θ) p(θ).\underbrace{p(\theta \mid \text{data})}_{\text{posterior}} = \frac{\overbrace{p(\text{data} \mid \theta)}^{\text{likelihood}}\;\overbrace{p(\theta)}^{\text{prior}}}{p(\text{data})} \;\propto\; p(\text{data} \mid \theta)\,p(\theta).

The denominator doesn't depend on θ\theta, so for finding the best θ\theta 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:

θ^MAP=arg⁡min⁡θ  [−log⁡p(data∣θ)⏟NLL: fit the data  − log⁡p(θ)⏟penalty: stay plausible].\hat\theta_{\text{MAP}} = \arg\min_\theta\;\Big[\underbrace{-\log p(\text{data} \mid \theta)}_{\text{NLL: fit the data}}\;\underbrace{-\,\log p(\theta)}_{\text{penalty: stay plausible}}\Big].

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 θ\theta is the Beta(a, b) distribution, with density proportional to θa−1(1−θ)b−1\theta^{a-1}(1-\theta)^{b-1}. Multiply by the likelihood θh(1−θ)t\theta^h(1-\theta)^t and the posterior has the same form, θh+a−1(1−θ)t+b−1\theta^{h+a-1}(1-\theta)^{t+b-1}: it's Beta(a+h, b+ta + h,\ b + t). So the prior acts like a−1a-1 imaginary heads and b−1b-1 imaginary tails added to the data, and

θ^MAP=h+a−1n+a+b−2,E[θ∣data]=h+an+a+b.\hat\theta_{\text{MAP}} = \frac{h + a - 1}{n + a + b - 2}, \qquad \mathbb E[\theta \mid \text{data}] = \frac{h + a}{n + a + b}.

With the flat prior Beta(1, 1), MAP equals the MLE. With Beta(1, 1) the posterior mean is h+1n+2\frac{h+1}{n+2}, 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 11/12≈0.91711/12 \approx 0.917, while 48 out of 50 gives 49/52≈0.94249/52 \approx 0.942.

As data piles up, hh and tt swamp aa and bb, and MAP converges to the MLE. Priors matter most when data is scarce, exactly when the MLE is least trustworthy.

The purple dashed curve is the Beta(a, b) prior, the teal dotted curve is the likelihood of the data (scaled to area 1), and the gold curve is the posterior, their normalised product. Start with 9 heads and 1 tail: the MLE says 0.9 but the prior pulls the MAP back toward 0.5. Now slide heads and tails up together and watch the likelihood overpower the prior.

Regularization is a prior

Now the payoff for ML. Take a linear model with Gaussian noise, yi=w⊤xi+εiy_i = \mathbf w^\top\mathbf x_i + \varepsilon_i with εi∼N(0,σ2)\varepsilon_i \sim \mathcal N(0, \sigma^2). The NLL is 12σ2∑i(yi−w⊤xi)2\frac1{2\sigma^2}\sum_i (y_i - \mathbf w^\top\mathbf x_i)^2 plus a constant: squared error (chapter 12 says more).

  • Gaussian prior wj∼N(0,τ2)w_j \sim \mathcal N(0, \tau^2): −log⁡p(w)=12τ2∑jwj2+const-\log p(\mathbf w) = \frac{1}{2\tau^2}\sum_j w_j^2 + \text{const}. Multiply everything by 2σ22\sigma^2 and MAP minimises ∑i(yi−w⊤xi)2+λ∥w∥22,λ=σ2/τ2.\sum_i (y_i - \mathbf w^\top\mathbf x_i)^2 + \lambda\|\mathbf w\|_2^2, \qquad \lambda = \sigma^2/\tau^2. That's ridge regression, or L2 regularization, called weight decay in deep learning. A tighter prior (smaller τ\tau) means a bigger λ\lambda.
  • Laplace prior p(wj)∝e−∣wj∣/bp(w_j) \propto e^{-|w_j|/b}: −log⁡p(w)=1b∑j∣wj∣+const-\log p(\mathbf w) = \frac1b\sum_j |w_j| + \text{const}, giving the lasso or L1 regularization, λ∥w∥1\lambda\|\mathbf w\|_1.

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 (w−a)2+λw2(w - a)^2 + \lambda w^2 gives w=a1+λw = \frac{a}{1+\lambda}: shrunk, but never zero unless aa is. Minimising (w−a)2+λ∣w∣(w - a)^2 + \lambda|w| gives w=sign⁡(a)max⁡(∣a∣−λ/2, 0)w = \operatorname{sign}(a)\max(|a| - \lambda/2,\ 0), the soft threshold: whenever the data's pull ∣a∣|a| is weaker than λ/2\lambda/2, the kink wins and ww snaps to exactly 0.

Drag the teal handle to set where the data alone would put a weight (w_data); the slider sets the penalty strength λ. Blue is the L2 objective, gold the L1 objective, and the dots are their minima. L2 always lands a fixed fraction of the way to w_data. Drag w_data close to 0 and the L1 minimum sticks at exactly 0, held there by the kink.

Worked exampleThree heads in three flips

  • MLE: 3/3=13/3 = 1. Absurdly confident.
  • Prior Beta(2, 2), gently favouring fairness (like 1 imaginary head and 1 imaginary tail): MAP =3+13+2=0.8= \frac{3 + 1}{3 + 2} = 0.8.
  • Posterior mean =3+23+4=5/7≈0.714= \frac{3+2}{3+4} = 5/7 \approx 0.714.
  • After 300 heads in 300 flips, MAP =301/302≈0.997= 301/302 \approx 0.997: 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…

  1. likelihood × prior
  2. likelihood + prior
  3. likelihood ÷ prior
  4. the likelihood alone

Bayes' rule: p(θ∣D)∝p(D∣θ) p(θ)p(\theta \mid D) \propto p(D \mid \theta)\,p(\theta). In logs this becomes a sum, which is where "loss + penalty" comes from.

With a completely flat prior, the MAP estimate equals…

  1. the MLE
  2. the prior mean
  3. 0
  4. 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 θ\theta?

  1. 10/14 ≈ 0.714
  2. 0.8
  3. 11/16 ≈ 0.688
  4. 0.5

h+a−1n+a+b−2=8+210+4=1014\frac{h + a - 1}{n + a + b - 2} = \frac{8 + 2}{10 + 4} = \frac{10}{14}. (0.8 is the MLE; 11/16 is the posterior mean.)

Adding λ∥w∥22\lambda\|\mathbf w\|_2^2 to a squared-error loss corresponds to which prior on the weights?

  1. A zero-mean Gaussian
  2. A Laplace distribution
  3. A uniform distribution
  4. No prior: it's just a penalty

−log⁡-\log of a Gaussian density is a quadratic, w22τ2\frac{w^2}{2\tau^2} + 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?

  1. Laplace, giving an L1 penalty
  2. Gaussian, giving an L2 penalty
  3. A very wide Gaussian
  4. A flat prior

The Laplace prior's penalty ∣w∣|w| 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 (w−3)2+λw2(w - 3)^2 + \lambda w^2 with λ=2\lambda = 2. What is ww?

  1. 1
  2. 1.5
  3. 3
  4. 0

Derivative: 2(w−3)+2λw=02(w - 3) + 2\lambda w = 0, so w=31+λ=1w = \frac{3}{1 + \lambda} = 1. L2 shrinks by the factor 1/(1+λ)1/(1+\lambda).

Minimise (w−0.4)2+λ∣w∣(w - 0.4)^2 + \lambda|w| with λ=1\lambda = 1. What is ww?

  1. 0
  2. 0.2
  3. −0.1
  4. 0.4

For w>0w > 0 the derivative is 2(w−0.4)+12(w - 0.4) + 1, zero at w=−0.1w = -0.1, which isn't positive, so there's no minimum with w>0w > 0. Similarly none with w<0w < 0. So the minimum is at the kink, w=0w = 0. Soft threshold: max⁡(0.4−λ/2,0)=max⁡(−0.1,0)=0\max(0.4 - \lambda/2, 0) = \max(-0.1, 0) = 0. (−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)

Chapter 10

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 pp is

I(x)=−log⁡2p(x) bits.I(x) = -\log_2 p(x) \text{ bits}.

Why the log? Because information from independent events should add: two independent coin flips carry twice the information of one, while their probabilities multiply, 12×12=14\frac12 \times \frac12 = \frac14. The log turns multiplication into addition: −log⁡214=2-\log_2\frac14 = 2 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 1/2k1/2^k is like one of 2k2^k equally likely options, and you'd need kk 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:

H(p)=E[−log⁡2p(X)]=−∑xp(x)log⁡2p(x).H(p) = \mathbb E[-\log_2 p(X)] = -\sum_x p(x)\log_2 p(x).

(Outcomes with p(x)=0p(x) = 0 contribute 0, since they never happen.) Entropy measures uncertainty:

  • It's 0 when one outcome is certain: no surprise ever.
  • It's at most log⁡2K\log_2 K for KK outcomes, reached only by the uniform distribution: maximum uncertainty.
  • For a coin with bias pp, H=−plog⁡2p−(1−p)log⁡2(1−p)H = -p\log_2 p - (1-p)\log_2(1-p), which peaks at 1 bit for a fair coin and drops to 0 at p=0p = 0 or 1.

Shannon's source coding theorem makes this concrete: you can't compress draws from pp into fewer than H(p)H(p) bits each on average, and you can get arbitrarily close. Common symbols get short codes, rare ones long codes, about −log⁡2p-\log_2 p bits each.

Units: with log⁡2\log_2 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 qq of the words, seeing it gives −log⁡2q-\log_2 q 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 H(parent)−∑childrenncnH(child)H(\text{parent}) - \sum_{\text{children}} \frac{n_c}{n}H(\text{child}). This is a special case of mutual information, I(X;Y)=H(Y)−H(Y∣X)I(X; Y) = H(Y) - H(Y \mid X): how much knowing XX reduces your uncertainty about YY.

Drag the bar tops to reshape a categorical distribution (the rest rescale to keep the total at 1). Under each probability is its surprise in bits, and the readout gives the entropy, the probability-weighted average of those surprises. Press Uniform to hit the maximum log₂ K, and Certain to hit 0. Change the number of outcomes and see the maximum grow like log₂ K.

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: 12⋅1+14⋅2+18⋅3+18⋅3=1.75\frac12 \cdot 1 + \frac14 \cdot 2 + \frac18 \cdot 3 + \frac18 \cdot 3 = 1.75 bits.
  • A code that achieves it: A = 0, B = 10, C = 110, D = 111. Average length =0.5⋅1+0.25⋅2+0.125⋅3⋅2=1.75= 0.5 \cdot 1 + 0.25 \cdot 2 + 0.125 \cdot 3 \cdot 2 = 1.75 bits, better than the 2 bits a fixed-length code needs.
  • If all four were equally likely, the entropy would be log⁡24=2\log_2 4 = 2 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?

  1. 3 bits
  2. 8 bits
  3. 1/8 bit
  4. −3 bits

−log⁡2(1/8)=log⁡28=3-\log_2(1/8) = \log_2 8 = 3 bits: it's like identifying one of 8 equally likely options.

What is the entropy of a fair coin flip?

  1. 1 bit
  2. 0.5 bits
  3. 2 bits
  4. 0 bits

−12log⁡212−12log⁡212=12+12=1-\frac12\log_2\frac12 - \frac12\log_2\frac12 = \frac12 + \frac12 = 1 bit.

What is the entropy of a uniform distribution over 32 outcomes?

  1. 5 bits
  2. 32 bits
  3. 1/32 bit
  4. 16 bits

log⁡232=5\log_2 32 = 5 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. 1.5 bits
  2. 1.585 bits
  3. 1 bit
  4. 2 bits

0.5⋅1+0.25⋅2+0.25⋅2=1.50.5 \cdot 1 + 0.25 \cdot 2 + 0.25 \cdot 2 = 1.5 bits. (1.585 = log⁡23\log_2 3 would be the uniform distribution over 3, the maximum.)

A coin lands heads 90% of the time. What is its entropy?

  1. About 0.469 bits
  2. About 0.9 bits
  3. About 0.152 bits
  4. About 0.1 bits

−0.9log⁡20.9−0.1log⁡20.1≈0.9×0.152+0.1×3.322≈0.137+0.332=0.469-0.9\log_2 0.9 - 0.1\log_2 0.1 \approx 0.9 \times 0.152 + 0.1 \times 3.322 \approx 0.137 + 0.332 = 0.469 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?

  1. About 0.72 bits
  2. 1 bit
  3. About 2.32 bits
  4. About 0.32 bits

You land in the 800 group with probability 0.8 (gaining −log⁡20.8≈0.32-\log_2 0.8 \approx 0.32 bits) or the 200 group with probability 0.2 (gaining −log⁡20.2≈2.32-\log_2 0.2 \approx 2.32 bits). The average is 0.8×0.32+0.2×2.32≈0.720.8 \times 0.32 + 0.2 \times 2.32 \approx 0.72 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?

  1. About 0.531 bits
  2. About 0.469 bits
  3. 1 bit
  4. 0.8 bits

Parent entropy 1 bit. Each child has entropy H(0.9,0.1)≈0.469H(0.9, 0.1) \approx 0.469, and they're weighted ½ each, so the average child entropy is 0.469. Gain =1−0.469=0.531= 1 - 0.469 = 0.531 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)

Chapter 11

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, pp (where the data really comes from), and the model's, qq (what we predict). When an outcome xx happens, we are surprised by −log⁡q(x)-\log q(x), because qq is what we believed. Averaging over what actually happens gives the cross-entropy:

H(p,q)=Ex∼p[−log⁡q(x)]=−∑xp(x)log⁡q(x).H(p, q) = \mathbb E_{x \sim p}[-\log q(x)] = -\sum_x p(x)\log q(x).

In coding terms: if you design a code that's optimal for qq (about −log⁡2q(x)-\log_2 q(x) bits for symbol xx) but the symbols actually come from pp, then H(p,q)H(p, q) is your average code length.

You can never do better than coding for the truth: H(p,q)≥H(p)H(p, q) \ge H(p), with equality only when q=pq = p (this is called Gibbs' inequality). The extra cost is the Kullback–Leibler divergence:

DKL(p ∥ q)=H(p,q)−H(p)=∑xp(x)log⁡p(x)q(x)  ≥  0.D_{\mathrm{KL}}(p\,\|\,q) = H(p, q) - H(p) = \sum_x p(x)\log\frac{p(x)}{q(x)} \;\ge\; 0.

KL measures how different qq is from pp, in a specific sense: the expected extra surprise (or extra bits) from using qq when the truth is pp.

Three properties worth remembering

  • It's zero exactly when the distributions match, and positive otherwise.
  • It isn't symmetric: DKL(p ∥ q)≠DKL(q ∥ p)D_{\mathrm{KL}}(p\,\|\,q) \ne D_{\mathrm{KL}}(q\,\|\,p) in general. So it's a "divergence", not a true distance. The two directions ask different questions: DKL(p∥q)D_{\mathrm{KL}}(p\|q) averages over pp, so it heavily punishes qq for being small where pp is large; DKL(q∥p)D_{\mathrm{KL}}(q\|p) averages over qq, so it punishes qq for putting mass where pp has little.
  • It can be infinite. If q(x)=0q(x) = 0 for an outcome that pp says can happen, then −log⁡q(x)=∞-\log q(x) = \infty: you said it was impossible, and it happened. That's why models should never assign exactly zero probability.

The asymmetry matters when you fit qq to pp. Minimising forward KL DKL(p∥q)D_{\mathrm{KL}}(p\|q) makes qq "cover" everywhere pp has mass, spreading out if it must (mode-covering). Minimising reverse KL DKL(q∥p)D_{\mathrm{KL}}(q\|p) makes qq avoid places pp 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 qθq_\theta, the truth pp is fixed, so H(p)H(p) is a constant. Therefore

arg⁡min⁡θH(p,qθ)=arg⁡min⁡θ[H(p)+DKL(p ∥ qθ)]=arg⁡min⁡θDKL(p ∥ qθ).\arg\min_\theta H(p, q_\theta) = \arg\min_\theta \big[H(p) + D_{\mathrm{KL}}(p\,\|\,q_\theta)\big] = \arg\min_\theta D_{\mathrm{KL}}(p\,\|\,q_\theta).

Minimising cross-entropy is minimising KL from the truth to the model. And when pp is the empirical distribution of the training data, H(p,qθ)=−1n∑ilog⁡qθ(xi)H(p, q_\theta) = -\frac1n\sum_i \log q_\theta(x_i) is exactly the average negative log-likelihood from chapter 8. Three names, one objective: minimise cross-entropy = minimise KL = maximise likelihood.

Gold bars are the true distribution p, purple bars are the model q; drag either set of bar tops. The readout shows H(p), the cross-entropy H(p, q), and the KL divergence in both directions. Press Make q = p to get KL = 0, then Swap p and q to see the two directions disagree. q nearly misses outcome 1 shows how fast D_KL(p‖q) explodes when q puts almost no mass where p does.

Worked exampleA fair coin, modelled badly

Truth p=(0.5,0.5)p = (0.5, 0.5), model q=(0.9,0.1)q = (0.9, 0.1), in bits.

  • H(p)=1H(p) = 1 bit.
  • H(p,q)=−0.5log⁡20.9−0.5log⁡20.1≈0.5(0.152)+0.5(3.322)=1.737H(p, q) = -0.5\log_2 0.9 - 0.5\log_2 0.1 \approx 0.5(0.152) + 0.5(3.322) = 1.737 bits.
  • DKL(p ∥ q)=1.737−1=0.737D_{\mathrm{KL}}(p\,\|\,q) = 1.737 - 1 = 0.737 bits.
  • The other direction: DKL(q ∥ p)=0.9log⁡20.90.5+0.1log⁡20.10.5≈0.763−0.232=0.531D_{\mathrm{KL}}(q\,\|\,p) = 0.9\log_2\frac{0.9}{0.5} + 0.1\log_2\frac{0.1}{0.5} \approx 0.763 - 0.232 = 0.531 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 pp they differ by the constant H(p)H(p), 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 H(p)>0H(p) > 0.

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 DKL(p ∥ p)D_{\mathrm{KL}}(p\,\|\,p)?

  1. 0
  2. H(p)H(p)
  3. 1
  4. It depends on pp

Every term is p(x)log⁡p(x)p(x)=p(x)log⁡1=0p(x)\log\frac{p(x)}{p(x)} = p(x)\log 1 = 0. A distribution doesn't diverge from itself.

Which inequality always holds?

  1. H(p,q)≥H(p)H(p, q) \ge H(p)
  2. H(p,q)≤H(p)H(p, q) \le H(p)
  3. DKL(p ∥ q)≤0D_{\mathrm{KL}}(p\,\|\,q) \le 0
  4. H(p,q)=H(q,p)H(p, q) = H(q, p)

Coding with the wrong distribution can only cost extra bits: H(p,q)=H(p)+DKL(p∥q)H(p,q) = H(p) + D_{\mathrm{KL}}(p\|q) with DKL≥0D_{\mathrm{KL}} \ge 0.

The true label is one-hot, p=(1,0)p = (1, 0), and the model predicts q=(0.25,0.75)q = (0.25, 0.75). What is the cross-entropy H(p,q)H(p, q) in bits?

  1. 2 bits
  2. 0.415 bits
  3. 0.25 bits
  4. 0.811 bits

Only the true class counts: −1⋅log⁡20.25=2-1 \cdot \log_2 0.25 = 2 bits. With a one-hot target, cross-entropy is just the surprise of the correct answer. (0.415 is −log⁡20.75-\log_2 0.75, the surprise of the wrong class.)

p=(0.5,0.5)p = (0.5, 0.5) and q=(0.25,0.75)q = (0.25, 0.75). What is DKL(p ∥ q)D_{\mathrm{KL}}(p\,\|\,q) in bits?

  1. About 0.208
  2. About 0.189
  3. About 1.208
  4. 0

0.5log⁡20.50.25+0.5log⁡20.50.75=0.5(1)+0.5(−0.585)≈0.2080.5\log_2\frac{0.5}{0.25} + 0.5\log_2\frac{0.5}{0.75} = 0.5(1) + 0.5(-0.585) \approx 0.208. (1.208 is the cross-entropy H(p,q)H(p,q); 0.189 is the other direction.)

Same p=(0.5,0.5)p = (0.5, 0.5) and q=(0.25,0.75)q = (0.25, 0.75). What is DKL(q ∥ p)D_{\mathrm{KL}}(q\,\|\,p) in bits?

  1. About 0.189
  2. About 0.208, the same as DKL(p ∥ q)D_{\mathrm{KL}}(p\,\|\,q)
  3. About −0.208
  4. About 0.811

0.25log⁡20.250.5+0.75log⁡20.750.5=−0.25+0.75(0.585)≈0.1890.25\log_2\frac{0.25}{0.5} + 0.75\log_2\frac{0.75}{0.5} = -0.25 + 0.75(0.585) \approx 0.189. Close to, but not equal to, the forward direction: KL isn't symmetric, and it's never negative. (0.811 is H(q)H(q).)

A model assigns probability exactly 0 to an outcome that actually happens 10% of the time. What is DKL(p ∥ q)D_{\mathrm{KL}}(p\,\|\,q)?

  1. Infinite
  2. 0.1 times something finite
  3. 0, because the outcome is rare
  4. Undefined but treated as 0

That outcome contributes 0.1×log⁡0.10=∞0.1 \times \log\frac{0.1}{0} = \infty. The model said "impossible" and was wrong, so its expected surprise is unbounded. This is why softmax outputs are never exactly 0.

Soft targets p=(0.7,0.2,0.1)p = (0.7, 0.2, 0.1) (say, a teacher's predictions in distillation). Among all model outputs qq, which minimises the cross-entropy H(p,q)H(p, q), and what is the minimum?

  1. q=pq = p, and the minimum is H(p)≈1.157H(p) \approx 1.157 bits
  2. q=(1,0,0)q = (1, 0, 0), and the minimum is 0
  3. q=(1/3,1/3,1/3)q = (1/3, 1/3, 1/3), and the minimum is log⁡23\log_2 3
  4. q=pq = p, and the minimum is 0

H(p,q)=H(p)+DKL(p∥q)H(p,q) = H(p) + D_{\mathrm{KL}}(p\|q), and KL is zero only at q=pq = p. The minimum is H(p)=−0.7log⁡20.7−0.2log⁡20.2−0.1log⁡20.1≈0.360+0.464+0.332=1.157H(p) = -0.7\log_2 0.7 - 0.2\log_2 0.2 - 0.1\log_2 0.1 \approx 0.360 + 0.464 + 0.332 = 1.157 bits, not 0, because the targets themselves are uncertain. q=(1,0,0)q = (1,0,0) would give infinite cross-entropy.

Code it (optional: real Python runs in your browser and is graded by test cases)

Chapter 12

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, p(y∣x,w)p(y \mid \mathbf x, \mathbf w). 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: y=fw(x)+εy = f_{\mathbf w}(\mathbf x) + \varepsilon, with ε∼N(0,σ2)\varepsilon \sim \mathcal N(0, \sigma^2). Then p(y∣x,w)=N(y; fw(x),σ2)p(y \mid \mathbf x, \mathbf w) = \mathcal N(y;\ f_{\mathbf w}(\mathbf x), \sigma^2), and the NLL of one example is

−log⁡p(y∣x,w)=(y−fw(x))22σ2+log⁡σ+12log⁡2π.-\log p(y \mid \mathbf x, \mathbf w) = \frac{\big(y - f_{\mathbf w}(\mathbf x)\big)^2}{2\sigma^2} + \log\sigma + \tfrac12\log 2\pi.

With σ\sigma fixed, the last two terms are constants and 12σ2\frac1{2\sigma^2} is a positive scale, so minimising the average NLL is exactly minimising the mean squared error 1n∑i(yi−fw(xi))2\frac1n\sum_i (y_i - f_{\mathbf w}(\mathbf x_i))^2. 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, p(ε)∝e−∣ε∣/bp(\varepsilon) \propto e^{-|\varepsilon|/b}, 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 KK classes, a network outputs KK real numbers called logits z\mathbf z. The softmax turns them into a categorical distribution (chapter 3):

qk=softmax⁡(z)k=ezk∑jezj.q_k = \operatorname{softmax}(\mathbf z)_k = \frac{e^{z_k}}{\sum_j e^{z_j}}.

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 yy is

−log⁡qy=−zy+log⁡∑jezj,-\log q_y = -z_y + \log\sum_j e^{z_j},

and that is the cross-entropy H(p,q)H(\mathbf p, \mathbf q) of chapter 11 with a one-hot target p\mathbf p. For two classes with a sigmoid output q=σ(z)q = \sigma(z) it becomes binary cross-entropy, −[ylog⁡q+(1−y)log⁡(1−q)]-[y\log q + (1-y)\log(1-q)]: 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

∂(−log⁡qy)∂z=q−p,\frac{\partial(-\log q_y)}{\partial \mathbf z} = \mathbf q - \mathbf p,

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 elosse^{\text{loss}} 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 TT divides the logits before the softmax, softmax⁡(z/T)\operatorname{softmax}(\mathbf z / T):

  • T=1T = 1: the distribution the model learned.
  • T<1T < 1: differences between logits are magnified, the distribution sharpens and its entropy drops. As T→0T \to 0 it becomes greedy decoding: always the top token.
  • T>1T > 1: 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.

Drag the blue logit bars at the top; the bottom panel shows softmax(z / T). Slide the temperature: near 0 nearly all the probability piles onto the top token, at 3 the bars level out. Pick the true next token from the menu to see its cross-entropy loss −ln q, and press Sample 200 tokens: the purple dots show how often each token was actually drawn.

Worked exampleLogits (2, 1, 0)

  • e2,e1,e0≈7.389,2.718,1e^2, e^1, e^0 \approx 7.389, 2.718, 1; total 11.10711.107. Softmax ≈(0.665,0.245,0.090)\approx (0.665, 0.245, 0.090).
  • If the true class is the first, the loss is −ln⁡0.665≈0.408-\ln 0.665 \approx 0.408 nats. If it's the third, −ln⁡0.090≈2.408-\ln 0.090 \approx 2.408 nats.
  • Gradient (true class first): q−p≈(0.665−1, 0.245, 0.090)=(−0.335,0.245,0.090)\mathbf q - \mathbf p \approx (0.665 - 1,\ 0.245,\ 0.090) = (-0.335, 0.245, 0.090). It sums to zero, as it always does.
  • At T=0.5T = 0.5 the logits become (4, 2, 0) and the top probability rises to e4/(e4+e2+1)≈0.867e^4/(e^4 + e^2 + 1) \approx 0.867; at T=2T = 2 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 μ\mu and σ\sigma 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?

  1. Gaussian noise with a fixed variance
  2. Laplace noise
  3. Uniform noise
  4. No noise at all

The Gaussian NLL is (y−f)22σ2\frac{(y - f)^2}{2\sigma^2} + constant, so minimising it is minimising squared error. Laplace noise would give mean absolute error.

What is softmax⁡(0,0,0,0)\operatorname{softmax}(0, 0, 0, 0)?

  1. (0.25, 0.25, 0.25, 0.25)
  2. (0, 0, 0, 0)
  3. (1, 1, 1, 1)
  4. It's undefined

Each entry is e0/(4e0)=1/4e^0 / (4e^0) = 1/4. 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?

  1. ln⁡4≈1.386\ln 4 \approx 1.386
  2. 2
  3. 0.25
  4. 0.75

−ln⁡0.25=ln⁡4≈1.386-\ln 0.25 = \ln 4 \approx 1.386 nats. (2 would be the answer in bits.)

What happens to sampling from softmax⁡(z/T)\operatorname{softmax}(\mathbf z / T) as the temperature T→0T \to 0?

  1. It always picks the token with the largest logit (greedy decoding)
  2. It becomes uniform over all tokens
  3. It becomes uniform over the top two tokens
  4. Nothing changes; temperature only rescales the loss

Dividing by a tiny TT blows up the gaps between logits, so the largest one takes almost all the probability. Large TT does the opposite and flattens toward uniform.

A 3-class model outputs q=(0.7,0.2,0.1)\mathbf q = (0.7, 0.2, 0.1) and the true class is the second. What is the gradient of the cross-entropy loss with respect to the logits?

  1. (0.7, −0.8, 0.1)
  2. (−0.3, 0.2, 0.1)
  3. (0.7, 0.2, 0.1)
  4. (−0.7, 0.8, −0.1)

The gradient is q−p\mathbf q - \mathbf p with p=(0,1,0)\mathbf p = (0, 1, 0): (0.7,0.2−1,0.1)=(0.7,−0.8,0.1)(0.7, 0.2 - 1, 0.1) = (0.7, -0.8, 0.1). 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 T=0.5T = 0.5. About what probability goes to the first class?

  1. 0.867
  2. 0.665
  3. 0.506
  4. 1.0

Divide by 0.5 to get (4, 2, 0); then e4/(e4+e2+1)≈54.6/63.0≈0.867e^4 / (e^4 + e^2 + 1) \approx 54.6 / 63.0 \approx 0.867. (0.665 is T=1T = 1 and 0.506 is T=2T = 2.)

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?

  1. e2≈7.4e^2 \approx 7.4: it's as unsure as if choosing uniformly among about 7 tokens
  2. 4: it's as unsure as choosing among 4 tokens
  3. 2: it gets 2 tokens wrong in every sentence
  4. 22=42^2 = 4 bits of error per token

Perplexity is eaverage NLLe^{\text{average NLL}} when the NLL is in nats: e2≈7.39e^2 \approx 7.39. A uniform distribution over kk tokens has cross-entropy ln⁡k\ln k, so a loss of 2 nats is like hesitating between about 7.4 equally likely options. (222^2 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

0≤P(A)≤10 \le P(A) \le 1, P(Ω)=1P(\Omega) = 1, P(Ac)=1−P(A)P(A^c) = 1 - P(A)

P(A∪B)=P(A)+P(B)−P(A∩B)P(A \cup B) = P(A) + P(B) - P(A \cap B)

Independent: P(A∩B)=P(A)P(B)P(A \cap B) = P(A)P(B)

Conditioning & Bayes

P(A∣B)=P(A∩B)/P(B)P(A \mid B) = P(A \cap B)/P(B)

P(E)=∑iP(E∣Hi)P(Hi)P(E) = \sum_i P(E \mid H_i)P(H_i)

P(H∣E)=P(E∣H)P(H)P(E)P(H \mid E) = \dfrac{P(E \mid H)P(H)}{P(E)}; odds × likelihood ratio = posterior odds

Discrete distributions

Bernoulli: px(1−p)1−xp^x(1-p)^{1-x}; mean pp, var p(1−p)p(1-p)

Binomial: (nk)pk(1−p)n−k\binom nk p^k(1-p)^{n-k}; mean npnp, var np(1−p)np(1-p)

Categorical: ∏kpkyk\prod_k p_k^{y_k} with one-hot y\mathbf y

Expectation, variance, covariance

E[aX+bY+c]=aE[X]+bE[Y]+c\mathbb E[aX + bY + c] = a\mathbb E[X] + b\mathbb E[Y] + c (always)

Var⁡(X)=E[X2]−μ2\operatorname{Var}(X) = \mathbb E[X^2] - \mu^2, Var⁡(aX+b)=a2Var⁡(X)\operatorname{Var}(aX + b) = a^2\operatorname{Var}(X)

Var⁡(X+Y)=Var⁡X+Var⁡Y+2Cov⁡(X,Y)\operatorname{Var}(X + Y) = \operatorname{Var}X + \operatorname{Var}Y + 2\operatorname{Cov}(X, Y), ρ=Cov⁡σXσY\rho = \frac{\operatorname{Cov}}{\sigma_X\sigma_Y}

Continuous & Gaussian

P(a≤X≤b)=∫abf(x) dxP(a \le X \le b) = \int_a^b f(x)\,dx; densities can exceed 1

N(μ,σ2)\mathcal N(\mu, \sigma^2): 1σ2πe−(x−μ)2/2σ2\frac{1}{\sigma\sqrt{2\pi}}e^{-(x-\mu)^2/2\sigma^2}; z=(x−μ)/σz = (x - \mu)/\sigma

±1σ: 68.3%, ±2σ: 95.4%, ±3σ: 99.7%

Sums & the CLT

P(X+Y=s)=∑kP(X=k)P(Y=s−k)P(X + Y = s) = \sum_k P(X = k)P(Y = s - k) (convolution)

Independent: means add, variances add; Gaussian + Gaussian = Gaussian

Xˉn≈N(μ,σ2/n)\bar X_n \approx \mathcal N(\mu, \sigma^2/n): error shrinks like 1/n1/\sqrt{n}

Multivariate Gaussian

Σij=Cov⁡(Xi,Xj)\Sigma_{ij} = \operatorname{Cov}(X_i, X_j), symmetric, PSD; Var⁡(u⊤x)=u⊤Σu\operatorname{Var}(\mathbf u^\top\mathbf x) = \mathbf u^\top\Sigma\mathbf u

Contours: ellipses along eigenvectors of Σ\Sigma, semi-axes λi\sqrt{\lambda_i}

Cov⁡(Ax)=AΣA⊤\operatorname{Cov}(A\mathbf x) = A\Sigma A^\top; sample μ+Lz\boldsymbol\mu + L\mathbf z, LL⊤=ΣLL^\top = \Sigma

Maximum likelihood

θ^=arg⁡max⁡∏ip(xi∣θ)=arg⁡min⁡ [−∑ilog⁡p(xi∣θ)]\hat\theta = \arg\max \prod_i p(x_i \mid \theta) = \arg\min\,[-\sum_i \log p(x_i \mid \theta)]

Coin: θ^=h/n\hat\theta = h/n. Gaussian: μ^=xˉ\hat\mu = \bar x, σ^2=1n∑(xi−xˉ)2\hat\sigma^2 = \frac1n\sum(x_i - \bar x)^2

Priors & MAP

posterior ∝ likelihood × prior; MAP = argmin [NLL − log prior]

Beta(a, b) prior: MAP =h+a−1n+a+b−2= \frac{h + a - 1}{n + a + b - 2}, mean =h+an+a+b= \frac{h + a}{n + a + b}

Gaussian prior → L2 (ridge, weight decay); Laplace prior → L1 (lasso, sparse)

Information

Surprise −log⁡2p-\log_2 p bits; entropy H(p)=−∑plog⁡pH(p) = -\sum p\log p

0≤H≤log⁡2K0 \le H \le \log_2 K; 1 nat = 1.443 bits

Information gain = H(parent)−∑ncnH(child)H(\text{parent}) - \sum \frac{n_c}{n}H(\text{child})

Cross-entropy & KL

H(p,q)=−∑plog⁡q≥H(p)H(p, q) = -\sum p\log q \ge H(p)

DKL(p∥q)=∑plog⁡pq=H(p,q)−H(p)≥0D_{\mathrm{KL}}(p\|q) = \sum p\log\frac pq = H(p, q) - H(p) \ge 0; not symmetric

min cross-entropy = min KL = max likelihood

Losses & LLMs

Gaussian noise → MSE; Laplace noise → MAE

softmax⁡(z)k=ezk/∑jezj\operatorname{softmax}(\mathbf z)_k = e^{z_k}/\sum_j e^{z_j}; loss −log⁡qy-\log q_y; gradient q−p\mathbf q - \mathbf p

Temperature: softmax⁡(z/T)\operatorname{softmax}(\mathbf z/T); perplexity =eloss in nats= e^{\text{loss in nats}}

Glossary

Bayes' rule
P(H∣E)=P(E∣H)P(H)/P(E)P(H \mid E) = P(E \mid H)P(H)/P(E): 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 pp, 0 otherwise. (Ch 3)
Beta distribution
A distribution over a probability θ∈[0,1]\theta \in [0, 1], with density ∝ θa−1(1−θ)b−1\theta^{a-1}(1-\theta)^{b-1}; the standard prior for a coin. (Ch 9)
Binomial distribution
The number of successes in nn independent Bernoulli(pp) trials. (Ch 3)
Categorical distribution
One of KK outcomes, with probabilities p1,…,pKp_1, \ldots, p_K 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 N(μ,σ2/n)\mathcal N(\mu, \sigma^2/n), whatever the original distribution. (Ch 6)
Conditional probability
P(A∣B)=P(A∩B)/P(B)P(A \mid B) = P(A \cap B)/P(B): the probability of AA once you know BB happened. (Ch 2)
Convolution
The operation that gives the distribution of a sum of independent random variables: ∑kp(k) q(s−k)\sum_k p(k)\,q(s - k). (Ch 6)
Correlation
Covariance divided by both standard deviations; always between −1 and 1. (Ch 4)
Covariance
E[(X−μX)(Y−μY)]\mathbb E[(X - \mu_X)(Y - \mu_Y)]: whether two variables move together. (Ch 4)
Covariance matrix
The matrix Σ\Sigma of all pairwise covariances of a random vector; symmetric and positive semi-definite. (Ch 7)
Cross-entropy
H(p,q)=−∑plog⁡qH(p, q) = -\sum p\log q: the average surprise when outcomes follow pp but you predict with qq. 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
H(p)=−∑plog⁡pH(p) = -\sum p\log p: the average surprise, or uncertainty, of a distribution. (Ch 10)
Event
A set of outcomes. (Ch 1)
Expectation
The probability-weighted average ∑x p(x)\sum x\,p(x); the balance point of a distribution. (Ch 4)
Gaussian (normal) distribution
The bell curve N(μ,σ2)\mathcal N(\mu, \sigma^2). (Ch 5)
Independence
P(A∩B)=P(A)P(B)P(A \cap B) = P(A)P(B): learning one tells you nothing about the other. (Ch 1)
KL divergence
DKL(p∥q)=∑plog⁡(p/q)D_{\mathrm{KL}}(p\|q) = \sum p\log(p/q): the extra cost of using qq when the truth is pp. Non-negative and not symmetric. (Ch 11)
L1 / L2 regularization
Penalties λ∥w∥1\lambda\|\mathbf w\|_1 and λ∥w∥22\lambda\|\mathbf w\|_2^2; MAP estimation with Laplace and Gaussian priors. (Ch 9)
Likelihood
L(θ)=p(data∣θ)L(\theta) = p(\text{data} \mid \theta), viewed as a function of the parameters. (Ch 8)
Logits
The raw scores a network outputs before the softmax. (Ch 12)
Mahalanobis distance
(x−μ)⊤Σ−1(x−μ)\sqrt{(\mathbf x-\boldsymbol\mu)^\top\Sigma^{-1}(\mathbf x-\boldsymbol\mu)}: 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)
−∑ilog⁡p(xi∣θ)-\sum_i \log p(x_i \mid \theta); the loss that training minimises. (Ch 8, 12)
Perplexity
ecross-entropy in natse^{\text{cross-entropy in nats}}: the effective number of equally likely choices a language model is torn between. (Ch 12)
PMF
Probability mass function p(x)=P(X=x)p(x) = P(X = x) 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 Ω\Omega of all possible outcomes. (Ch 1)
Softmax
ezk/∑jezje^{z_k}/\sum_j e^{z_j}: 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 TT before the softmax: T<1T < 1 sharpens, T>1T > 1 flattens. (Ch 12)
Variance
E[(X−μ)2]\mathbb E[(X - \mu)^2]: the average squared distance from the mean. (Ch 4)

Where to go next