Index Ai Academy
Foundation · Statistics and information

Review: find the slip (statistics and information)

Statistics slips to fix, mixed practice from the module, and its formula sheet.

About 38 minutes · Free lesson

What it covers6

Why it matters

Module 7's slips are the ones that reach reports. A mean pulled up by one slow request goes on a dashboard as "typical". A loss that hits a probability of exactly 0 prints inf, and a night of training is lost. A softmax without its exponential still adds up to 1, and quietly gives the wrong chances. A sample size planned on "twice the data, half the wobble" comes out four times too small. A model's training error is reported as what users should expect. Recall is reported where precision was meant, a two-point lead between models is announced before anyone asks whether it's luck, and a KL divergence is computed the wrong way around. Each runs without complaint. This review gathers the eight, each with the check that catches it, mixes problems from all of Module 7, and collects every rule on one sheet, ready for Module 8.

What you'll be able to do

  • Spot the common slips of Module 7: a mean pulled by an outlier, a log of zero, softmax without the exponential, twice the data expected to halve the wobble, training error reported as test error, precision and recall swapped, a lucky win taken as real, and KL turned around
  • Find and fix slips in statistics code that runs but gives a wrong answer
  • Mix problems from every lesson of the module, and run a short statistics program in your head, line by line
  • Use the module's formula sheet: each rule, what it says, and its Python line, and see where Module 7 sits in a model
Quick check
Have a guess before you start. A team reports "our model's error is 0.02" from the data it was trained on. What should you ask?
  1. Nothing: 0.02 is low
  2. Which library was used?
  3. What's the error on held-back data?
  4. How long did the training run take?
Show the answer

What's the error on held-back data?

Training error flatters a model; only held-back data shows what to expect on new cases (lesson 101).

Find the slip

Purpose. Eight slips cover most of Module 7's mistakes, and each has a quick check. The first five come from describing data, samples, regression, likelihood and softmax:

  • A mean pulled by an outlier. One 40-second request makes the "typical" time 10 seconds. Check: compare the mean with the median; a big gap means a lopsided column.
  • A log of zero. A probability that rounds to exactly 0 makes −log p infinite. Check: is the loss finite? Clip probabilities into [ε, 1 − ε] before the log.
  • Softmax without the exponential. z / z.sum() adds up to 1 but isn't softmax, and breaks on negative scores. Check: a score of 0 must still get a positive share.
  • Twice the data for half the wobble. The standard error divides by √n, so halving it takes four times the data. Check: σ/√(2n) is σ/√n divided by only 1.41.
  • Training error reported as test error. Check: which rows was the error computed on? Only held-back rows count.

Put numbers on the fourth slip before reading on.

Quick check
A standard error is 2 with 100 samples. How many samples bring it down to 1?
  1. 150
  2. 1,000
  3. 400
  4. 200
Show the answer

400

Halving σ/√n needs √n twice as big: 4 × 100 = 400 samples.

The last three slips come from the lessons on judging models and measuring a gap between distributions:

  • Precision and recall swapped. Both count the model's right yeses. Precision divides by every yes the model said, TP + FP; recall divides by every real yes, TP + FN. Check: a model that says yes to everything must get a recall of 1.
  • A lucky win taken as real. One model's lead over another on a test set can be noise. Check: compare them item by item, and see whether 0 falls outside the 95% range of the mean difference. And after k tries, the chance of at least one false win is 1 − 0.95ᵏ, not 0.05 × k.
  • KL turned around. KL(p ‖ q) weights each gap by the truth p and puts p on top of each ratio. Swapped, it's KL(q ‖ p), usually a different number. Check: which of the two is the truth?

Below are fifteen worked lines, with a comment saying what each should give. Eight have a slip.

Try it now

How the checks catch them. Each slip fails a one-line test. Printing the mean beside the median shows 10.4 against 3 for the response times. Printing the loss shows inf. Feeding the "softmax" a score of −1 gives a negative share. Computing σ/√(2n) shows the wobble shrank by 1.41, not 2. Asking "which rows?" of the reported error shows they were the training rows. A model that says yes to everything gets a "recall" below 1 from the swapped formula. Twenty tries at 0.05 each give a "chance" of 1. And naming the truth before writing a KL fixes its order. Predict the next one before you run it.

Quick check
What does this print?
import numpy as np

x = np.array([2.0, 3.0, 4.0, 3.0, 40.0])
print(x.mean(), np.median(x))
  1. 3.0 10.4
  2. 10.4 4.0
  3. 3.0 3.0
  4. 10.4 3.0
Show the answer

10.4 3.0

The 40 pulls the mean up to 10.4, above four of the five values; the median, the middle of 2, 3, 3, 4, 40, stays at 3.

Slips that hide in code. Like the earlier modules', these slips mostly run without an error. A softmax without its exponential passes the "adds up to 1" check for positive scores. A loss of inf only shows up when someone reads the printout, and nan can poison every weight within a step. The two drills below are slips of this kind: each runs, each gives a confident wrong answer, and one check exposes each.

Drill

A softmax with no exponential

This softmax adds up to 1 but gives the wrong chances, and a negative score gets a negative chance. Find the slip and fix it, keeping the safe shift.

import numpy as np

def softmax(z):
    z = z - z.max()
    return z / z.sum()

print(softmax(np.array([2.0, 1.0, 0.1])))
In the lesson, your code is checked as you write it.
In your own words
Which check would you run on any function that's meant to return a probability distribution, and why that one?

Write a sentence or two, then compare it with a good answer in the lesson.

Mixed practice

Purpose. Problems from across Module 7, mixed. Name each one's lesson before you start: describing data, samples, comparing models, likelihood, regression, logistic regression, scoring a classifier, softmax, entropy or KL divergence. If one stops you, the steps show the way, and the formula sheet in the last part has every rule in one place.

Play computer. The program below runs the module in small: a mean against a median, a standard error, precision and recall from the same counts, a lead read from paired differences (+1 where only B is right, −1 where only A is), and a KL divergence. Several lines sit where this review's slips hide. Work out every value in your head before you type it, the way Python prints it. .item() turns NumPy's one-number answers into plain Python numbers, so they print plainly.

Worked example

Worked example: evaluating a classifier with its checks built in

Score a two-class model on its training rows and its held-back rows, checking that every softmax row adds up to 1 and that no probability can hit log 0.

import numpy as np

def chances(S):
    E = np.exp(S - S.max(axis=1, keepdims=True))
    return E / E.sum(axis=1, keepdims=True)

def loss(S, y):
    P = chances(S)
    total = 0.0
    for i in range(len(y)):
        total = total - np.log(np.clip(P[i, y[i]], 1e-12, 1))
    return P, total / len(y)

P, train = loss(np.array([[2.0, 0.5], [0.2, 1.5], [1.8, 0.1], [0.3, 2.2]]), np.array([0, 1, 0, 1]))
Q, test = loss(np.array([[1.0, 0.9], [0.4, 0.6], [2.5, 0.2]]), np.array([1, 1, 0]))
print("rows add to 1:", P.sum(axis=1).round(6).tolist())
print("train:", round(float(train), 3), "test:", round(float(test), 3))
It runs right here in your browser, with nothing to install.

The safe softmax keeps every row a distribution; the clip means a confident wrong answer costs a large but finite loss rather than inf. Then the honest number: the cross-entropy on the four training rows is 0.187, on the three held-back rows 0.479, more than twice as high. The test figure is the one to report, and the gap says the model fits its own rows better than new ones. Three checks, two lines each, catch most of this module's slips.

Quick check
What does this print?
import numpy as np

z = np.array([1.0, 0.0])
print((z / z.sum()).tolist(), (np.exp(z) / np.exp(z).sum()).round(3).tolist())
  1. [1.0, 0.0] [1.0, 0.0]
  2. [1.0, 0.0] [0.731, 0.269]
  3. [0.5, 0.5] [0.731, 0.269]
  4. [0.731, 0.269] [1.0, 0.0]
Show the answer

[1.0, 0.0] [0.731, 0.269]

Without the exponential, the score 0 gets no share at all; with it, e⁰ = 1 still earns 0.269 against e¹ = 2.718.

Quick check
A training loop prints loss: 0.41, 0.38, inf, nan, nan. Which slip is most likely?
  1. The learning rate is too small
  2. The model is already perfect
  3. A probability hit 0, and its log became −inf
  4. The data has an outlier in the mean
Show the answer

A probability hit 0, and its log became −inf

−log 0 is inf, and the next steps turn inf into nan. Clipping probabilities before the log, or computing the loss from the scores directly, prevents it.

Drill

A loss that blows up

This loss is meant to average −log of the chances the model gave the right answers, but one chance has rounded to 0.0 and the loss prints inf. Fix it by clipping the chances into [1e-12, 1] before the log.

import numpy as np

def nll(p_right):
    return float(-np.mean(np.log(p_right)))

print(nll(np.array([0.9, 0.0, 0.8])))
In the lesson, your code is checked as you write it.
In your own words
Which kind of problem in the mixed ladder did you have to stop and think about most? What told you which method to use?

Write a sentence or two, then compare it with a good answer in the lesson.

The formula sheet

Purpose. Every rule of Module 7 in one place, with what it says and its Python line.

lessonrulein plain wordsin Python
97x̄ = (1/n) Σ xᵢ; s = √((1/n) Σ (xᵢ − x̄)²); z = (x − x̄)/scenter, spread, distance in s'sx.mean(), np.median(x), x.std(), np.percentile(x, 95)
98SE = σ/√n; x̄ ± 1.96·s/√nthe wobble of an averagesigma / n ** 0.5
99dᵢ = bᵢ − aᵢ; d̄ ± 1.96·s_d/√n; P(at least one false win in k tries) = 1 − 0.95ᵏcompare item by item; the lead is real when 0 is outside its ranged = b - a, d.mean(), d.std() / len(d) ** 0.5
100log L(θ) = Σ log P(xᵢ given θ); θ̂ = argmaxthe setting that makes the data least surprisingps[np.argmax(ll)]
101w = cov(x, y)/var(x); b = ȳ − w·x̄the line with the smallest squared missesnp.linalg.lstsq(X, y, rcond=None)
Quick check
Which row of the sheet so far catches "twice the data halves the wobble"?
  1. Lesson 98: SE = σ/√n
  2. Lesson 100: the log-likelihood
  3. Lesson 97: the z-score
  4. Lesson 101: the slope
Show the answer

Lesson 98: SE = σ/√n

The √n says the wobble shrinks with the square root of the data: halving it takes four times as much.

The rest of the sheet:

lessonrulein plain wordsin Python
102σ(z) = 1/(1 + e⁻ᶻ); L = −[y log p + (1 − y) log(1 − p)]; slope p − ya score into a chance; the cost of a yes-or-no guess1 / (1 + np.exp(-z))
103precision = TP/(TP + FP); recall = TP/(TP + FN); F1 = 2PR/(P + R)right out of the model's yeses; found out of the real yesestp = np.sum((y == 1) & (pred == 1))
104pᵢ = e^(zᵢ)/Σⱼ e^(zⱼ)scores into chances that add to 1e = np.exp(z - z.max()); e / e.sum()
105H(p) = −Σ pᵢ log₂ pᵢ; H(p, q) = −Σ pᵢ log₂ qᵢ; perplexity 2^Haverage surprise; the model's average surprisep @ np.log2(1 / q)
106KL(p ‖ q) = Σ pᵢ log₂(pᵢ/qᵢ); H(p, q) = H(p) + KL(p ‖ q)the model's extra surprise over the truth's own; 0 only when they matchp @ np.log2(p / q)

Each row is also a check: if an answer breaks a row, the slip is in that step.

Quick check
Which row of the rest of the sheet says why lowering a model's cross-entropy shrinks its KL divergence?
  1. Lesson 106: H(p, q) = H(p) + KL(p ‖ q)
  2. Lesson 103: F1 = 2PR/(P + R)
  3. Lesson 102: the logistic slope p − y
  4. Lesson 104: the safe softmax, shifted
Show the answer

Lesson 106: H(p, q) = H(p) + KL(p ‖ q)

The data fixes its own entropy H(p), so cross-entropy can fall only as far as the KL gap above it does: lowering one lowers the other by the same amount.

Where Module 7 lives in a model. Statistics is how a model is fit and how it's judged. Describing data scales its input numbers so no feature drowns the rest, and a batch's gradient wobbles like any average, by σ/√n. Likelihood picks its loss: squared error for a line, and for a classifier −log of the right answer's chance, the cross-entropy against the targets, which is the data's own entropy plus a KL gap. Logistic regression and softmax turn its scores into chances. And judging it is statistics too: held-back rows, precision and recall read from the confusion table, and an error bar on its lead over the last model. The map below lights all of it.

Coming up. First, lesson 108 turns this module's formulas around: sample sizes from error bars, inputs from chances, logit gaps from softmax, and chances from bits and losses. Then Module 8 has no new math: it runs everything at once. Lesson 109 trains one neuron by hand, from weighted sum to update. Lesson 110 stacks neurons into layers as matrix products, with softmax at the end. Lesson 111 trains that network with cross-entropy and the slope p − y flowing backward, lesson 113 builds attention from dot products and softmax, and lesson 118 is the capstone: a sign reader from the formulas alone.

In your own words
Pick the rule on the sheet you're most likely to slip on. What check would you use to catch the slip?

Write a sentence or two, then compare it with a good answer in the lesson.

Goes deeper in

Practice what you just read

  • 1 code example you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 12 review cards for spaced repetition

Try a quiz question

What's the slip in p = z / z.sum() used as a softmax?

  1. No exponential: negative scores get negative chances
  2. It should divide by z.max()
  3. It should subtract the mean of the scores first
  4. There's no slip

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Foundation · about 96 hours of study

Foundation math

From whole numbers to the math inside a neural network: each idea by hand, in Python, and in AI 118 lessons All free
  1. Numbers and place value FreeWhat a digit's place is worth, the number line, and Python as a calculator that never tires.36 min
  2. Multiplying and dividing: groups FreeEqual groups, quotient and remainder, and cutting training data into batches.35 min
  3. Order of operations, and names for numbers FreeBrackets, powers, then multiply and divide, then add and subtract; variables hold numbers.36 min
  4. Numbers below zero FreeThe number line through zero, sign rules, distance from zero, and an error's direction and size.37 min
  5. Fractions: equal parts, equal fractions, adding FreePieces of a whole, equal fractions, and re-cutting to add; accuracy as a fraction.45 min
  6. Multiplying and dividing fractions FreeA share of a share, dividing by flipping, and why chances in a row get small.35 min
  7. Decimals and rounding FreeFractions in place value, rounding, and why 0.1 + 0.2 isn't exactly 0.3.36 min
  8. Percentages FreePer hundred, percent change, percentage points, and the accuracy and error rates of models.35 min
  9. Ratios, rates and proportion FreeSharing in a ratio, rates per unit, scaling, and splitting data 80/10/10.35 min
  10. Powers and roots FreeRepeated multiplying, the laws of exponents, square roots, and squared error.43 min
  11. Very big and very small numbers FreePowers of ten, e-notation like 3e-4, orders of magnitude, and a model's size in memory.36 min
  12. Bits, bytes and floats: how numbers are stored FreeBase 2, what n bits can hold, a float as sign, power and digits, and a tensor's memory.35 min
  13. Review: find the slip (numbers) FreeBroken calculations to fix, mixed practice from the whole module, and its formula sheet.34 min
  14. Letters for numbers FreeVariables, terms and like terms, substitution, and a model's formula as a Python function.41 min
  15. Expanding and factoring FreeBrackets as areas, pulling out common factors, and a squared error expanded into a bowl.41 min
  16. Solving equations: keep the balance FreeThe same move on both sides, undoing steps in reverse, and running a model's formula backward.41 min
  17. Rearranging a formula FreeMaking any letter the subject, round-trip checks, and planning a training run.36 min
  18. Inequalities and true-or-false FreeRanges, flipping the sign, if and elif, and the thresholds, clips and ReLU inside a model.42 min
  19. Functions: a rule from input to output Freef(x) notation, tables and graphs, domain and range, loops over lists, and loss as a function.42 min
  20. Chaining and undoing functions Freeg(f(x)), inverses that undo, scaling and unscaling, and a network as a chain.42 min
  21. Straight lines: slope and intercept FreeRise over run, the line through two points, and a model's weight and bias as slope and intercept.42 min
  22. Two equations, two unknowns FreeSubstitution and elimination, where lines cross, and why models are fitted, not solved.42 min
  23. Quadratics: bowls and their lowest point FreeRoots by factoring and by formula, the discriminant, the vertex, and the best weight of a model.42 min
  24. Exponentials: growth and decay FreeThe same factor each step, the number e, and decaying learning rates.43 min
  25. Logarithms: the power question FreeTo what power?, the laws of logs, and adding log-probabilities instead of multiplying.45 min
  26. Sequences and Σ FreeArithmetic and geometric sequences, Σ as a loop that adds, and mean squared error.40 min
  27. Weighted and moving averages FreeWeights that add to 1, a window average, the exponential moving average, and smoothing a loss curve.35 min
  28. Sets, and reading the symbols FreeSets, union and intersection, ℝⁿ and f : ℝⁿ → ℝᵐ, and reading a paper's first equation.41 min
  29. Review: find the slip (algebra) FreeBroken algebra and code to fix, mixed practice from the whole module, and its formula sheet.34 min
  30. Transposing step by step: undo in reverse order FreeA formula's layers, the opposite of each, peeling from the outside in, conditions, and round-trip checks.35 min
  31. Formulas with fractions: clear them first FreeClearing denominators, cross-multiplying, a letter in the bottom, and reciprocal formulas like 1/R = 1/R₁ + 1/R₂.35 min
  32. When the letter appears twice: collect and factor FreeGathering the letter on one side, factoring it out, dividing by the bracket, and rearranging precision and F1.35 min
  33. Squares, roots and powers FreeSquare roots with ±, squaring to undo a root, cube and nth roots, and the √d inside attention.40 min
  34. When the letter is squared and plain: quadratics FreeRearranging into ax² + bx + c = 0, the formula, completing the square, and choosing the root that fits.35 min
  35. Letters in the power: exponentials and logarithms FreeTaking logs to bring a power down, exponentiating to free a letter, and the logit that undoes the sigmoid.40 min
  36. Rearranging inequalities: when the sign flips FreeThe four moves on an inequality, negatives and reciprocals that flip it, logs below 1, and sample sizes.35 min
  37. Inverse functions, lines and scaling FreeUndoing a function by making x the subject, domains that allow it, line forms, and unscaling predictions.40 min
  38. Sequences and sums: find n, a, d and r FreeEvery letter of the arithmetic and geometric formulas as the subject, and an average's window from its decay.40 min
  39. Combining formulas: substitute and eliminate FreePutting one formula inside another to remove a letter, and sizing a training run from a time or money budget.35 min
  40. Review: rearrange anything (algebra) FreeBroken rearrangements to fix, mixed practice from the whole algebra block, a strategy chart, and its formula sheet.35 min
  41. Coordinates and distance FreePoints as (x, y), Pythagoras, distance in any number of coordinates, and nearest neighbors.42 min
  42. Angles, degrees and radians FreeMeasuring a turn, converting units, arcs, and the angle between two arrows.36 min
  43. Sine and cosine FreeAcross and up: right triangles, the unit circle, and directions and rotations.42 min
  44. Waves: height, speed and shift FreeAmplitude, period and phase, sampling a wave, and position codes in transformers.37 min
  45. Review: find the slip (shapes and waves) FreeBroken geometry and code to fix, mixed practice from the module, and its formula sheet.29 min
  46. Angles, triangles and waves: rearranging with sin, cos and tan FreeSides and angles from SOH CAH TOA, principal values, arcs, polar coordinates, and a wave's time and period.45 min
  47. Vectors: lists of numbers that point FreeA list, a point and an arrow; components, dimension, NumPy arrays, and data as vectors.42 min
  48. Adding and scaling vectors FreeComponent-wise sums, scalar multiples, mixes, and the weight update w − ηg.43 min
  49. Length and distance: norms FreeL2, L1 and max norms, unit vectors, distance, and the norms inside losses and clipping.42 min
  50. The dot product FreeMultiply in pairs and add; a·a as squared length; a @ b; one neuron as a dot product.43 min
  51. Angle, cosine similarity and projection FreeDirection without length, perpendicular vectors, shadows, and search by meaning.45 min
  52. Perpendicular directions: bases and coordinates FreeOrthonormal directions, coordinates as dot products, rebuilding a vector, and taking a direction out.35 min
  53. Matrices: tables of numbers FreeRows, columns and entries; two-dimensional arrays and slices; a data set as a matrix.41 min
  54. Adding, scaling and transposing matrices FreeEntry-by-entry sums and scalings, the transpose, mean images, and tables turned around.36 min
  55. A matrix times a vector FreeEach row dotted with the vector, the size rule, A @ x, and a layer acting on one example.42 min
  56. Matrix multiplication FreeRow meets column, the size rule, order matters, and a batch through a layer: X W + b.45 min
  57. Identity, diagonal, triangular and symmetric FreeFour patterns and their jobs: rescaling, distance tables, and the causal mask.37 min
  58. Matrices as movements of space FreeStretches, flips, shears and rotations; columns as landing spots; chaining; a layer moving data.42 min
  59. Determinant and inverse FreeThe area factor ad − bc, singular matrices, undoing a matrix, and redundant features.42 min
  60. Solving systems by elimination FreeAugmented matrices, row moves, back-substitution, the three outcomes, and fitting weights.45 min
  61. Independence, span and rank FreeRedundant vectors, span, rank, outer products, and low-rank updates like LoRA.42 min
  62. Eigenvectors: directions that only stretch FreeAv = λv, checking candidates, np.linalg.eig, and the main direction of a data cloud.41 min
  63. SVD and PCA: the important directions first FreeA matrix as pieces by size, the best rank-k copy, compression, and PCA maps of data.45 min
  64. Tensors, shapes and broadcasting FreeAxes and shapes, reshape, axis=, broadcasting, and shapes through a small model.43 min
  65. One-hot vectors and lookup tables: embeddings FreeA one-hot row picks a table's row, a sentence looked up as vectors, and a score for every word.35 min
  66. Sliding dot products: convolution FreeA small pattern slid along a list and over a grid, output sizes, stride and padding, and shared weights.40 min
  67. Review: find the slip (vectors and matrices) FreeShape slips to fix, mixed practice from the module, and its formula sheet with shapes.36 min
  68. Vector equations: rearranging with arrows FreeSolving for a vector or a scale, recovering a gradient from two weight snapshots, and an angle from a dot product.40 min
  69. Matrix equations: multiply by the inverse, on the correct side FreeNo dividing by a matrix: inverses from the left or right, order, transposes, and the normal equations.40 min
  70. Rates of change FreeChange over change, secants, rates from readings with np.diff, and reading a loss curve.41 min
  71. Limits: what a value heads toward FreeApproaching from both sides, holes, corners and jumps, epsilon, and judging activations.37 min
  72. The derivative: slope at a point FreeShrinking secants, f′(x) and dy/dx, Δy ≈ f′Δx, and which way a weight should move.45 min
  73. Derivative rules FreeConstants, powers, multiples, sums, eˣ and ln x, checked numerically, and a squared error's slope.41 min
  74. The product rule and the chain rule FreeProducts and chains of functions, forward then backward, and one neuron's dL/dw.45 min
  75. Lowest points and curvature Freef′ = 0, the second-derivative test, tables, local and global minima, and convex losses.43 min
  76. Standing in for a curve near a point FreeTangent lines, a curvature term, growing error, and why learning rates must be small.37 min
  77. Partial derivatives FreeOne input at a time, ∂, nudging in Python, and the two slopes of a line's loss.41 min
  78. The gradient FreeAll the slopes as a vector, steepest climb and descent, a numerical gradient, and the loss gradient.42 min
  79. Gradient descent FreeStepping against the gradient, the learning rate, a training loop, and fitting a line.45 min
  80. Faster descent: momentum and Adam FreeMomentum and Adam by hand, the bias correction, and three optimizers down one narrow valley.40 min
  81. The chain rule with many paths: backpropagation by hand FreeGraphs, multiply along paths and add across them, gradient checks, and a 2-2-1 network by hand.45 min
  82. Automatic differentiation: how PyTorch finds every slope FreeA tape of steps walked backward, and requires_grad, backward(), .grad, zero_grad() and no_grad().40 min
  83. Jacobians and Hessians FreeSlopes of vector functions, a layer's Jacobian, second partials, and bowls, domes and saddles.42 min
  84. Integrals: adding up thin slices FreeStrip and trapezoid sums, summing undoes differencing, probability as area, and AUC.43 min
  85. Review: find the slip (calculus) FreeCalculus slips to fix, mixed practice from the module, and its formula sheet.36 min
  86. Rearranging in calculus: slopes, steps and constants FreeSetting a slope to zero, Newton's step, the chain rule turned around, constants from a point, and learning rates.45 min
  87. Counting: choices, orders and groups FreeThe counting principle, factorials, ordered picks and groups, and why attention's cost grows with the square of the length.43 min
  88. Probability: from counts to chances FreeEqually likely outcomes, the complement, distributions, seeded simulation, and a next-word model.43 min
  89. Combining events: and, or, independent FreeThe or rule, independence, probability trees, drawing with and without replacement, and chains of steps.42 min
  90. Conditional probability and Bayes' rule FreeConditionals from tables, why P(A | B) isn't P(B | A), Bayes' rule, and precision and recall.45 min
  91. Random variables and distributions FreeUncertain numbers, the probability of a range, sampling by slices, and sampling versus argmax.42 min
  92. Expected value, variance and standard deviation FreeProbability-weighted averages, spread in the data's own units, and a training loss as an expected value.42 min
  93. Bernoulli, binomial, uniform and normal FreeYes-or-no trials, counts of yeses, the 68-95-99.7 rule, z-scores, and an accuracy's error bar.45 min
  94. Two variables at once: covariance and correlation FreeJoint tables and marginals, covariance, correlation, the covariance matrix, and features that carry the same information.45 min
  95. Review: find the slip (probability) FreeProbability slips to fix, mixed practice from the module, and its formula sheet.36 min
  96. Probability formulas: solve for the missing chance FreeConditionals, Bayes' rule for the prior, the or rule, expected values, variance, and z-scores turned around.45 min
  97. Describing data: center, spread and scale FreeMean, median and mode, variance and standard deviation, percentiles, outliers, and standardizing features.42 min
  98. Samples, the law of large numbers and the central limit theorem FreeSamples and populations, the standard error σ/√n, the bell of averages, and error bars on test scores.43 min
  99. Is the difference real? Comparing two models FreePaired differences, a bootstrap interval, what a p-value is and isn't, and why many tries make lucky wins.40 min
  100. Maximum likelihood FreeLikelihoods as products, log-likelihoods as sums, grid search, underflow, and the negative log-likelihood loss.45 min
  101. Linear regression: the best line FreeResiduals, least squares by formula, three roads to one line, the matrix form, and train versus test error.45 min
  102. Logistic regression: a line that answers yes or no FreeThe sigmoid, the log loss, its slope p − y, a training loop, and choosing a threshold.45 min
  103. Scoring a classifier: confusion table, precision, recall, F1 FreeThe four cells, accuracy, precision, recall and F1, and what moving a threshold does to each.35 min
  104. Softmax: scores into probabilities FreeExponentiate and share out, shifting and temperature, the safe softmax, and a classifier's last step.43 min
  105. Surprise, entropy and cross-entropy FreeSurprise in bits, entropy, cross-entropy and KL divergence, perplexity, and a language model's loss.45 min
  106. KL divergence: how far one distribution is from another FreeKL by hand, cross-entropy as entropy plus KL, why it isn't symmetric, and a soft-target loss.35 min
  107. Review: find the slip (statistics and information) FreeStatistics slips to fix, mixed practice from the module, and its formula sheet.38 min
  108. Statistics and information: n, z, logits and bits FreeSample sizes from error bars, inputs from probabilities, logit gaps from softmax, and chances from bits and losses.40 min
  109. One neuron, start to finish FreeWeighted sum, activation, loss, slopes and update, by hand and in code, and what one straight line can and can't split.45 min
  110. A layer and a small network as matrices FreeTwo layers on a batch, the shape of every matrix, adding a hidden unit, and XOR solved.45 min
  111. Training a small network FreeThe backward pass in matrix form, gradient checks, a full training loop, and reading loss curves.45 min
  112. The same network in PyTorch Freenn.Sequential with the NumPy weights loaded, the same loss and slopes, then SGD and mini-batches.45 min
  113. Attention as matrix math FreeScaled dot-product scores, the causal mask, a row-by-row softmax, and blending value vectors.45 min
  114. Residual connections and layer norm FreeAdding the input back and why its slope keeps learning alive, layer norm by hand, and add and norm.40 min
  115. A transformer block, start to finish FreeA sentence through embeddings, attention, add and norm, a small network and next-word scores, every shape named.45 min
  116. Planning a model: rearranging the formulas of a working network FreeLayer widths from parameter counts, sizes from memory and compute, the attention scale, and a training plan.40 min
  117. Final test: transpose any formula FreeSlips to fix from every topic, mixed practice of every kind of rearranging, the strategy chart and the full sheet.45 min
  118. Capstone: a sign reader from the formulas FreeBuild, train and test a trail-sign classifier with NumPy alone, and report its accuracy with an error bar.45 min
Part of a free course 118 lessons

The Foundation Math For Ai & ML: from arithmetic to attention

Learn the math behind AI from arithmetic up: numbers, algebra, vectors and matrices, calculus, probability and statistics, each shown as numbers moving and checked in Python, ending with a network you build and train from the formulas.

Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write