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?
0.375
0.5
0.25
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)
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)?
8
12
6
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−μ
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?
−2
16
2
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:
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.
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?
At 0 heads, falling all the way from the start
At 40 heads, climbing all the way to the end
At 20 heads, n × p, rising and falling in a bell
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 = 0print(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:
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?
Kept numbers are divided by 1 − 0.5, so the average stays 1
Dropout adds 1 to every number it keeps
The dropped numbers' values move to their neighbors
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=np(1−p)
In plain words: an accuracy measured on n questions wobbles by about this much from test to test.
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?
It stays the same
It shrinks to a tenth
It grows
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.
√(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.
31Formulas with fractions: clear them firstFreeClearing denominators, cross-multiplying, a letter in the bottom, and reciprocal formulas like 1/R = 1/R₁ + 1/R₂.35 min
37Inverse functions, lines and scalingFreeUndoing a function by making x the subject, domains that allow it, line forms, and unscaling predictions.40 min
38Sequences and sums: find n, a, d and rFreeEvery letter of the arithmetic and geometric formulas as the subject, and an average's window from its decay.40 min
40Review: rearrange anything (algebra)FreeBroken rearrangements to fix, mixed practice from the whole algebra block, a strategy chart, and its formula sheet.35 min
41Coordinates and distanceFreePoints as (x, y), Pythagoras, distance in any number of coordinates, and nearest neighbors.42 min
42Angles, degrees and radiansFreeMeasuring a turn, converting units, arcs, and the angle between two arrows.36 min
43Sine and cosineFreeAcross and up: right triangles, the unit circle, and directions and rotations.42 min
44Waves: height, speed and shiftFreeAmplitude, period and phase, sampling a wave, and position codes in transformers.37 min
68Vector equations: rearranging with arrowsFreeSolving for a vector or a scale, recovering a gradient from two weight snapshots, and an angle from a dot product.40 min
87Counting: choices, orders and groupsFreeThe counting principle, factorials, ordered picks and groups, and why attention's cost grows with the square of the length.43 min
88Probability: from counts to chancesFreeEqually likely outcomes, the complement, distributions, seeded simulation, and a next-word model.43 min
89Combining events: and, or, independentFreeThe or rule, independence, probability trees, drawing with and without replacement, and chains of steps.42 min
100Maximum likelihoodFreeLikelihoods as products, log-likelihoods as sums, grid search, underflow, and the negative log-likelihood loss.45 min
101Linear regression: the best lineFreeResiduals, least squares by formula, three roads to one line, the matrix form, and train versus test error.45 min
109One neuron, start to finishFreeWeighted sum, activation, loss, slopes and update, by hand and in code, and what one straight line can and can't split.45 min
111Training a small networkFreeThe backward pass in matrix form, gradient checks, a full training loop, and reading loss curves.45 min
112The same network in PyTorchFreenn.Sequential with the NumPy weights loaded, the same loss and slopes, then SGD and mini-batches.45 min
113Attention as matrix mathFreeScaled dot-product scores, the causal mask, a row-by-row softmax, and blending value vectors.45 min
114Residual connections and layer normFreeAdding the input back and why its slope keeps learning alive, layer norm by hand, and add and norm.40 min
115A transformer block, start to finishFreeA sentence through embeddings, attention, add and norm, a small network and next-word scores, every shape named.45 min
117Final test: transpose any formulaFreeSlips to fix from every topic, mixed practice of every kind of rearranging, the strategy chart and the full sheet.45 min
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.
See the course →
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