Index Ai Academy
Foundation · Probability

Bernoulli, binomial, uniform and normal

Yes-or-no trials, counts of yeses, the 68-95-99.7 rule, z-scores, and an accuracy's error bar.

About 45 minutes · Free lesson

What it covers6

Why it matters

A few distributions turn up so often that they have names, and knowing them saves rebuilding a table each time. A single yes-or-no trial is a Bernoulli; the number of yeses in many such trials is binomial; values that are all equally likely are uniform; and sums of many small effects pile up into the bell-shaped normal. Each has a job in ML. Network weights start as small normal numbers; dropout switches each unit off with a Bernoulli coin flip; and the number of test questions a model gets right is binomial, which tells you how much its accuracy would wobble on a different test. This lesson meets all four, simulates them, and puts an error bar on an accuracy.

What you'll be able to do

  • Recognize four distributions: one yes-or-no trial, the count of yeses in n trials, equally likely values, and the bell curve
  • Use the binomial's mean np and variance np(1 − p), the 68–95–99.7 rule, and the z-score
  • Simulate each with rng.random, rng.binomial and rng.normal, stretch and shift a standard normal, and plot a binomial turning into a bell
  • Put an error bar on a model's accuracy, and start a layer's weights, and dropout, with torch.randn, nn.init.normal_ and nn.Dropout
Quick check
Have a guess before you start. A fair coin is tossed 4 times. What is the chance of exactly 2 heads?
  1. 0.375
  2. 0.5
  3. 0.25
  4. 0.0625
Show the answer

0.375

There are C(4, 2) = 6 ways to place 2 heads, each with chance 0.5⁴ = 0.0625: 6 × 0.0625 = 0.375.

The math: four shapes

Purpose. Four shapes that keep appearing.

  • Bernoulli(p): one trial, 1 ("yes") with chance p and 0 with chance 1 − p. A coin, a correct answer, a unit kept by dropout. Mean p.
  • Binomial(n, p): the number of yeses in n independent Bernoulli trials. Its chance of exactly k yeses:
P(k)=C(n,k) pk(1−p)n−k,mean np,variance np(1−p)P(k) = C(n, k)\, p^k (1-p)^{n-k}, \qquad \text{mean } np, \quad \text{variance } np(1-p)

In plain words: count the ways to place k yeses (lesson 87), times the chance of any one such sequence.

For 4 coin tosses: 0.0625, 0.25, 0.375, 0.25, 0.0625 for 0 to 4 heads, mean 4 × 0.5 = 2.

Quick check
From lesson 87: what is C(4, 2)?
  1. 8
  2. 12
  3. 6
  4. 4
Show the answer

6

4 × 3 ÷ 2 = 6: the ways to choose which 2 of 4 tosses are heads.

The picture. Step through the binomial for 4 fair tosses: for each count of heads, the ways to place them, times the chance of one sequence. The picture draws each chance as a bar, one for each count from 0 to 4, in the order the steps find them. Watch which bar ends up tallest, and why.

Try it now

Then set the chance each time to 0.8 and press Use these numbers, like a model that gets 80% of questions right: the bars lean toward 4.

Uniform. Every value in a range equally likely: a fair die, or a random number between 0 and 1, where the density is a flat line of height 1.

Normal. The bell curve, set by its mean μ and standard deviation σ. Sums of many small, independent effects come out roughly normal (lesson 98 says why), which is why heights, measurement errors and much else look like it. Its shares follow the 68–95–99.7 rule: about 68% of values fall within 1σ of the mean, 95% within 2σ, and 99.7% within 3σ. A z-score says how many σ a value is from the mean:

z=x−μσz = \frac{x - \mu}{\sigma}

In plain words: subtract the mean, then measure in standard deviations.

Quick check
Heights have mean 170 cm and σ = 8 cm. What is the z-score of 186 cm?
  1. −2
  2. 16
  3. 2
  4. 1
Show the answer

2

(186 − 170) ÷ 8 = 2: two standard deviations above the mean, taller than about 97.5% of people.

In your own words
In your own words: what does a z-score let you compare that raw values can't?

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

In Python: simulate each one

Purpose. Draw from each distribution, and check its mean and spread.

import numpy as np

rng = np.random.default_rng(0)
x = rng.normal(size=100000)
print(round(float(np.mean(np.abs(x) < 1)), 3), round(float(np.mean(np.abs(x) < 2)), 3))
y = 3 + 2 * rng.normal(size=10000)
print(round(float(y.mean()), 2), round(float(y.std()), 2))
b = rng.binomial(10, 0.3, size=10000)
print(round(float(b.mean()), 2), round(float(b.var()), 2))
print(round(float(rng.random(10000).mean()), 2))
It runs right here in your browser, with nothing to install.

rng.normal draws standard normals: 68.4% and 95.5% land within 1σ and 2σ. Stretch and shift: 3 + 2 × z comes out with mean 2.99 and σ 2.0, about the 3 and 2 it was built with, the way any normal is made from a standard one. rng.binomial(10, 0.3) gives mean 3.0 and variance 2.11, close to the 3 and 2.1 that np and np(1 − p) predict. rng.random is uniform on [0, 1), with mean 0.5.

Code flow. Here is one draw of five from each, a line at a time. Step through and watch each line fill a row of boxes: u uniform numbers, bern a Bernoulli made from them (a 1 where u is under 0.3), binom five counts of yeses in 10 trials, z standard normals, and x those normals stretched and shifted.

Areas without tables. The share of a normal to the left of a value is its cdf; the value with a given share to its left is its ppf. Statistics libraries provide both (norm.cdf and norm.ppf in SciPy); the cdf can also be built from math.erf, a function in Python's standard library:

import math

def cdf(z):
    return 0.5 * (1 + math.erf(z / math.sqrt(2)))

print(round(cdf(1) - cdf(-1), 4), round(cdf(2) - cdf(-2), 4), round(1 - cdf(1.25), 4))

0.6827 and 0.9545 are the exact 68% and 95%. A named mistake: skipping the sketch. Before computing, sketch the bell and shade the area you want: left of x, right of x, or between two values. 1 − cdf(1.25) = 0.1056 is the area to the right, which a quick sketch tells you to expect is small.

Quick check
What does this print?
import math

def cdf(z):
    return 0.5 * (1 + math.erf(z / math.sqrt(2)))

print(round(cdf(0), 2), round(cdf(3) - cdf(-3), 3))
  1. 0 0.997
  2. 0.5 0.997
  3. 1 0.95
  4. 0.5 0.68
Show the answer

0.5 0.997

Half the bell lies left of the mean, and 99.7% lies within 3σ.

Worked example

Worked example: each distribution, checked

Simulate a Bernoulli, a binomial, a uniform and a normal, and compare each sample's mean and spread with the formulas.

import numpy as np

rng = np.random.default_rng(12)
bern = (rng.random(20000) < 0.3).astype(int)
binom = rng.binomial(20, 0.25, size=20000)
unif = rng.random(20000) * 10
norm = 50 + 5 * rng.normal(size=20000)
print(round(float(bern.mean()), 2), 0.3)
print(round(float(binom.mean()), 2), 20 * 0.25, round(float(binom.var()), 2), 20 * 0.25 * 0.75)
print(round(float(unif.mean()), 2), 5.0)
print(round(float(norm.mean()), 1), round(float(norm.std()), 1))
In the lesson you can change this and run it.

rng.random(n) < 0.3 is True 30% of the time: a Bernoulli, turned into 1s and 0s by .astype(int). The binomial's mean, 5.0, and variance, 3.69, sit close to the formulas' 5 and 3.75. Uniform numbers stretched to [0, 10) average 4.97, close to 5. The stretched and shifted normal has mean 50.0 and σ 5.0. Each formula is confirmed by 20,000 samples, to within the wobble of a sample.

A binomial turning into a bell. Count heads in 40 fair tosses, 100,000 times over, and plot what share of the runs gave each count, from 0 to 40. np.bincount counts the runs that gave each number of heads, as in lesson 91:

import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(0)
heads = rng.binomial(40, 0.5, size=100000)
shares = np.bincount(heads, minlength=41) / 100000
plt.plot(range(41), shares)
plt.xlabel("heads in 40 fair tosses")
plt.ylabel("share of 100,000 runs")
plt.show()

Each run's count is a sum of 40 small yes-or-no effects, and the counts pile up into the bell of the normal. That's why the normal turns up wherever many small effects add.

Quick check
Read the plot. Where is the curve highest, and what shape does it make?
  1. At 0 heads, falling all the way from the start
  2. At 40 heads, climbing all the way to the end
  3. At 20 heads, n × p, rising and falling in a bell
  4. Nowhere: it's flat, as every count is as likely
Show the answer

At 20 heads, n × p, rising and falling in a bell

The shares peak at 20 = 40 × 0.5, the binomial's mean, and fall away evenly on both sides: the normal's bell shape. Counts far from 20, like 5 or 35, almost never happen.

Drill

Stretch and shift a standard normal

With seed 21, make 50,000 samples of a normal with mean 100 and σ 15 by stretching and shifting standard normals. Set m and s to their mean and standard deviation, rounded to 0 places, and share to the share within 1σ of the mean, rounded to 2 places.

import numpy as np

rng = np.random.default_rng(21)
z = rng.normal(size=50000)
x = z
m = 0
s = 0
share = 0
print(m, s, share)
In the lesson, your code is checked as you write it.
In your own words
Why can every normal distribution be made from the standard one?

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

In AI and ML: each shape has a job

Purpose. Initialization, dropout and accuracy all use these distributions.

Weights start normal. A network's weights begin as small random normal numbers, scaled so that signals neither explode nor vanish as they pass through the layers. Here are the 2,048 weights of a layer with 64 inputs and 32 outputs, one row per output as PyTorch stores them (lesson 55), drawn with σ = 0.1. np.histogram counts how many land in each of 8 bins, each 0.1 wide, from −0.4 to 0.4, and returns the counts with the bins' edges:

import numpy as np

rng = np.random.default_rng(2)
W = rng.normal(0, 0.1, size=(32, 64))
counts, edges = np.histogram(W, bins=8, range=(-0.4, 0.4))
print(W.shape, round(float(W.std()), 2))
print(counts.tolist())
print(round(float(np.mean(np.abs(W) < 0.1)), 3))

The weights come out with σ 0.1, as drawn, and a share of 0.685 lies within 0.1 of 0. The picture draws the counts.

In PyTorch. Three lines from real models. torch.randn draws standard normals, like rng.normal, and 0.1 times them stretches them to σ 0.1. nn.init.normal_ fills a layer's own weights the same way, in place (the _ at the end). nn.Dropout(0.5) switches each number off with a Bernoulli coin flip during training, so the network can't lean on any one unit.

import torch
import torch.nn as nn

torch.manual_seed(0)
W = 0.1 * torch.randn(32, 64)
print(W.shape, round(W.std().item(), 2))
layer = nn.Linear(64, 32)
nn.init.normal_(layer.weight, mean=0.0, std=0.1)
print(layer.weight.shape, round(layer.weight.std().item(), 2))
drop = nn.Dropout(0.5)
out = drop(torch.ones(10000))
print(out.min().item(), out.max().item(), round((out == 0).float().mean().item(), 1))

Both weight lines print torch.Size([32, 64]), PyTorch's way of writing the shape (32, 64), and σ 0.1, as the NumPy cell did. Dropout turned about half (0.5) of 10,000 ones into 0.0 and the rest into 2.0. After training, drop.eval() switches dropout off.

Quick check
nn.Dropout(0.5) turned 10,000 ones into 0.0s and 2.0s. Why are the kept ones 2.0, not 1.0?
  1. Kept numbers are divided by 1 − 0.5, so the average stays 1
  2. Dropout adds 1 to every number it keeps
  3. The dropped numbers' values move to their neighbors
  4. It's random: another run could keep them at 1.0
Show the answer

Kept numbers are divided by 1 − 0.5, so the average stays 1

Half the numbers become 0, so the survivors are doubled (1 ÷ 0.5 = 2) to keep the average where it was: 0.5 × 0 + 0.5 × 2 = 1. The next layer then sees inputs of the same size in training and after it.

Accuracy has an error bar. If a model answers each test question right with chance p, its number right out of n is binomial, and its accuracy (that number over n) has standard deviation

σacc=p(1−p)n\sigma_{\text{acc}} = \sqrt{\frac{p(1-p)}{n}}

In plain words: an accuracy measured on n questions wobbles by about this much from test to test.

n, p = 100, 0.87
sd = (p * (1 - p) / n) ** 0.5
print(round(sd, 4), round(p - 2 * sd, 3), round(p + 2 * sd, 3))

87 right of 100 has a standard deviation of about 0.034, so a rough 95% range is 0.80 to 0.94: a second model scoring 0.85 on the same test isn't clearly worse.

Quick check
The same model is tested on 10,000 questions instead of 100. What happens to its accuracy's standard deviation?
  1. It stays the same
  2. It shrinks to a tenth
  3. It grows
  4. It shrinks to a hundredth
Show the answer

It shrinks to a tenth

σ is √(p(1 − p)/n); n is 100 times bigger, and √100 = 10, so σ is a tenth as big.

The error bar, from the binomial. The number right on n questions is binomial, with variance np(1 − p). The accuracy divides that count by n, which divides the variance by n², leaving p(1 − p)/n, and its square root is the error bar σ. Because of that square root, a hundred times the questions buys only a tenth of the error bar, which is why benchmark sizes run to thousands, and why a gain of a fraction of a point on a small test says little. Predict both numbers for an accuracy near 0.9.

Quick check
What does this print?
p = 0.9
print(round((p * (1 - p) / 100) ** 0.5, 4), round((p * (1 - p) / 10000) ** 0.5, 4))
  1. 0.03 0.0003
  2. 0.3 0.03
  3. 0.09 0.0009
  4. 0.03 0.003
Show the answer

0.03 0.003

√(0.09 ÷ 100) = 0.03 and √(0.09 ÷ 10,000) = 0.003: 100 times the questions, a tenth of the spread.

Drill

Error bars on two models

Model A got 87 of 100 right; model B got 870 of 1,000. Set sd_a and sd_b to their accuracy standard deviations, rounded to 4 places, and ranges to their rough 95% ranges (accuracy ± 2σ), each end rounded to 3 places, as a list of two tuples.

sd_a = 0
sd_b = 0
ranges = []
print(sd_a, sd_b, ranges)
In the lesson, your code is checked as you write it.
In your own words
Two models score 0.87 and 0.85 on a 100-question test. Can you say the first is better?

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

Goes deeper in

Practice what you just read

  • 7 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 9 review cards for spaced repetition

Try a quiz question

Which distribution counts the yeses in 50 independent yes-or-no trials?

  1. Binomial
  2. Bernoulli
  3. Uniform
  4. Normal

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