A spam filter answers yes or no. A web server counts how many requests arrive each second. A scale reports a weight with a small random error. All three are random variables (P1.D2), but they behave very differently: one has two values, one counts with no upper limit, and one takes any real value.
Luckily, a handful of recipes cover most cases. Each is a PMF or density with one or two adjustable numbers, and each fits a typical kind of quantity. Learn the recipes, and “what is the distribution of this?” often becomes a short checklist.
Recipes with knobs: distributions and parameters
A named distribution is a rule that gives a PMF (for a discrete variable) or a density (for a continuous one) with a few adjustable numbers called parameters. Think of a recipe with a few knobs. The knobs decide which member of the family you get: a fair coin and a coin that lands heads of the time are the same recipe with two settings of one knob.
- Parameters describe the distribution. They are fixed numbers, such as , , , and below.
- Values are what the random variable can take, such as , , or .
“ has the Bernoulli distribution with parameter ” is written . The symbol means “is distributed as”. Fitting a model to data (P1.D10) often means choosing the parameters that make the data most likely.
Each distribution below comes with its mean, the average value you see over many draws, and its variance, the average squared distance of a draw from the mean. The standard deviation is the square root of the variance, and it is in the same units as the values. P1.D4 shows how to compute the mean and variance in general. Here they are stated, and the gallery below checks them.
Bernoulli: one yes/no trial
A Bernoulli trial has two outcomes. Call them (“success”) and (“failure”). The word “success” is only a label: a spam email, a defective part or a click can all be the “success”. The distribution has one parameter, , the probability of :
One formula covers both: for . Check: gives , and gives .
- Mean . If , then of many draws are 1s, so their average is .
- Variance . For it is , so the standard deviation is . The variance is largest, , at (most uncertain), and it is at or , where the outcome is certain.
- CDF. A staircase (P1.D2): for , for and for .
Bernoulli variables are everywhere in ML: the label of a spam example, whether a neuron is kept or dropped by dropout (P4.17), and whether a coin lands heads (P1.D1). A fair coin is Bernoulli().
Binomial: count the successes in trials
Flip a coin with three times, and count the heads. What is the probability of exactly ? List the sequences with two heads: HHT, HTH and THH. If the flips do not affect each other (this is independence, P1.D5), each sequence has probability . There are such sequences, so .
The same two steps work for any and .
- Every particular sequence with successes and failures has probability , because the trials multiply.
- The number of such sequences is the number of ways to choose which of the trials are successes, (P1.D1).
So the binomial distribution, written , has
for .
For and the whole PMF is , , and for , and these add to . The binomial is the right model only under three conditions: a fixed number of trials, each trial a yes/no result with the same , and the trials independent. Dealing five cards from a deck and counting the hearts is not binomial: each card changes what is left in the deck, so the trials are not independent.
- Mean and variance . A binomial is a sum of independent Bernoulli variables, so these are times the Bernoulli mean and variance (P1.D4 covers sums of random variables, and P1.D5 defines independence).
- is exactly Bernoulli().
- Shape. For the bars are symmetric. For small the bars pile up near with a long tail to the right, and for near the pile is near with a tail to the left. For larger the shape becomes a smooth bell (see the Go-deeper box on the Gaussian approximation), and the spread relative to the mean shrinks: for , the standard deviation is of the mean at , at and at .
Worked example. Take and . Then . The mean is , the variance is and the standard deviation is . The probability of or fewer successes is . With and , , the number you met in P1.D1.
Categorical: one of classes
When there are more than two outcomes, say the class of a photo (cat, dog or bird), the categorical distribution gives each class a probability , with every and . So . The model in P1.D1 that said cat , dog , bird is a categorical distribution with . The parameters are the probabilities themselves, and because they add to , only of them can be chosen freely.
A draw is usually recorded as a one-hot vector: a vector of numbers with a at the drawn class and everywhere else. Class out of is . This is how classification labels enter a model (P3.A8).
- Two classes is Bernoulli: call the classes and , and plays the role of .
- No mean. The class names are labels, not quantities. “Dog” is not the average of “cat” and “bird”, so asking for the mean of the class number has no meaning. (If you give the classes numbers on purpose, such as star ratings, you can ask for that mean, but it is a choice you made.)
- Where the probabilities come from. A network produces raw scores called logits, and softmax turns them into probabilities (P3.A8). The scores become , which add to . The gallery below does exactly this.
- Many draws. If you draw times independently and count how often each class appears, the vector of counts follows the multinomial distribution. With probabilities and , the counts have probability . The binomial is the multinomial with . This is only a preview.
Uniform: every value is equally likely
The discrete uniform distribution on the whole numbers gives each of the values the probability . A fair die is the case , : each face has probability , the mean is , and the variance is .
The continuous uniform distribution on , written , has a flat density (P1.D2):
The height makes the area of the rectangle, height times width, equal to . The CDF is the ramp on , so for : the probability is the length of the part you ask about, divided by the total length. The mean is and the variance is .
For the density is , the mean is , the variance is , and . For the density is , taller than : a density is a probability per unit length, and the interval is short. Whether the end points are included does not matter, because a single point has probability .
In ML, the random number generator of a computer produces numbers that behave like draws from , and other random draws are built from them (P1.D2, P1.D9). Random search for hyperparameters draws each setting uniformly from a range (P4.23).
Gaussian: the bell curve
The Gaussian (or normal) distribution is a continuous distribution with two parameters, the mean (the centre) and the standard deviation (the width, with ). Its variance is , and we write . The density is
- Shape. The curve is symmetric about , which is also its highest point. Changing slides the curve left or right. Changing stretches it: a larger gives a wider, flatter bell.
- The constant. The factor makes the total area . For the area under is (P1.C9), and dividing by it gives the peak height for the standard Gaussian .
- The height can exceed 1. The peak height is , so for it is . This is fine, for the same reason as for the uniform density: the area is still , because the curve is very narrow. A density is not a probability.
Standardizing. If , the number counts how many standard deviations is above the mean, and has the standard Gaussian distribution . So one table or one function, for the standard Gaussian, answers every question about every Gaussian. If exam scores are , a score of has .
The CDF. The CDF of the standard Gaussian is written . As P1.C9 and P1.D2 noted, the area under the bell curve has no formula made from the usual elementary functions, so is computed numerically through the error function: . In Python, math.erf does it. The values to remember are and . For any Gaussian, . For the exam scores, .
The 68–95–99.7 rule. The probability of landing within , or standard deviations of the mean is the same for every Gaussian:
- within : , so the rest, , is split evenly between the two tails
- within :
- within : , so the chance of being farther than away is , about in
The rounded numbers , and percent are easy to remember, but the exact ones matter when it counts: is reached at standard deviations, not (which gives ).
Tails. The curve falls very fast: the chance of landing more than above the mean is and more than above is about . Yet it never reaches , so any real number has a positive density, and a Gaussian model for a quantity that cannot be negative (a price, a height) puts a little probability on impossible values. Real data also often show more extreme values than a Gaussian predicts, so a Gaussian is an assumption to check, not a fact.
Why the Gaussian is everywhere. The sum or average of many small independent effects tends to look Gaussian whatever the shape of the individual effects, as long as their variance is finite and no single effect dominates (the central limit theorem, P1.D8). Extremely heavy-tailed effects, such as those of the Cauchy distribution, do not follow this rule. Measurement error is a typical case. The multivariate version of the Gaussian, with an ellipse for its shape, is the subject of P1.D7.
Poisson: counting events at a steady rate
Suppose a server receives on average requests per second. In one second it may see , , or more, and there is no upper limit. The Poisson distribution counts events in a fixed interval of time or space. It has one parameter, , the average number of events per interval:
for
For the probabilities of are , , , and . The probabilities add to because (the series for ), which cancels the factor .
- Mean and variance are both . This is a signature of the Poisson. If counts have a variance far larger than their mean, the Poisson is a poor model for them.
- When to use it. The events must be independent of each other, arrive at a steady average rate, and not come in clumps. Requests from many unrelated users and typos in a long text are typical.
- A limit of the binomial. Cut the interval into tiny slots. If each slot has a chance of containing one event, the number of events is Binomial(), with mean . As grows the slots shrink, and the binomial approaches the Poisson. With and , the binomial gives for , for , for , and the Poisson gives . The variance approaches too.
- Waiting times. If events arrive like this, the time to wait for the next one has the exponential distribution with density for and mean . For it is the of P1.C9 and P1.D2. With per hour the mean wait is minutes, and the probability of no event in half an hour is , which is also for a Poisson with .
Go deeper Why the binomial turns into the Poisson
Write the binomial probability with and rearrange:
Hold and fixed and let . The fraction is a product of factors, each close to , so it goes to . The last factor goes to too. The factor goes to , the same limit as in compound interest (P1.A2). What is left is , the Poisson PMF.
Go deeper Approximating a binomial by a Gaussian
For large with not too close to or , the binomial bars follow a Gaussian curve with the same mean and variance . For and the Gaussian has and . At the exact binomial value is , and the Gaussian density gives . The largest gap between the bars and the curve over all is .
A binomial value is a whole number but the Gaussian is continuous, so for a sum of bars it helps to treat each bar as the interval from to . This is called the continuity correction. To find , the exact value is . The Gaussian with the correction gives , and without it . Rules of thumb for when the approximation is good differ between books. A common one asks that and are both at least about . This is the first sign of the central limit theorem (P1.D8).
The gallery
Pick a distribution and move its sliders. The chart shows the probability of every value (or the density), the dashed line marks the mean, and the dark bracket marks the mean plus and minus one standard deviation. The readouts below the chart give the mean, the variance and a probability you choose.
Things to try with the gallery:
- Choose Binomial with , and . The readouts give , mean , variance and . Slide to and the bars become symmetric around . Slide to and then to : all the probability sits on one bar and the variance is .
- Press Rare events (Binomial() with the Poisson overlay). The dots sit almost on top of the bars, and the largest gap is . Then set and with the Poisson overlay: the gap grows to , because is not small.
- Press Large n (Binomial() with the Gaussian overlay). The curve follows the tops of the bars, with a largest gap of .
- Choose Gaussian and press , , . The shaded probability is , , . Change and and watch that these three numbers do not change.
- Press Narrow Gaussian (). The curve is taller than : the highest density is , and the area is still .
- Choose Poisson and set . The bars at and are both , and the mean and variance are both . Turn on the Binomial overlay, which starts at , and raise to to watch the gap shrink.
- Choose Categorical with the logits . The probabilities are , , . Raise one logit and the other two probabilities fall, because the total stays .
- Choose Uniform (any real number) with and , and shade . The probability is .
Intuition
Think of each distribution as a shape template that you adjust with its knobs. Bernoulli is two bars. Binomial is a hill of bars centred on . Categorical is bars that must share one unit of probability. Uniform is a flat shelf. Gaussian is the smooth bell. Poisson is a hill that starts at with a tail to the right.
The analogies break where the knobs interact. In the binomial, moves both the centre and the skew. In the Gaussian, and move the centre and the width separately, which is one reason it is so convenient.
Math
Mean and variance of each distribution (P1.D4 shows how to get them):
- Bernoulli(): mean , variance .
- Binomial(): mean , variance .
- Discrete uniform on : mean , variance .
- Uniform(): mean , variance .
- Gaussian : mean , variance .
- Poisson(): mean , variance .
- Exponential(): mean .
- Categorical: no mean for class names.
CDFs: Bernoulli is a staircase, the uniform is a ramp , the Gaussian is , and the binomial and Poisson CDFs are sums of their PMFs, .
Code
Plain Python is enough for all the PMFs, because math.comb and math.erf exist.
from math import comb, erf, exp, factorial, sqrt
binom = lambda n, p, k: comb(n, k) * p**k * (1 - p)**(n - k)
poisson = lambda lam, k: exp(-lam) * lam**k / factorial(k)
phi = lambda z: 0.5 * (1 + erf(z / sqrt(2)))
print(binom(10, 0.3, 3), poisson(3, 2), phi(1)) # 0.2668..., 0.2240..., 0.8413...Choosing a distribution
To choose, look at the quantity, not at a table of distributions.
- Two outcomes (yes/no, 0/1): Bernoulli.
- Number of successes among trials, with the same each time and independent trials: binomial.
- One of classes: categorical. A next token out of a vocabulary is a categorical draw with a very large .
- A count with no fixed upper limit, from independent events arriving at a steady average rate: Poisson.
- A real number with noise around a centre: Gaussian.
- A real number in a known range with no preference: uniform.
Every one of these is an assumption about the world, and the checks are as important as the choice. A binomial needs independent trials with the same . A Poisson needs a variance close to its mean. A Gaussian needs a quantity that is not strongly skewed or full of extreme values. When the check fails, other distributions exist, and the same ideas (a PMF or density, a few parameters) carry over.
Where these appear in a loss function
Each choice of distribution leads to a loss function, which is the negative log of the probability the model gave to what really happened. This section only previews it. P1.D10 develops the idea and P3.A2, P3.A7 and P3.A8 use it.
- Bernoulli and binary cross-entropy. A model gives for an email being spam, a Bernoulli parameter. If the email is spam (), the model gave the truth probability , and the loss is . If it is not spam (), the truth got , and the loss is . In one formula, . For three examples with labels and predictions the average loss is (P3.A7).
- Categorical and cross-entropy. A classifier gives and the true class is the first. The loss is . Only the probability of the true class matters. Next-token prediction in a language model is the same, with the vocabulary as the classes (P3.A8, P10.A1).
- Gaussian and mean squared error. Suppose the model says the target is . The negative log of the density is . With , and it is : half the squared error plus a constant that does not depend on the prediction. So choosing the predictions that minimize the total of these losses is the same as minimizing the total squared error (P3.A2).
- Gaussian and uniform initial weights. Training starts from random weights, drawn from a Gaussian or a uniform distribution whose width depends on the layer size (P4.12).
- Poisson for counts. Counts such as clicks per day can be modelled with a Poisson whose is predicted by the model. Because must be positive, the model output is usually passed through an exponential.
Try it: PMFs, simulations and the Poisson limit
The first cell computes everything exactly with math.comb and math.erf, so every run prints the same numbers. The second cell simulates with a fixed seed and compares the results with the theory. Predict the Poisson numbers before you run it.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Challenge: add the Poisson check for another rate, , and find the smallest for which the largest gap to the binomial falls below .
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Challenge: change the seed and rerun. Which numbers move, and by how much? How many draws would you need before the variance matches the theory to two decimals?
With seed 11 the second cell printed a mean of and a variance of for the binomial, and the Gaussian shares inside , and standard deviations were , and . Other seeds give slightly different numbers.
Common mistakes
Check your understanding
You flip a fair coin times and count the heads. Which distribution fits, and with which parameters?
There are independent yes/no trials with the same , and we count the successes, which is the binomial setting. A Bernoulli variable describes one flip only. A Poisson with has the same mean, but it has no upper limit and its variance is , while this count never exceeds and has variance . A categorical variable describes one draw among classes, not a count.
For , what is the variance?
The variance is . The value is the mean . The value is the Bernoulli variance , which has not been multiplied by . The value is , the mean number of failures.
Exam scores are . What is the -score of a score of ?
The score is above the mean, and one standard deviation is , so . The value is the distance in score points and has not been divided by . The value divides by the variance instead of the standard deviation. The value divides by , which is not the standard deviation.
A Gaussian with has its peak density at . What does that tell you?
A density gives probability per unit of . When is small, the curve must be tall to keep the area at . The statement that a probability cannot exceed is true, but the height of a density is not a probability. The peak of a Gaussian is , which exceeds for below , so the distribution is Gaussian. A single point has probability , and the area, not the height, is what must equal .
Calls arrive at an average rate of per minute, as a Poisson process. What is the probability of no calls in a given minute?
The Poisson PMF at is . The value is the probability of at least one call. The value would need a guess of equal chances with no basis in the rate. The value is the probability of exactly one call, .
Exercises
- A Bernoulli variable has . Find its mean, variance and standard deviation.
Show answer
The mean is , the variance is , and the standard deviation is . - A multiple-choice quiz has questions and a student guesses each with success probability , independently. Find the probability of exactly right answers and of at least one right answer.
Show answer
. At least one: . - What is the probability of exactly heads in fair flips, and of exactly sixes in rolls of a fair die?
Show answer
. For the die, . - A categorical distribution has probabilities . If three independent draws are made, what is the probability of the sequence class 1, class 1, class 3? What is the one-hot vector of class 3?
Show answer
The draws are independent, so the probability is . The one-hot vector of class 3 is . - For , find the density, the mean, the variance and .
Show answer
The density is . The mean is , and the variance is . . - Gaussian weights of apples are grams. Find the probability that a weight is between and grams, between and grams, and above grams.
Show answer
The interval to is , so . The interval to is , so . Above is , and half of the remaining lies in the upper tail: . - A Gaussian has and . Find the -score of , and the value with .
Show answer
. For , . - Let . Find , and .
Show answer
. . . - Each of items is faulty with probability , independently. Estimate the probability of exactly faults with a Poisson, and compare with the exact binomial value.
Show answer
Take . The Poisson gives . The exact binomial value is . They differ by only about because is large and small. - A server logs on average requests per minute, but the variance of the counts is . Is a Poisson model good?
Show answer
No. A Poisson has variance equal to its mean, so it would give variance . A variance four times the mean means the counts are much more spread out, for example because the requests arrive in bursts. - A model gives of being spam. Find the binary cross-entropy loss when the email is spam and when it is not.
Show answer
Spam (): . Not spam (): . Being confidently wrong is penalized much more heavily. - A Gaussian has . What is its peak density, and why is it not a problem that it exceeds ?
Show answer
. A density is probability per unit of , and the curve is only a few tenths wide, so its area is still .
Next: P1.D4 shows how the mean and variance stated here are computed, and why the mean of a sum is the sum of the means. P1.D5 defines independence and studies joint and conditional distributions. P1.D7 extends the Gaussian to several variables, P1.D8 explains why Gaussians are everywhere, and P1.D10 turns “which parameters fit my data?” into maximum likelihood.