Semester 1 · Week 02
Probability, statistics, and linear algebra
- Ch 3 Maths Foundations: Statistics, Probability & Linear Algebra
Chapter 3: Maths foundations
Every dataset is a matrix. Every model is maths applied to it.
Notes · slide 2
Time: 50 minutes for one chapter. About 15 on probability, 10 on statistics, 10 on linear algebra, 10 on the worked example, and 5 to check understanding.
Say: Tonight is the maths the rest of the course assumes. Not proofs. Fluency: reading an equation, and noticing when a model's assumptions don't match the data.
Say: One thread ties it together. Linear regression is a statistics problem, a matrix calculation, and the first model later chapters build on. We finish there.
GenAI link: The same holds for an LLM. Its text becomes a matrix: each token is a row of numbers, called an embedding. Everything after that is matrix maths and probability.
Next: why this matters.
Why this chapter matters
- Probability is the calculus of uncertainty.
- Statistics summarises data and draws defensible inferences.
- Linear algebra represents and transforms data at scale.
Most classifiers compute a probability underneath. Most EDA is applied statistics. Skipping the maths only means meeting it later, inside a library, without the words to reason about it.
Notes · slide 3
Say: Three fields. Probability is the calculus of uncertainty. Statistics summarises data and says how far to trust it. Linear algebra represents and transforms data at scale.
Say: Most classifiers compute a probability under the hood, even when the output is a label. Most exploratory analysis is applied statistics. Every dataset is a matrix.
Key line: skipping the maths doesn't remove it. You meet it later, inside a library, without the words to reason about it.
Ask: "Who feels rusty on maths?" Reassure them. The goal is literacy, not expertise.
GenAI link: An LLM uses all three at once. Probability: it outputs a distribution over the next token. Statistics: its benchmark scores are samples, so they carry error bars. Linear algebra: nearly all its compute is matrix multiplication, which is why it runs on GPUs.
Next: probability.
Probability
Notes · slide 4
Time: about 15 minutes, through the bell curve.
Say: Probability is how we talk about uncertainty. Every classifier answers a probability question, so this is where we start.
Next: conditional probability.
Probability and conditional probability
- P(A) is a number from 0 to 1. P(A)=0.3 means 30% of the time, in the long run.
- P(A∣B) is the probability of A given that B is true.
- "Given these features, how likely is this outcome?" is a conditional probability question.
That's what every classifier answers, from logistic regression to a large transformer.
Notes · slide 5
Say: A probability runs from 0 to 1. 0.3 means 30% of the time over many repeats. The one that matters for ML is conditional probability: the chance of A once you know B is true.
Say: "Given these features, how likely is this outcome?" That's a conditional probability. Logistic regression answers it. So does a large transformer.
Ask: "What's the probability a random email is spam? What about given it contains 'winner'?" Listen for: the second is higher. The evidence changes the probability.
GenAI link: An LLM computes P(next token | all the text so far). A reply is a chain of conditional probabilities, one per token. The prompt is the evidence it conditions on. That's why changing the prompt changes the answer.
Next: the rule that links them.
Bayes' theorem
P(A∣B)=P(B)P(B∣A)P(A)
| Term | Meaning |
|---|---|
| P(A) prior | Belief before the evidence. The base rate |
| P(B∣A) likelihood | How likely the evidence is if A is true |
| P(A∣B) posterior | Updated belief after the evidence |
Notes · slide 6
Definition: Bayes' theorem says how to update a belief when new evidence arrives. Start with how likely something was before the evidence. Multiply by how likely the evidence would be if it were true. Then divide by how likely the evidence is overall, from every cause. The result is the updated belief.
Base rate: how common something is in the whole population, before you know anything about the case in front of you. If 1 person in 100 has a disease, the base rate is 1%. It's the prior when you know nothing else. When the base rate is low, even strong evidence often isn't enough to make the thing likely, because the many cases without it produce their own false signals.
Say: Bayes' theorem turns one conditional probability into the other. In ML terms, B is the evidence, the features, and A is the label.
Say: Walk the table. The prior is what you believed before the evidence: the base rate. The likelihood is how probable the evidence is if A is true. The posterior is what you want: the updated belief.
Key line: the posterior depends on the prior. Ignore the base rate and you get the wrong answer.
GenAI link: One way to read in-context learning is Bayesian. The model brings a prior from training. The examples in your prompt act as evidence and shift its answer. It's a useful lens, not a settled account of how LLMs work.
Next: a worked example that shows how wrong.
Worked example: a positive test
- A disease affects 1% of people.
- The test catches 99% of cases and has a 5% false positive rate.
- Someone tests positive. How likely are they to have it?
Notes · slide 7
Do: read the setup, then ask the room to guess before you move on. Take a show of hands: above 90%? 50 to 90%? Below 50%? Most people say about 95%.
Next: the answer.
Worked example: a positive test
- A disease affects 1% of people.
- The test catches 99% of cases and has a 5% false positive rate.
- Someone tests positive. How likely are they to have it?
P(disease∣+)=(0.99×0.01)+(0.05×0.99)0.99×0.01≈0.167
Only 16.7%. The base rate dominates.
Notes · slide 8
Do: reveal the answer, then work it on the board.
Say: Picture 10,000 people. 100 have the disease, and 99 of them test positive. 9,900 are healthy, and 5% of them, 495, also test positive. So 99 of 594 positives are real. That's 16.7%.
Key line: the healthy majority is so large that a small false positive rate swamps the true positives.
Say: This is the same trap as last week's 95%-accurate fraud model. Rare classes make every evaluation a Bayes calculation.
GenAI link: AI-text detectors fall into this trap. Say 2% of essays are AI-written, and a detector catches 99% of them with a 5% false positive rate. Of every 10,000 essays, it flags 198 AI essays and 490 human ones. So only about 29% of flagged essays are AI-written. Content filters that look for rare harmful prompts face the same maths.
Next: the shapes randomness takes.
Distributions you'll meet constantly
| Distribution | Describes | Use when |
|---|---|---|
| Gaussian | Symmetric, bell-shaped values | Measurement error, residuals |
| Bernoulli | One yes/no outcome | Every binary label |
| Binomial | Successes in n trials | Conversion counts |
| Poisson | Rare events in an interval | Tickets per day, failures per hour |
The Central Limit Theorem explains why so much is roughly Gaussian.
Notes · slide 9
Say: A distribution describes which values are likely and how spread out they are. Four come up constantly. Gaussian for measurement error and residuals. Bernoulli for one yes or no: every binary label. Binomial for successes in n tries. Poisson for counts of rare events in an interval.
Ask: "Which fits: tickets per hour, whether one email is spam, heads in 50 flips?" Listen for: Poisson, Bernoulli, Binomial.
Say: Picking the wrong one is a common modelling error, such as ordinary regression on skewed counts.
Central Limit Theorem: add up or average many independent random values, and the result tends towards a Gaussian as the count grows. That holds almost whatever shape the original values have. One die roll is flat: each face is equally likely. The average of 30 rolls is bell-shaped around 3.5. It's why sample means, error bars, and A/B tests can use the Gaussian. It needs the values to be independent and their spread to be finite. Very heavy-tailed data, where single extreme values dominate, can break it.
GenAI link: An LLM's output is a categorical distribution: the Bernoulli extended to one outcome per token in the vocabulary. Image diffusion models start from Gaussian noise and learn to remove it step by step.
Next: the Gaussian in detail.
The Gaussian
f(x)=σ2π1exp(−2σ2(x−μ)2)
- Two parameters: mean μ and standard deviation σ.
- Linear regression's maximum-likelihood derivation assumes Gaussian residuals.
Notes · slide 10
Say: Don't memorise the formula. Notice it has two knobs: the mean sets the centre, the standard deviation sets the width. The squared distance from the mean in the exponent is why values far out get rare fast.
Say: It appears when many small, independent effects add up. That's the Central Limit Theorem. It's why linear regression assumes Gaussian residuals.
Say: De Moivre showed in 1733 that a Binomial looks Gaussian once there are enough trials. One of the oldest results still in daily use.
GenAI link: The Gaussian runs through generative models. Network weights usually start as small random Gaussian draws. Diffusion models add Gaussian noise to images in training, then learn to reverse it. Variational autoencoders describe each input as a Gaussian in a small hidden space.
Next: what it looks like.
The bell curve

Symmetric, set by its mean and standard deviation. Sums of many small effects end up here.
Notes · slide 11
Say: Symmetric around the mean. Most values sit near the middle, and the tails thin out fast.
Ask: "Name something you measure that is not bell-shaped." Listen for: incomes, waiting times, counts, anything with a long right tail.
Key line: the distribution is a claim about how the data was made. The model inherits that claim, right or wrong.
GenAI link: Word frequencies are not bell-shaped. A few words are very common and most are rare: a long tail, known as Zipf's law. That's one reason LLMs split rare words into smaller pieces called tokens. A model sees "the" constantly, but might meet a rare name only a few times.
Next: statistics.
Statistics
Notes · slide 12
Time: about 10 minutes, through the p-value.
Say: Statistics does two jobs. Describe the data you have. Then judge whether a pattern is real or chance.
Next: describing data.
Describing data
- Mean: the average. Pulled by outliers.
- Median: the middle value. Robust to outliers.
- Variance and standard deviation: how spread out values are.
- Covariance and correlation: how two variables move together.
r=σXσYCov(X,Y)∈[−1,1]
Correlation measures linear association only.
Notes · slide 13
Say: The mean is pulled by outliers. The median isn't. When they differ a lot, the data is skewed or mixed. Standard deviation is spread in the original units. Correlation rescales covariance to between −1 and 1, so you can compare across units.
Covariance: how two variables move together. For each row, take how far X is from its mean and how far Y is from its mean, and multiply the two. Then average across rows. It's positive when they rise together, negative when one rises as the other falls, and near zero when there's no straight-line link. Its units are X's units times Y's, so its size is hard to read. Correlation divides by both standard deviations to fix that.
Say: Correlation only measures straight-line association. A strong curved relationship can have r near zero. Always plot the scatter.
Ask: "House prices in a city. Mean or median?" Listen for: median, because a few very expensive houses pull the mean up.
Say: This week's lab hides a trap here. Let them find it.
GenAI link: An LLM is a description of its training data, the same as a mean or a correlation, at a much larger scale. It learns which words and ideas go together in the text it saw. So it models what is likely to be said, not what is true. The two overlap when the training text is mostly right and agrees with itself. They split in three ways.
GenAI link, common errors: if a false claim is common in the training text, the model learns it as likely. TruthfulQA, a 2021 benchmark, asked questions where popular misconceptions are the likely answer. Larger models of that time were often less truthful, not more. They had learned the misconceptions better.
GenAI link, rare facts: facts that appear rarely in training are in the long tail. A 2023 study found that how well a model answers a question tracks how many training documents mention its subject. Where the data is thin, the model still produces fluent, likely-sounding text. That's a hallucination: typical wording with nothing behind it.
GenAI link, confidence: fluency is not evidence. A model sounds as sure about a rare fact as a common one. Base models are fairly well calibrated: their token probabilities track how often they're right. Fine-tuning a model to be a helpful assistant can weaken that.
Key line for GenAI: association is not truth. Correlation can't tell you why two variables move together, and an LLM's fluency can't tell you whether a claim is true. Grounding answers in sources, as RAG does, helps. Checking the source is still your job.
GenAI link, tools: embeddings are compared with cosine similarity, a close relative of correlation. Correlation is the cosine similarity of two vectors after each is centred on its mean. RAG ranks documents by cosine similarity to the question.
Next: is a pattern real?
Hypothesis tests and the p-value
- A p-value is the probability, if the null hypothesis were true, of data at least as extreme as yours.
- It is not the probability that the null is true.
- Statistical significance is not practical importance. Report an effect size too.
Treating p<0.05 as a finish line is one of the most common mistakes in industry data science.
Notes · slide 14
Say: Assume no effect. Ask how surprising the data would be if that were true. That's the p-value. It is not the probability that the null is true.
Say: Test enough things and something crosses 0.05 by chance. That's p-hacking, and it's usually not deliberate. In 2015, a replication of 100 psychology studies found only 36% significant again.
P-hacking: trying analyses until one gives p < 0.05, then reporting only that one. It's rarely fraud. It grows from small, reasonable-looking choices. Drop some outliers. Try another metric. Split by region. Stop collecting data the moment the result looks good. Each choice is another test, and each test is another chance of a false positive.
Say: The maths is simple. At a 0.05 threshold, one test of a true null has a 5% chance of a false positive. Run 20 independent tests and the chance that at least one comes up significant is 1 − 0.95²⁰, about 64%. Report only that one and it looks like a discovery.
Say: The defences: decide the test, the metric, and the sample size before you look at the data. Report every test you ran, not only the winners. When you run many tests, raise the bar for each one. The Bonferroni correction divides 0.05 by the number of tests. Check a surprising result on fresh data before you trust it.
Ask: "An A/B test tracks 15 metrics. One improves with p = 0.04. Ship it?" Listen for: not yet. With 15 metrics and no real effect, the chance of at least one p < 0.05 is about 54%. Retest that metric on new traffic.
Key line: significant is not the same as important. With enough data, 0.9000 to 0.9001 accuracy can be "significant". Always report an effect size.
GenAI link: LLM leaderboards are hypothesis tests, whether people say so or not. On a 500-question benchmark at 80% accuracy, the standard error is about 1.8 points. A one-point lead can be chance. Prompt tuning invites p-hacking: try enough prompts on the same test set and one will win by luck.
Next: linear algebra.
Linear algebra
Notes · slide 15
Time: about 10 minutes, through regression.
Say: Linear algebra is the language data is stored and transformed in. Every model, from regression to a large neural network, is a chain of matrix operations.
Next: vectors and matrices.
Vectors and matrices
- A vector is an ordered list of numbers. One customer with seven features is a point in R7.
- A matrix stacks vectors. A dataset with n rows and d features is an n×d matrix.
- In code, both are numpy arrays.
Notes · slide 16
Say: A vector is an ordered list of numbers. One customer with seven features is one point in seven dimensions. A matrix stacks those rows. A dataset with n rows and d features is an n by d matrix.
Say: In code they're numpy arrays. A Python list is not a vector. Adding two lists joins them end to end. Adding two arrays adds element by element. Mixing them up gives silent, wrong-shaped bugs.
Ask: "A dataset has 500 customers and 12 features. What shape is X?" Listen for: 500 by 12.
GenAI link: An embedding is a vector. An LLM turns each token into a vector of hundreds to thousands of numbers. Meaning becomes geometry: related words point in similar directions. A prompt of n tokens becomes an n by d matrix, the same shape as a dataset.
Next: the operations models use.
The operations that matter
- Dot product: a weighted sum. The core of every linear model.
- Matrix multiplication: rows times columns.
- Transpose and inverse: flipping and undoing.
- Eigenvectors: directions a matrix only stretches. PCA in Chapter 15 is built on them.
(1324)(5768)=(19432250)
Notes · slide 17
Say: A dot product multiplies matching elements and adds. A linear model's prediction is the dot product of features and weights. Matrix multiplication is many dot products at once: row of the first times column of the second. Work the top-left entry: 1×5 + 2×7 = 19. Then the top-right entry: the same first row, times the second column. 1×6 + 2×8 = 22. The row picks the output's row, and the column picks its column.
Say: Eigenvectors are directions a matrix only stretches. PCA in Chapter 15 uses them.
Say: In numpy, * multiplies element by element. @ is matrix multiplication. On square matrices both run without error, and only one is right.
GenAI link: Attention is built on dot products. Each token's query vector is dotted with every other token's key vector, and the scores say how much attention it pays to each one. Matrix rank returns in LoRA, a common way to fine-tune LLMs. A matrix's rank is how many independent directions it holds. LoRA freezes each large weight matrix W and learns only a change to it. That change is the product of two thin matrices, B and A, with a small inner size r, often 8 or 16. Their product BA is the same size as W, but its rank is at most r. For a 4,096 by 4,096 matrix, a full update has about 16.8 million numbers. A rank-8 update has 65,536, about 0.4%. It works because the changes fine-tuning needs seem to lie in a few directions. Each task's update is small enough to store and swap on its own.
Next: where all three meet.
Where all three meet: linear regression
Predictions are a matrix product:
y^=Xw
The least-squares weights have a closed form, the normal equations:
w=(X⊤X)−1X⊤y
Not an approximation. The exact minimiser. sklearn returns the same answer with a more stable solver.
Notes · slide 18
Say: Read the symbols first. w is the weights: one coefficient per feature. ŷ, said "y-hat", is the predictions. The hat means estimated. y is the true values from the data.
Say: The gap between y and ŷ, row by row, is the error, also called the residual. Least squares squares each gap and adds them up. Squaring makes every gap count as positive, so misses above and below can't cancel out. It also weighs big misses much more than small ones. Training picks the w that makes that sum as small as possible.
Say: Predictions are X times w: one dot product per row. Learning means finding the w that minimises squared error, a statistics objective. That minimum has an exact formula, the normal equations.
Say: It's not an approximation or an iteration. It's the exact answer. sklearn gets the same answer with a more stable method than inverting X-transpose-X.
Ask: "If X is n by d, what shape is X-transpose-X?" Listen for: d by d. Small, however many rows.
Say: Next week covers what to do when no formula like this exists: gradient descent.
GenAI link: A transformer is mostly layers of Xw, with simple nonlinear steps between them. Its last layer, which turns a vector into a score for every token, is a linear model. There's no normal-equation shortcut for billions of weights. That's why it's trained by gradient descent, next week's topic.
Next: the worked example.
Worked example, part 1: more data helps slowly
The error of an average shrinks as 1/n.
| Fair coin flips | Typical gap from 0.5 |
|---|---|
| 100 | 0.05 |
| 10,000 | 0.005 |
| 1,000,000 | 0.0005 |
100 times the data gives 10 times the precision.
Notes · slide 19
Say: The notebook flips a fair coin 10,000 times and gets 0.4924 heads. That's 0.0076 from 0.5, about 1.5 typical gaps. Normal for chance. The law of large numbers says the average closes in on the truth. This slide is about how slowly.
Say: The typical gap is the standard error: 0.5 divided by the square root of n for a fair coin. To cut it by 10, you need 100 times the flips. To halve it, four times. That rule holds for any average: polls, A/B tests, model accuracy on a test set.
Ask: "An A/B test compares two versions of a sign-up page. With 10,000 users per version, it can detect a sign-up rate that rises from 10% to 11%. How many users to detect a rise from 10% to 10.5%?" Listen for: about 40,000. A change half the size needs four times the data.
Say: The notebook also checks the disease example by simulating 100,000 people and counting positives. It gets 16.7% again. When you're unsure of the algebra, simulate it.
GenAI link: the same rule sets how many prompts an LLM evaluation needs. Doubling the test set doesn't halve the noise. Quadrupling it does. Scaling laws for LLMs show a similar pattern of slow returns: test loss falls as a power of data and compute, so each tenfold increase gives a similar, modest step.
Key line: precision grows with the square root of the data. Plan for that before you collect it.
Next: when summary statistics mislead.
Worked example, part 2: same statistics, different data
Four datasets, published by Anscombe in 1973. All four have:
- the same mean and variance of x and of y
- the same correlation, r=0.816
- the same regression line, y=3+0.5x
Only the plots differ. Summary statistics can't stand in for a plot.
Notes · slide 20
Say: The notebook's iris summary hides a story. Petal length has mean 3.758 cm and median 4.350 cm. That gap comes from three species mixed together, and only a plot shows it. Anscombe built these four datasets in 1973 to make the same point as sharply as possible.
Do: walk the four panels. I is a straight-line relationship with noise: the only one where the line fits. II is a smooth curve, so a straight line is the wrong model. III is a perfect line except one outlier, which tilts the fit. IV has no relationship at all: ten points share one x value, and one far point creates the whole correlation.
Say: In 2017, Matejka and Fitzmaurice took this further with the Datasaurus Dozen: 13 datasets with nearly identical summary statistics. One of them is a drawing of a dinosaur.
Ask: "Which panel is linear regression right for?" Listen for: only I.
GenAI link: a single benchmark score is a summary statistic too. Two models at 80% can fail on very different questions. One might be strong on common questions and weak on rare ones. Break evaluation results down by question type, the way you'd plot the data, before you trust the average.
Key line: plot before you summarise. The same numbers can describe very different data.
Next: why it's called regression.
Worked example, part 3: why it's called regression
- In 1886, Galton found that very tall parents tend to have children shorter than themselves, and very short parents taller ones. He called it regression towards mediocrity. Today it's called regression to the mean.
- In standard units, the regression line's slope is r. Unless r is exactly 1 or −1, every prediction sits closer to the mean than its input.
- Iris: r=0.963. A flower 2 standard deviations above average in petal length is predicted 1.93 above average in width.
Least squares predicts the average outcome. Expect it to be less extreme than reality.
Notes · slide 21
Say: First, the notebook's result. It fits petal width from petal length with the normal equations in numpy, then with sklearn. They agree to six decimal places, with R² of 0.927. For one feature, R² is r squared: 0.963² ≈ 0.927.
Say: Now the name. Galton measured parents and children in 1886. Children of very tall parents were tall, but less tall than their parents on average. The line he fitted pulled every prediction back towards the average. That's where the word regression comes from.
Say: It isn't a force. It happens whenever two measurements are imperfectly correlated. An extreme value is partly skill and partly luck, and the luck doesn't repeat.
Say: Kahneman tells of flight instructors who believed praise made pilots worse and shouting made them better. After a great landing, the next one was usually worse. After a terrible one, it was usually better. Regression to the mean, whatever the instructor said.
Ask: "The worst sales region gets a new manager, and sales rise next quarter. Was it the manager?" Listen for: maybe, but the worst region would likely improve anyway. You need a comparison group. That's why medical trials have one.
GenAI link: least squares predicts the average of all plausible outcomes. When many outcomes are plausible, the average is a blur. Early image models trained on squared error made blurry pictures: the mean of many possible images. GANs and diffusion models were built partly to produce one sharp, plausible image instead of the average. LLMs face a related pull. At low temperature, their answers drift towards the most typical wording.
Key line: least squares predicts the average. Real outcomes are more extreme than its predictions.
Next: the chapter in one idea.
Mental model
- A dataset is a matrix.
- A model is a function that turns the matrix into predictions.
- A training objective measures how wrong those predictions are.
- Probability is the language that objective is written in.
- Statistics says how confident to be in the result.
You don't need to be a mathematician. You need to read these equations without flinching.
Notes · slide 22
Say: A dataset is a matrix. A model turns it into predictions. An objective measures how wrong they are. Probability is the language of that objective. Statistics says how confident to be.
Say: You don't need to be a mathematician. You need to read these equations and reason about what changing an input does to the output.
GenAI link: The same five lines describe an LLM. The dataset is text turned into a matrix of token vectors. The model is a very large function. The objective is cross-entropy on the next token. Probability is its output. Statistics says how far to trust its evaluations.
Next: check yourself.
Check yourself
- Why is a 99%-accurate test only 16.7% reliable here?
- When would you report the median instead of the mean?
- What does r=0 tell you, and what doesn't it?
- What does p=0.03 mean, in one sentence?
- What shape is X⊤X if X is n×d?
Notes · slide 23
Do: give pairs three minutes, then take answers.
Answers: 1. The base rate dominates: healthy people far outnumber sick ones, so false positives swamp true ones. 2. When the data is skewed or has outliers. 3. No straight-line association. There may still be a curved one. 4. The probability of data at least this extreme if the null were true. 5. d by d.
Lab: the penguins lab hides Simpson's paradox. A correlation flips sign within each species. Let learners find it before you explain it.
GenAI link: a bonus question. "An AI-text detector flags an essay. What do you need to know before acting on it?" Listen for: how common AI essays are, and the detector's false positive rate. It's question 1 again.
This week
- Read Chapter 3: Maths Foundations: Statistics, Probability & Linear Algebra.
- Take the Chapter 3 quiz.
- Run the notebooks: Chapter 3 (opens in a new tab).
- Optional: the further reading for week 2.
Slide 1 of 24: Probability, statistics, and linear algebra
Keys: → or Space next · ← back · Home/End · F full screen · N notes. Swipe on touch screens. "Save as PDF" opens the print dialog with one slide per page: choose "Save as PDF" as the printer. "Print handout" adds the speaker notes, in black on white.