Module 2 · The maths and statistics you need, from scratch
Time: about 8 hours, including the lab · Lab: python course/labs/lab02_maths.py
You need: school arithmetic (fractions, percentages, squaring a number). Nothing else is assumed. Each idea below is built only from ideas before it.
By the end you can:
- say what a function with parameters is, and why "learning" means choosing parameter values;
- work with powers, the number e and logarithms, and say why machine learning uses them;
- multiply a vector by a matrix by hand, and count a layer's parameters;
- find a slope by nudging, use the chain rule, and run gradient descent by hand;
- use the two rules of probability, and read precision and recall as conditional probabilities;
- compute a mean and a standard deviation, and derive the standard error of a proportion;
- explain what a 95% interval is, where 1.96 comes from, and how many examples a test needs.
Why this matters
Every later module rests on this one.
- How models learn (Modules 4–8) needs Part A: functions, logarithms, matrices, slopes and gradient descent.
- How models are judged (Modules 9–11) needs Part B: probability, averages, spread and sampling error. This is the part the internship uses every day. If time is short, read Part B first (§6–§12), then come back for Part A.
You won't be asked to compute derivatives in the job. You will be asked what a number like "88.75%" means and how sure anyone can be of it. That answer is in Part B.
Part A · Maths for learning
1. Functions and parameters
A function is a rule that turns an input into an output. "Double it and add one" is a function. Written with a letter for the input:
Give it x = 3 and it returns 7. The letter x is just a placeholder for "whatever you put in".
Now replace the fixed numbers 2 and 1 with letters:
This is no longer one rule; it is a family of rules, one for every choice of w and b. The letters w and b are parameters: knobs that select which member of the family you get. With w = 2, b = 1 you get the rule above; with w = 0.5, b = 10 you get a different one.
A food-service example. Suppose a kitchen needs to predict meals to prepare from the number of patients on a ward. A sensible family of rules is
where w is "meals per patient" and b is a fixed extra (staff meals, spares). Which values of w and b are right? You could guess. Or you could look at past days and pick the values that would have predicted them best. That second option is machine learning. Module 4 does it step by step.
This is the whole idea in miniature:
| Word | Meaning | In the example | In TrayCheck |
|---|---|---|---|
| Input | What the rule is given | Number of patients | A photo (27,648 numbers) |
| Output | What it returns | Meals to prepare | Four probabilities, one per dish |
| Model | The family of rules, with parameters left open | w × patients + b | MobileNetV2 plus a new head |
| Parameters | The open values | w and b: 2 numbers | About 2.4 million numbers |
| Training | Choosing parameter values from examples | Fit w, b to past days | Fit the parameters to 400 labelled photos |
The symbol θ ("theta") is often used to mean "all the parameters together", and fθ means "the function you get with those parameter values".
Two pieces of notation used throughout the course:
- Subscripts number things in a list: x₁, x₂, x₃ are the first, second and third inputs.
- Σ ("sigma") means "add up". Σᵢ xᵢ means x₁ + x₂ + x₃ + … over all i. For x = [4, 1, 5], Σᵢ xᵢ = 10.
2. Powers, the number e, and logarithms
These three ideas appear in every classifier: the model's probabilities are made with e, and its training loss is a logarithm.
Powers
A power is repeated multiplication: 2³ = 2 × 2 × 2 = 8. Three rules follow directly from that definition:
| Rule | Why | Example |
|---|---|---|
| aᵐ × aⁿ = aᵐ⁺ⁿ | Multiplying m copies by n more copies gives m + n copies | 2² × 2³ = 4 × 8 = 32 = 2⁵ |
| a⁰ = 1 | Multiplying by zero extra copies changes nothing | 2⁰ = 1 |
| a⁻ⁿ = 1 / aⁿ | A negative power divides instead | 2⁻³ = 1/8 |
The number e
e ≈ 2.718 is a constant, like π. It comes from growth. Put $1 in a bank paying 100% interest a year. Paid once at year's end, you have $2. Paid as two half-year instalments of 50%, you have 1.5 × 1.5 = $2.25. Paid monthly, (1 + 1/12)¹² = $2.61. Daily, $2.71. As the instalments get smaller and more frequent, the total settles at 2.71828…, and that limit is e.
What matters for this course is how the function eˣ behaves:
| x | −2 | −1 | 0 | 1 | 2 | 3 |
|---|---|---|---|---|---|---|
| eˣ | 0.135 | 0.368 | 1 | 2.718 | 7.389 | 20.09 |
- It is always positive, even for negative x.
- It keeps order: a bigger x always gives a bigger eˣ.
- It grows fast: each step of 1 in x multiplies the result by 2.718.
That combination is exactly what's needed to turn arbitrary scores (which can be negative) into positive numbers that can become probabilities (§8).
Logarithms
A logarithm answers the reverse question: what power gives this number?
- log₁₀(1000) = 3, because 10³ = 1000.
- The natural logarithm, written ln, uses base e: ln(e²) = 2, ln(1) = 0.
Everything about logs comes from the power rules above:
| Log rule | Comes from | Why it matters |
|---|---|---|
| ln(a × b) = ln a + ln b | Powers add when you multiply | Turns a product of many probabilities into a sum (§9) |
| ln(1) = 0 | e⁰ = 1 | A probability of 1 costs nothing |
| ln of a number between 0 and 1 is negative | Making a number smaller than 1 needs a negative power | So −ln(p) is positive for any probability |
| ln(p) heads to −∞ as p heads to 0 | e raised to a very negative power is tiny | Being sure of a wrong answer is punished without limit |
The quantity that will matter most is −ln(p), where p is a probability:
| p | 1 | 0.99 | 0.9 | 0.5 | 0.25 | 0.1 | 0.01 |
|---|---|---|---|---|---|---|---|
| −ln(p) | 0 | 0.010 | 0.105 | 0.693 | 1.386 | 2.303 | 4.605 |
Small when p is near 1; large when p is near 0. Hold on to this table; §9 explains why it is the training loss of TrayCheck and nearly every classifier.
3. Vectors, dot products and matrices
Vectors
A vector is an ordered list of numbers: x = [0.2, 0.9, 0.4]. Position matters: the first number always means the same thing. A TrayCheck photo is a vector of 27,648 numbers: 96 rows × 96 columns × 3 colours (red, green, blue), each a brightness from 0 to 255.
The dot product: a weighted sum
The dot product of two vectors of the same length multiplies matching entries and adds the results:
With x = [0.2, 0.9, 0.4] and w = [1.5, −2.0, 0.5]:
1.5 × 0.2 + (−2.0) × 0.9 + 0.5 × 0.4 = 0.3 − 1.8 + 0.2 = −1.3
Read w as "how much each input matters, and in which direction". A large positive weight means "this input pushes the result up"; a negative weight pushes it down; zero ignores it. A dot product is therefore a weighted sum, and it is the basic computation of every artificial neuron.
Matrices and matrix multiplication
A matrix is a table of numbers. Its shape is (rows, columns). This W has shape (3, 2):
W = [ 1 0 ]
[ 2 -1 ]
[ 0 3 ]
Multiplying the vector x (3 numbers) by W means: take the dot product of x with each column of W. Each column gives one output.
column 1 = [1, 2, 0]: 0.2×1 + 0.9×2 + 0.4×0 = 2.0
column 2 = [0, -1, 3]: 0.2×0 + 0.9×(-1) + 0.4×3 = 0.3
x W = [2.0, 0.3]
So a (3, 2) matrix turns 3 numbers into 2. The general rule for shapes:
The inner sizes (b) must match, because each dot product pairs every input with one weight. If you stack 32 input vectors as the rows of a (32, 3) matrix, one multiplication by W gives a (32, 2) result: 32 outputs at once. That is how a computer processes a batch of photos.
A dense layer
A dense layer (also called fully connected) is a matrix multiplication plus a bias, one extra number added to each output:
With n inputs and m outputs, W has n × m weights and b has m biases. TrayCheck's
last layer turns 96 numbers into 4 dish scores, so it has 96 × 4 + 4 = 388 parameters, exactly
what Keras reports for the layer named food_class.
Shape thinking is the most useful habit in deep learning. Before running code, say the shapes out loud:
(32, 1280) × (1280, 96) → (32, 96). Most bugs are shape mismatches.
The transpose
The transpose of a matrix, written Wᵀ, swaps rows and columns: row 1 becomes column 1. The (3, 2) matrix above becomes (2, 3). You'll meet it in Modules 4 and 5, where running a layer "backwards" multiplies by the transpose: the forward pass sends each input to every output, so the backward pass collects from every output back to each input.
4. Slopes and derivatives
Learning means adjusting parameters to make a model less wrong. To know which way to adjust a parameter, you need to know how the error changes when that parameter changes. That is a slope.
The slope of a straight line
For a straight line, the slope is "rise over run": how much the output goes up per step of 1 in the input. f(x) = 2x + 1 has slope 2 everywhere: every step of 1 in x raises f by 2.
The slope of a curve: nudge and see
A curve's slope changes from point to point. To find it at one point, nudge the input a little and see how much the output moves, per unit of nudge. For f(x) = x² at x = 3 (where f = 9):
| Nudge h | f(3 + h) | Change ÷ nudge |
|---|---|---|
| 1 | 16 | (16 − 9) / 1 = 7 |
| 0.1 | 9.61 | 0.61 / 0.1 = 6.1 |
| 0.01 | 9.0601 | 0.0601 / 0.01 = 6.01 |
| 0.001 | 9.006001 | 6.001 |
As the nudge shrinks, the answer settles on 6. That limiting value is the derivative, written f ′(x) or df/dx: the slope of the curve at that exact point.
Algebra shows why it's 6. (3 + h)² − 9 = 6h + h², so the change per unit of nudge is 6 + h, which becomes 6 as h shrinks to nothing. Doing the same at any point x gives 2x: the derivative of x² is 2x.
The derivative's practical meaning, used everywhere below:
"Nudge the input by h and the output moves by about slope × h." If the slope is negative, increasing the input decreases the output.
A few derivatives you'll see, each found the same way:
| Function | Derivative | In words |
|---|---|---|
| a constant, e.g. 5 | 0 | It doesn't change |
| a x | a | A straight line's slope |
| x² | 2x | Steeper the further you are from 0 |
| eˣ | eˣ | eˣ is its own slope (that's what makes e special) |
| ln(x) | 1/x | |
| max(0, x) (called ReLU, Module 5) | 0 if x < 0, 1 if x > 0 | Flat, then a 45° line |
| a sum f + g | f ′ + g ′ | Slopes of a sum add |
Several inputs: partial derivatives and the gradient
A model's error depends on many parameters at once. The partial derivative with respect to one parameter, written ∂L/∂w (the curly ∂ just signals "one of several inputs"), is the slope when you nudge only that one and hold the others still.
The gradient, written ∇L, is the list of all the partial derivatives. It points in the direction in which L increases fastest, so its opposite points downhill.
The chain rule
Models are built from functions inside functions: the output of one layer is the input to the next. The chain rule says how slopes combine through such a chain: they multiply.
Think of gears. If gear B turns 3 times for each turn of gear A, and gear C turns 2 times for each turn of B, then C turns 3 × 2 = 6 times for each turn of A.
Worked example: y = (3x + 1)². Split it into an inner step u = 3x + 1 and an outer step y = u². At x = 1:
- inner: u = 4, and u changes 3 times as fast as x (slope of 3x + 1 is 3);
- outer: y = 16, and y changes 2u = 8 times as fast as u (slope of u² is 2u);
- chain: y changes 8 × 3 = 24 times as fast as x.
Check by nudging: at x = 1.001, y = 4.003² = 16.024009, a change of 0.024009 for a nudge of 0.001, i.e. 24.009 per unit. Correct.
A neural network is a long chain of simple steps ending in the error. The chain rule, applied from the error backwards one step at a time, gives the slope for every parameter. That procedure is backpropagation (Module 5).
5. Gradient descent: walking downhill
Imagine standing on a hillside in fog. You can't see the valley, but you can feel which way the ground slopes under your feet. Take a small step downhill; feel again; repeat. That is gradient descent. For one parameter w and an error L:
η ("eta") is the learning rate: the size of the step. The minus sign means "go against the slope": if the error rises as w rises (positive slope), decrease w, and vice versa.
By hand
Take L(w) = (w − 3)². Its lowest point is at w = 3. Its slope is 2(w − 3) (chain rule: outer 2u, inner slope 1). Start at w = 0 with η = 0.1:
| Step | w | Slope 2(w − 3) | Change −0.1 × slope | New w |
|---|---|---|---|---|
| 1 | 0 | −6 | +0.6 | 0.6 |
| 2 | 0.6 | −4.8 | +0.48 | 1.08 |
| 3 | 1.08 | −3.84 | +0.384 | 1.464 |
Each step moves w towards 3, and the steps get smaller as the slope flattens near the bottom.
Why the learning rate matters
The lab runs 25 steps at three learning rates:
learning rate 0.1: after 25 steps w = 2.9887 (creeps steadily towards 3)
learning rate 0.9: after 25 steps w = 3.0113 (overshoots back and forth, but settles)
learning rate 1.1: after 25 steps w = 289.1886 (each step overshoots further: diverges)
You can see why from the update itself. The distance from the target, d = w − 3, becomes d − η × 2d = (1 − 2η) × d after one step:
| η | Each step multiplies the distance by | Result |
|---|---|---|
| 0.1 | 0.8 | Shrinks steadily |
| 0.9 | −0.8 | Flips side each time, but still shrinks |
| 1.1 | −1.2 | Flips side and grows: the walk explodes |
Too small and training crawls; too large and it blows up. TrayCheck uses 0.0005 to train its new head and 0.00001, 50 times smaller, when adjusting the pre-trained layers (Module 8).
Two parameters
With more parameters, the gradient tells each one which way to move. Take L(w, b) = (2w + b − 7)², the squared error of the prediction 2w + b against a target of 7. At w = 1, b = 1 the prediction is 3, the miss is 3 − 7 = −4, and L = 16. By the chain rule (outer 2 × miss, inner slope 2 for w and 1 for b):
- ∂L/∂w = 2 × (−4) × 2 = −16
- ∂L/∂b = 2 × (−4) × 1 = −8
Both slopes are negative, so increasing either parameter lowers the error. One step with η = 0.05 gives w = 1 + 0.8 = 1.8 and b = 1 + 0.4 = 1.4. The new prediction is 5, the miss −2, and the error falls from 16 to 4. Training a network is this, repeated, for millions of parameters at once.
One caution. A real model's error surface has millions of dimensions and many dips, so gradient descent finds a good low point, not a guaranteed lowest one. For neural networks this works remarkably well in practice.
Part B · Probability and statistics for evaluation
6. Probability: two rules
A probability is a number from 0 to 1 saying how often something happens in the long run. "The model is right with probability 0.9" means: over many photos like these, it's right about 9 times in 10. The chance of something not happening is 1 minus the chance it does.
A probability distribution lists every possible outcome with its probability; the probabilities add up to 1. TrayCheck's output for each photo is one: four probabilities, one per dish, adding to 1.
Rule 1: "and" for independent events means multiply
Two events are independent if knowing one happened tells you nothing about the other. For independent events:
Why: event A happens in a share P(A) of all cases. Among those cases, B happens in a share P(B), because A tells you nothing about B. So both happen in a share P(A) × P(B).
Example: a model is right 90% of the time on photos it hasn't seen, and two photos are independent. The chance it gets both right is 0.9 × 0.9 = 0.81.
When events are not independent, the rule fails. Two photos of the same tray aren't independent: if the model gets one wrong, it probably gets the other wrong too. This is why Module 9 insists that test examples be independent of training examples, and of each other.
Rule 2: "or" for events that can't both happen means add
If A and B can't happen together, P(A or B) = P(A) + P(B). A photo can't be both "predicted ribs" and "predicted bibimbap", so the chance it is predicted as one of them is the sum.
Conditional probability: "given that"
P(A | B), read "the probability of A given B", is the share of B cases in which A also happens. You restrict attention to the B cases first, then count.
This is exactly what precision and recall are (Module 10), and why they differ. From TrayCheck's 160 test photos:
- Precision for bibimbap = P(really bibimbap | predicted bibimbap). The model said "bibimbap" 43 times; 37 were. 37/43 = 0.86.
- Recall for bibimbap = P(predicted bibimbap | really bibimbap). There were 40 real bibimbaps; the model found 37. 37/40 = 0.925.
Same 37 correct photos, different "given", different number. Mixing up P(A | B) and P(B | A) is one of the most common reasoning errors in medicine, law and machine learning.
7. From scores to probabilities: softmax
A classifier's last layer produces one raw score per class, called a logit. Logits can be any number, positive or negative, and don't add up to anything in particular. Softmax turns them into a probability distribution in two steps:
- Apply eˣ to each score: everything becomes positive, and order is kept (§2).
- Divide each by the total: now they add up to 1.
Worked example with four scores z = [2, 1, 0.1, −1]:
| Dish 1 | Dish 2 | Dish 3 | Dish 4 | Total | |
|---|---|---|---|---|---|
| Score z | 2 | 1 | 0.1 | −1 | |
| eᶻ | 7.389 | 2.718 | 1.105 | 0.368 | 11.580 |
| ÷ total | 0.638 | 0.235 | 0.095 | 0.032 | 1.000 |
Two properties used later:
- Only differences between scores matter. Adding 100 to every score multiplies every eᶻ by the same factor e¹⁰⁰ (power rule), which cancels when dividing by the total.
- Dividing every score by a "temperature" T changes how confident the result looks without changing which class wins. T > 1 squeezes scores together (flatter, less sure); T < 1 spreads them apart (peakier). Module 10 uses this to calibrate TrayCheck's scores.
8. Why the training loss is −ln(p): likelihood
Training needs one number that says how wrong the model is, so gradient descent can lower it. Which number? Here is the principled answer, built from Rule 1.
Likelihood. Suppose the model gives the correct dish probabilities 0.9, 0.6 and 0.8 on three training photos. If the photos are independent, the probability that the model "produces" all three correct labels is the product:
0.9 × 0.6 × 0.8 = 0.432
That product is the likelihood of the data under these parameter values. Another setting of the parameters giving 0.7, 0.7, 0.7 has likelihood 0.343, which is worse. Good parameters make the correct answers likely, so training should choose parameters that maximise the likelihood. This principle is called maximum likelihood.
Two practical problems, one fix. With 400 photos the product is tiny: even 0.9 multiplied 400 times is about 5 × 10⁻¹⁹, too small for a computer to handle accurately. And products are awkward to differentiate. Taking the logarithm fixes both, because ln turns a product into a sum (§2) and keeps the same best parameters (ln keeps order):
ln(0.9 × 0.6 × 0.8) = ln 0.9 + ln 0.6 + ln 0.8 = −0.105 − 0.511 − 0.223 = −0.839
Finally, flip the sign (so the goal is to minimise, as gradient descent does) and average over the n examples:
where pᵢ is the probability the model gave to the correct answer for example i. This is the
cross-entropy loss, also called log-loss. Keras calls it sparse_categorical_crossentropy,
and it is TrayCheck's training loss. For the three photos: 0.839 / 3 = 0.280.
What it rewards and punishes, from the table in §2:
right answer got probability 0.99: loss 0.010
right answer got probability 0.5: loss 0.693
right answer got probability 0.01: loss 4.605 ← confident and wrong is punished hard
Why not just train on accuracy? Accuracy only changes when a prediction flips from wrong to right, so nudging a parameter usually changes it by nothing: its slope is zero almost everywhere, and gradient descent gets no direction. Log-loss changes smoothly with every probability, so it always has a slope to follow.
9. Average and spread: mean, variance, standard deviation
The mean
The mean (average) is the total divided by the count. Module 10 compares an AI's waste estimates with weighed values on six trays; the differences (AI minus scale, in grams) were:
15, −10, 30, 15, 10, −10
Mean = 60 / 6 = 8.33 g. On average the AI over-estimates by about 8 g.
The spread
Two sets of numbers can share a mean and differ wildly in spread: [8, 8, 9] and [−50, 8, 67] both average about 8.3. To measure spread:
- Find each value's deviation from the mean: 6.67, −18.33, 21.67, 6.67, 1.67, −18.33.
- Square them, so negatives don't cancel positives: 44.4, 336.1, 469.4, 44.4, 2.8, 336.1.
- Average the squares. This is the variance. Divide by n − 1 = 5 rather than 6: 1,233.3 / 5 = 246.7. (Dividing by n − 1 is a small correction. The deviations were measured from a mean computed from the same numbers, which makes them slightly too small; with large n the difference vanishes.)
- Take the square root to get back to the original units: √246.7 = 15.7 g. This is the standard deviation (SD).
Read the SD as "a typical distance from the mean". Here: the AI is 8 g too high on average, and individual trays typically miss that average by about 16 g.
The spread of a yes/no quantity
Many evaluation numbers are shares of yes/no outcomes: right or wrong, flagged or not. Code each outcome as 1 (yes) or 0 (no). If the share of 1s is p:
- the mean is p (the average of a list of 0s and 1s is the share of 1s);
- the variance is p(1 − p).
Why: a share p of values sit at 1, a distance 1 − p from the mean; the rest sit at 0, a distance p away. The average squared distance is p(1 − p)² + (1 − p)p² = p(1 − p) × [(1 − p) + p] = p(1 − p).
For TrayCheck's test accuracy, p = 0.8875: variance 0.8875 × 0.1125 = 0.0998, SD 0.316. That is the spread of a single photo's right-or-wrong outcome. The next section asks how much the average over 160 photos would wobble.
10. Samples, and the binomial distribution
A test set is a sample: a limited set of examples standing in for all the photos the model will ever see (the population). The share right in the sample, written p̂ ("p-hat"), is an estimate of the true share p. Test a different 160 photos and you'd get a somewhat different p̂. How different?
Start with counting. Suppose each spot check (Module 11) independently finds an error with probability p. What's the chance of exactly k errors in n checks?
Tiny case first: n = 3 checks, p = 0.1.
- 0 errors: all three fine, 0.9 × 0.9 × 0.9 = 0.729 (Rule 1).
- 1 error: the error could be check 1, 2 or 3; each arrangement has probability 0.1 × 0.9 × 0.9 = 0.081, and they can't happen together, so add them (Rule 2): 3 × 0.081 = 0.243.
- 2 errors: 3 arrangements × 0.1 × 0.1 × 0.9 = 0.027.
- 3 errors: 0.1³ = 0.001.
The four add to 1.000, as a distribution must. The general pattern is the binomial distribution:
where the first factor, read "n choose k", counts the arrangements (3 in the example above).
A real case: 55 spot checks when the true hidden error rate is 3%. The exact binomial probabilities, and the lab's simulation of 10,000 such months:
| Errors found | Estimate k/55 | Exact probability | Lab simulation |
|---|---|---|---|
| 0 | 0.0% | 18.7% | 19.0% |
| 1 | 1.8% | 31.9% | 31.4% |
| 2 | 3.6% | 26.6% | 26.6% |
| 3 | 5.5% | 14.5% | 14.9% |
| 4 or more | 7.3% or more | 8.3% |
A true rate of 3% shows up as anything from 0% to 7% in a single month. One in five months finds no errors at all. A single estimate from a small sample is rough, and the next two sections put a number on how rough.
11. Why averages settle down: the standard error
Here is the key fact, with a check you can do by hand.
Spreads of independent quantities add as variances. If you add two independent quantities, the variance of the total is the sum of their variances. Check with dice: one die (1 to 6) has variance 2.917. Listing all 36 equally likely outcomes of two dice shows the total has variance 5.833, exactly double. (Why it works: the deviations of independent quantities are as likely to partly cancel as to pile up, and those effects balance exactly when you square and average.)
Now average n independent yes/no outcomes, each with variance p(1 − p):
- the total has variance n × p(1 − p);
- the average is the total divided by n. Dividing a quantity by n divides its variance by n², so the average has variance p(1 − p) / n;
- take the square root to get its SD.
The SD of an estimate is called its standard error (SE):
TrayCheck: √(0.0998 / 160) = 0.025, i.e. 2.5 percentage points. One photo's outcome has an SD of 0.316; the average of 160 has an SD 12.6 times smaller (√160 ≈ 12.6).
Notice the square root of n: to halve the standard error you need four times as many examples, not twice as many. That single fact drives every sample-size decision in a PoC.
12. The bell curve, 1.96, and the 95% interval
The bell curve
When a quantity is the sum (or average) of many independent small pieces, its distribution comes out bell-shaped, whatever the pieces look like individually. This is the central limit theorem, and the bell shape is the normal distribution. The number of correct photos out of 160 is a sum of 160 independent 0s and 1s, so it is close to normal: centred on 142, with SD 4.0 photos.
A normal distribution is fixed by its mean and SD, and the share of values within a given number of SDs of the mean is always the same:
| Within | 1 SD | 1.96 SD | 3 SD |
|---|---|---|---|
| Share of values | 68.3% | 95.0% | 99.7% |
That is where 1.96 comes from: it is the distance, in SDs, that captures the middle 95%.
The 95% interval
Combine the pieces. The estimate p̂ lands within 1.96 SE of the true p in about 95% of samples. Turn that around: if every time you test you report
the range will contain the true value about 95% of the time. That range is a 95% confidence interval. For TrayCheck: 0.8875 ± 1.96 × 0.025 = 0.8875 ± 0.049, so 83.8% to 93.6%.
What "95%" means, precisely: it describes the method. If you repeated the whole test many times with fresh photos, about 95% of the intervals produced would contain the true accuracy. (A simulation of 20,000 repeated tests with TrayCheck's numbers gives 94.3%, close to 95%.) Any one interval either contains the truth or doesn't; you just don't know which.
This simple version assumes the bell shape fits well. Near 0% or 100%, or with few examples, it doesn't: the distribution is squashed against the boundary and lopsided. The interval then misbehaves (it can even go below 0%). The Wilson interval fixes that (Module 11 explains how), and it is what TrayCheck reports: 82.9% to 92.8% for 142 of 160.
How many examples does a test need?
Turn the formula around. If you want the ± part (the margin, E) to be a certain size:
For accuracy near 90% and a margin of ±5 points: 1.96² × 0.9 × 0.1 / 0.05² = 138, so about 140 checked trays. For ±3 points, about 385; for ±2 points, about 865. Module 10 turns this into PoC planning advice.
Check your understanding
1. In "meals = w × patients + b", which letters are inputs, outputs and parameters? What does training do?
Patients is the input, meals the output, w and b the parameters. Training chooses the values of w and b that would have predicted past days best.
2. Without a calculator: is −ln(0.8) bigger or smaller than −ln(0.5)? Why does the loss care?
Smaller. 0.8 is closer to 1, and −ln(p) shrinks towards 0 as p approaches 1 (−ln 0.8 ≈ 0.22; −ln 0.5 ≈ 0.69). Giving the correct answer more probability means less loss.
3. A batch of 32 feature vectors of length 1280 goes through Dense(96). What's the weight matrix shape, the output shape and the parameter count?
W is (1280, 96); the output is (32, 96) by the shape rule; parameters = 1280 × 96 + 96 = 122,976,
exactly the dense layer's count in TrayCheck's model.
4. y = (2x − 1)². Use the chain rule to find the slope at x = 2, and check it by nudging.
Inner u = 2x − 1 = 3, slope 2. Outer y = u², slope 2u = 6. Chain: 6 × 2 = 12. Nudging: at x = 2.001, y = 3.002² = 9.012004, so (9.012004 − 9)/0.001 ≈ 12.
5. Gradient descent on (w − 3)² with learning rate 0.5, starting at 0. Where is w after one step, and why?
Exactly 3. The slope at 0 is −6, the step is −0.5 × −6 = +3. With η = 0.5 the multiplier (1 − 2η) is 0, so the distance to the target vanishes in one step. Real problems are never this tidy.
6. Softmax of [2, 1, 0.1, −1] is about [0.64, 0.23, 0.10, 0.03]. What is softmax of [12, 11, 10.1, 9]?
The same. Adding a constant to every score multiplies every eᶻ by the same factor, which cancels when dividing by the total.
7. The model said "ribs" 40 times and 36 were ribs; there were 40 real ribs. Write precision and recall as "probability of … given …".
Precision = P(really ribs | predicted ribs) = 36/40 = 0.90. Recall = P(predicted ribs | really ribs) = 36/40 = 0.90. Here they happen to be equal; usually they aren't.
8. Why is accuracy useless as a training loss, but fine as a reported result?
Accuracy only changes when a prediction flips, so its slope with respect to a parameter is zero almost everywhere and gradient descent gets no direction. As a reported result it's easy to understand, which is what a report needs.
9. Derive the standard error of an accuracy measured on 400 photos at p = 0.9, and say how it compares with 100 photos.
√(0.9 × 0.1 / 400) = √0.000225 = 0.015, i.e. 1.5 points. With 100 photos it's √(0.0009) = 0.03, 3 points. Four times the photos halves the standard error.
10. "Our 95% interval is 83% to 93%." Is it right to say "there's a 95% chance the true accuracy is in that range"?
Not strictly. The 95% describes the method: intervals made this way contain the truth in about 95% of repeated tests. In everyday conversation the looser phrasing is common and usually harmless, but the precise version is the one to give if asked.
Go deeper
Everything above is self-contained. These are for a second angle on the same ideas, or for going further.
For intuition (free)
- 3Blue1Brown, Essence of Linear Algebra (chapters 1–4) and Essence of Calculus (chapters 1–4, including the chain rule). Short animated videos. 3blue1brown.com
- Seeing Theory (Brown University): interactive probability and statistics, especially Basic Probability, Probability Distributions and Frequentist Inference. seeing-theory.brown.edu
- Khan Academy, Statistics and probability: the units on summarising quantitative data (variance and standard deviation), probability, and confidence intervals. khanacademy.org
One level more formal (free)
- Deisenroth, Faisal & Ong, Mathematics for Machine Learning (2020): Chapter 2 (linear algebra), Chapter 5 (vector calculus) and Chapter 6 (probability). mml-book.github.io
- Dive into Deep Learning, chapter Preliminaries: linear algebra, calculus, automatic differentiation and probability, with runnable code. d2l.ai
- Goodfellow, Bengio & Courville, Deep Learning, Chapters 2–4, including §3.13 on where the name "cross-entropy" comes from (information theory). deeplearningbook.org
Interview angle
"Training minimises cross-entropy, the negative log of the probability the model gives the right answer. It comes from maximum likelihood: you want parameters that make the correct labels as probable as possible, and the log turns that product into a sum you can minimise with gradient descent.
On the evaluation side, any accuracy from a test set is an estimate. Its standard error is the square root of p(1 − p)/n, so 160 photos at about 89% gives roughly ±5 points at 95%. Halving that needs four times as many examples, which is why I'd agree the sample size before a pilot starts."