Discrete Distributions

Flip a coin that lands heads 30% of the time. Ask how many heads come up in 10 flips, and the answers pile up around 3. Ask how many tails come before the first head, and the same coin gives a new shape: a mean of 2.33 and a long tail.

Pick a question and press play. Watch the pile of answers (blue) settle onto the formula's bars (warm), then drag p. Then we build, piece by piece, nine distributions from one coin, one count and one urn.

You need what a probability is and basic Python. We build the rest from zero.

Ask one coin four questions

0.30

Simulated in your browser with a fixed seed, illustrative. The warm bars are the exact distribution for the chosen p; the blue bars are the share of rounds that gave each answer.

Chapter 0

Count It, Then Add It Up

List every outcome, give each one a probability, and answer "at most" and "at least" by adding bars

A spam filter says yes or no. A language model picks one word from 50,000. A lidar counts the obstacles in one scan. Each answer comes from a list you can write down: 0, 1, 2, and so on. You cannot see 2.7 obstacles. Outcomes like these are discrete.

A random variable, written X, is a number that comes out of a random experiment. A distribution says how likely each value of X is. For a discrete X it is the probability mass function, or PMF: one bar for each value k, of height P(X = k). Every bar sits between 0 and 1, and the bars add up to exactly 1.

Roll two dice and add them. The sum runs from 2 to 12. Of the 36 equally likely pairs, six give 7, so P(X = 7) = 6/36. Questions like "at most 4" add bars from the left. That running total has its own name.

Call the chance of each value j its bar, p(j). The cumulative distribution function, or CDF, is the total of the bars up to and including k:

Say it aloud

F of k equals the sum, over every j up to k, of p of j.

F(k)
F of k the CDF: the chance that X is k or less. It climbs from 0 to 1 in steps.
Σj ≤ k
the sum over j up to k add one term for each value j from the smallest one up to k.
p(j)
p of j the PMF bar at j: the chance that X equals j exactly.
In plain words

Start at the left. Add the bar p(j) of each value j until you reach k. The total is F(k). For "at least k", take everything that is not "at most k minus 1": 1 minus F(k minus 1).

With numbers

Two dice: p(2) = 1/36, p(3) = 2/36, p(4) = 3/36. So F(4) = 6/36 = 0.167. At least 10 is 1 − F(9) = 1 − 30/36 = 6/36 = 0.167.

Add the bars

Warm bars are the PMF of the sum of two dice; the line above is the CDF. Drag k and pick a question. The lit bars are the ones you add.

4

Exact counts of the 36 pairs of two fair dice. No simulation.

Failure: "at least" off by one.

Symptom: the chance of a sum of at least 10 comes out as 3/36, half the truth.

Measure: add the bars at 10, 11 and 12 by hand: 3 + 2 + 1 = 6 of 36.

Fix: for a discrete X, "at least k" includes k, so it is 1 − F(k − 1), not 1 − F(k).

Each distribution in this lesson answers one counting question. Find the question, and you have the distribution.

  1. Bernoulli: one trial, yes or no, and the number p.
  2. Binomial: the number of heads in n flips (the hero's second question).
  3. Poisson: rare events in a window, as the limit of many tiny chances.
  4. Geometric: the tails before the first head, and why the coin has no memory.
  5. Neg. binomial: the tails before the r-th head, and counts that vary more than Poisson allows.
  6. Hypergeometric: draws from an urn without putting them back.
  7. Categorical: one pick from K options, softmax, and the uniform.
  8. Multinomial: counts in K categories at once, and why they pull against each other.
  9. Showcase: name the distribution behind five real-looking data sets.
  10. The field guide: every formula, convention and link in one place.
X is the number of errors in a log file. F(4) = 0.90. What is P(X ≥ 5)?

Chapter 1

One Trial, One Number

Code yes as 1 and no as 0, and one number p fixes the mean and the spread

A spam filter reads one email. The email is spam or it is not. Code spam as 1 and not spam as 0. A random variable with only the values 0 and 1 is a Bernoulli variable, named after Jacob Bernoulli. We call the outcome 1 a hit (textbooks say "success").

One number describes it. Call the chance of a hit p. Then the chance of a 0 is 1 − p. One formula covers both cases:

Say it aloud

P of X equals k equals p to the k, times one minus p to the one minus k.

P(X = k)
P of X equals k the chance that the trial gives the value k.
p
p the chance of a hit, between 0 and 1.
k
k the outcome: 1 for a hit, 0 for a miss. As a power, it switches a factor on (k = 1) or off (k = 0).
In plain words

If k is 1, the second factor has power 0 and becomes 1, so the answer is p. If k is 0, the first factor becomes 1, so the answer is 1 minus p.

With numbers

With made-up numbers: a filter gives p = 0.85 for one email. P(X = 1) = 0.851 × 0.150 = 0.85. P(X = 0) = 0.850 × 0.151 = 0.15.

The expected value E[X] is the average of X over many tries: each value times its chance. The variance Var(X) is the average squared distance from that mean. Both follow in three lines, because 0 squared is 0 and 1 squared is 1:

E[X] = 0 · (1 − p) + 1 · p = p E[X²] = 0² · (1 − p) + 1² · p = p Var(X) = E[X²] − (E[X])² = p − p² = p(1 − p)

Turn the one knob

Left: the two bars. Right: the variance p(1 − p) with your p marked. Drag p, then flip 100 times and count the hits.

0.85

Illustrative flips from a seeded generator. The bars and the curve are exact.

A filter at p = 0.85 has variance 0.85 × 0.15 = 0.1275. At p = 0.99 the variance is 0.0099. The spread is largest, 0.25, at p = 0.5, where the outcome is hardest to guess. A model's binary cross-entropy on one example is minus the log of the chance it gave the true label. For a spam email at p = 0.85 it is −ln 0.85 = 0.163.

Failure: p names the other outcome.

Symptom: a network set to "dropout 0.9" to keep 90% of its units keeps only 10%, and stops learning.

Measure: count the zeros in one dropout mask: 90% of the entries are 0.

Fix: check which outcome p belongs to. The original dropout paper uses p for the chance to keep a unit; PyTorch's nn.Dropout(p) uses p for the chance to zero it.

A Bernoulli variable has p = 0.3. What is its variance?

Chapter 2

Count the Heads in n Tries

Count the orderings, multiply by the chance of one of them, and get the binomial

Show a new page to 200 visitors. Each one converts or leaves. How many convert? Run the same Bernoulli trial n times, with the same p each time, and with no trial affecting another. The number of hits X has a binomial distribution, written Bin(n, p).

Take n = 10 and ask for exactly 3 hits. One ordering, hit hit hit then seven misses, has chance p3(1 − p)7. Every ordering with 3 hits has that same chance. So count the orderings. The binomial coefficient C(n, k), said "n choose k", counts the ways to pick which k trials are hits. It equals n! / (k! (n − k)!), where n! is 1 × 2 × … × n.

Say it aloud

P of X equals k equals n choose k, times p to the k, times one minus p to the n minus k.

P(X = k)
P of X equals k the chance of exactly k hits in n trials, for k from 0 to n.
C(n, k)
n choose k the number of orderings with k hits: n! / (k! (n − k)!).
p
p the chance of a hit on each trial.
n
n the number of trials, fixed before you start.
In plain words

The chance of one ordering with k hits is p to the k times one minus p to the n minus k. There are C(n, k) such orderings, and they cannot happen together. So multiply.

With numbers

n = 10, p = 0.3, k = 3: C(10, 3) = 120. One ordering has chance 0.33 × 0.77 = 0.00222. So P(X = 3) = 120 × 0.00222 = 0.267.

Count the orderings

Warm bars are Bin(n, p); the yellow line is the mean and the bracket is one standard deviation each side. Pick a k to see the orderings behind its bar.

10
0.30
3

Exact probabilities. No simulation.

The mean and the variance need no algebra. X is the sum of n Bernoulli variables. Averages always add. Variances add when the trials are independent. So:

E[X] = p + p + … + p = np Var(X) = p(1 − p) + … + p(1 − p) = np(1 − p) (needs independent trials)

For the page test, n = 200 and p = 0.05. The mean is 10 conversions, and the standard deviation is √9.5 = 3.08. Exactly 15 conversions has chance 0.034. Fifteen or more has chance 0.078, so 15 is not strong evidence of a better page. For accuracy on a test set, the same sums give its error bars: see The Statistics of Evaluation.

Failure: the trials are not independent.

Symptom: a test set holds 10 frames from each of 50 videos. Its 90% accuracy moves more between runs than np(1 − p) predicts.

Measure: the binomial standard deviation is 6.7 correct answers. In our simulation, where each video has its own accuracy, it is 7.6.

Fix: frames of one video pass or fail together, so count independent units (the 50 videos), or use a model where p varies by video.

You flip a fair coin 20 times. What are the mean and the variance of the number of heads?

Chapter 3

Many Chances, Each One Rare

Slice a window into more and more tiny slots and watch the binomial turn into the Poisson

A lidar sees on average 3 obstacles per scan, with no fixed number of trials and no upper limit. How likely are exactly 5? Cut the scan into n tiny slots. Each slot holds an obstacle with chance 3/n, on its own. The count is Bin(n, 3/n). Now make n huge.

Slice the window finer

Top: one window cut into n slots, with the slots that fired in teal. Bottom: warm bars are the Poisson; the yellow outline is Bin(n, λ/n). Drag n up and watch the gap close.

10
3.0

Exact bars. The gap is the total variation distance: half the sum of the bar differences. The strip of slots is one seeded, illustrative draw.

Two things happen as n grows. C(n, k) divided by nk tends to 1/k!. And (1 − λ/n)n tends to e−λ, where e = 2.718 is the base of the natural log. Call the average count in the window the rate λ, said "lambda". The limit is the Poisson distribution:

Say it aloud

P of X equals k equals lambda to the k, times e to the minus lambda, over k factorial.

P(X = k)
P of X equals k the chance of exactly k events in one window, for k = 0, 1, 2 and up, with no top.
λ
lambda the rate: the average number of events per window. It can be any positive number.
e−λ
e to the minus lambda the chance of no events at all.
k!
k factorial 1 × 2 × … × k, with 0! = 1. It removes the order of the k events.
In plain words

Start from the chance of nothing, e to the minus lambda. Multiply by lambda to the k for k events, and divide by k factorial because their order does not matter.

With numbers

With made-up numbers: λ = 3 obstacles per scan. P(X = 5) = 35 × e−3 / 5! = 243 × 0.0498 / 120 = 0.101. A clear scan has chance e−3 = 0.050.

At λ = 3 the gap between Bin(n, 3/n) and the Poisson is 0.086 for 10 slots, 0.0076 for 100, and 0.00075 for 1,000. The mean is λ, and the variance is also λ: the limit of n(λ/n)(1 − λ/n).

Two rules help. Add independent Poisson counts and the rates add: sensors at 3 and 5 per second give Poisson(8). Keep each event with chance q and you get Poisson(λq): 10 objects a scan with 40% cars gives Poisson(4) cars. The time between events is exponential (continuous lesson). Neuron spike counts are the classic case: Spikes to Rates.

Failure: events that come in bursts.

Symptom: at 2 errors an hour, the Poisson gives 10 or more errors in one hour a chance of 0.0000465, about once in 2.5 years. It happens after every bad deploy.

Measure: the hourly counts' variance divided by their mean. The Poisson needs about 1; bursty logs give far more.

Fix: events are not independent, and the rate is not constant. Model the extra spread with the negative binomial (Chapter 5).

A Poisson count has λ = 7. What is its variance?

Chapter 4

Wait for the First Head

Count the misses before the first hit, and find that past misses change nothing

A radio link delivers each packet with chance 0.3. The sender retries until one gets through. How many failed tries come first? Now the number of trials is not fixed. You stop at the first hit. The count of misses before it has a geometric distribution, Geom(p).

To see exactly k misses, you need k misses in a row and then a hit. With p the chance of a hit on each try:

Say it aloud

P of X equals k equals one minus p, to the k, times p.

P(X = k)
P of X equals k the chance of exactly k misses before the first hit.
p
p the chance of a hit on each try, the same every time.
k
k the number of misses: 0, 1, 2 and up, with no top.
In plain words

Multiply the chance of a miss, one minus p, by itself k times. Then multiply by p for the hit that ends the wait. Each extra miss shrinks the bar by the same factor.

With numbers

With made-up numbers: p = 0.3. P(X = 0) = 0.3. P(X = 2) = 0.72 × 0.3 = 0.147. Five or more misses in a row has chance 0.75 = 0.168.

The mean comes from one look at the first try. With chance p you stop with 0 misses. With chance 1 − p you have one miss, and the wait starts over. Write the mean as m:

m = p · 0 + (1 − p)(1 + m) so p m = 1 − p so m = (1 − p)/p Var(X) = (1 − p)/p²

At p = 0.3 the mean is 2.33 misses, or 3.33 tries in all. The variance is 7.78, so the standard deviation is 2.79, larger than the mean.

Forget the past misses

Blue bars: the misses still to come, over 4,000 simulated waits. Warm bars: Geom(p). Drag "already missed" up. Only the waits that got that far stay, and their remaining misses keep the same shape.

0.30
0

4,000 seeded, illustrative waits. The warm bars are exact.

That is the memoryless property. The chance of at least k misses is (1 − p)k. Given s misses, the chance of t more is (1 − p)s + t / (1 − p)s = (1 − p)t. That is the chance from the start. No other wait on 0, 1, 2, … has this property.

Failure: the library counts tries, not misses.

Symptom: a retry budget is one attempt too large, or a mean comes out as 3.33 instead of 2.33.

Measure: scipy.stats.geom(0.3).mean() returns 3.33 and geom.pmf(0) returns 0: SciPy counts tries, starting at 1.

Fix: say which convention you use. Misses = tries − 1; in SciPy, geom(p, loc=-1) counts misses.

A link succeeds with chance 0.3 per try. It has failed 4 times in a row. What is the chance the next try succeeds?

Chapter 5

Wait for r Heads, Fit Lumpy Counts

Add up r geometric waits, then use the same shape for counts whose rate wobbles

You need 3 positive examples from a stream where each sample is positive with chance 0.2. How many negatives come first? The count of misses before the r-th hit has a negative binomial distribution, NegBin(r, p).

The last trial is always the r-th hit. Before it come k misses and r − 1 hits, in any order. Call the number of hits you wait for r.

Say it aloud

P of X equals k equals k plus r minus one choose k, times p to the r, times one minus p to the k.

P(X = k)
P of X equals k the chance of exactly k misses before the r-th hit.
C(k + r − 1, k)
k plus r minus one choose k the ways to place k misses among the first k + r − 1 trials.
p
p the chance of a hit on each trial.
r
r the number of hits you wait for. With r = 1 this is the geometric.
In plain words

One ordering has r hits and k misses, so chance p to the r times one minus p to the k. The final hit is fixed, so count the ways to arrange the k misses among the trials before it.

With numbers

With made-up numbers: r = 3, p = 0.2, k = 10. C(12, 10) = 66. P(X = 10) = 66 × 0.23 × 0.810 = 66 × 0.008 × 0.107 = 0.057.

The wait for r hits is r geometric waits in a row, each independent. Means and variances add:

E[X] = r(1 − p)/p Var(X) = r(1 − p)/p² Var/E = 1/p

For r = 3 and p = 0.2: 12 negatives on average, variance 60, standard deviation 7.75. The variance is 1/p = 5 times the mean. A Poisson with the same mean would have variance 12.

That ratio matters for counts. Give each robot in a fleet its own fault rate, and Poisson faults at that rate. If the rates follow a Gamma distribution with shape r and mean r(1 − p)/p, the pooled counts are exactly NegBin(r, p). We simulated 400,000 such counts at r = 3, p = 0.2: mean 12.0, variance 60.0. Counts with variance above the mean are overdispersed.

Let the rate wobble

Each of 2,000 robot-days draws its own rate, then a Poisson count. Blue: the counts. Warm: NegBin with the same mean 4. Yellow outline: Poisson(4). Drag r down to make the rates vary more.

2

Seeded, illustrative fleet. Rates are Gamma with shape r and mean 4; larger r means steadier rates. At the right end every robot has rate 4.

Failure: a Poisson fit on overdispersed counts.

Symptom: sensor faults average 2.3 a day with variance 8.1. A Poisson fit gives 10 or more faults a day a chance of 0.014%. The fleet sees it on about 3% of days.

Measure: variance over mean is 3.5, not 1. In a Poisson regression, the Pearson chi-square divided by its degrees of freedom is far above 1, and the error bars are too narrow.

Fix: fit a negative binomial. By moments, p = mean/variance = 0.284 and r = mean · p/(1 − p) = 0.91.

Daily sensor faults have mean 2.3 and variance 8.1. Which model fits better?

Chapter 6

Draw Without Putting Back

Take items from a finite pool and watch each draw change the odds of the next

A lot of 100 chips holds 5 bad ones. An inspector tests 10, and never tests a chip twice. After the first chip, the pool has changed: 99 chips are left. The trials are no longer independent, so the binomial is wrong. The count of bad chips drawn has a hypergeometric distribution.

Count equally likely hands. Call the pool size N, the special items in it K, and the number you draw n. Choose k of the K special items, and n − k of the N − K others. Divide by all possible hands of n.

Say it aloud

P of X equals k equals K choose k, times N minus K choose n minus k, over N choose n.

P(X = k)
P of X equals k the chance of exactly k special items in the hand. The smallest k is max(0, n + K − N); the largest is min(n, K).
C(K, k)
K choose k the ways to pick k of the K special items.
C(N − K, n − k)
N minus K choose n minus k the ways to fill the rest of the hand from the ordinary items.
C(N, n)
N choose n every possible hand of n from the pool of N, all equally likely.
In plain words

Count the hands with exactly k special items: choose those k, then choose the ordinary rest. Divide by the number of all hands.

With numbers

N = 100 chips, K = 5 bad, n = 10 tested. P(X = 0) = C(95, 10) / C(100, 10) = 0.584. So the inspector finds at least one bad chip with chance 0.416. With 30 tests the chance rises to 0.839.

The mean is nK/N, the same as a binomial with p = K/N: each draw is special with chance K/N. The variance is smaller:

Var(X) = n (K/N)(1 − K/N) · (N − n)/(N − 1)

The last factor is the finite population correction. Each draw tells you something about what is left. Draw the whole pool, n = N, and the factor is 0: you know the count for sure.

Empty the urn

The urn holds 50 balls; 15 are teal. Warm bars: the hypergeometric. Yellow outline: the binomial with p = 0.3, as if you put each ball back. Drag n and draw a hand.

10

Exact bars. The drawn hand is a seeded, illustrative draw.

Failure: a random split starves the test set.

Symptom: a data set of 1,000 samples has 50 positives. A random 200-sample test set sometimes holds 4 positives or fewer, and recall jumps around between splits.

Measure: the count is hypergeometric with N = 1,000, K = 50, n = 200: mean 10, standard deviation 2.76, and P(X ≤ 4) = 0.016.

Fix: use a stratified split, which draws 10% of the positives and 10% of the negatives on purpose.

When does the hypergeometric differ most from the binomial?

Chapter 7

Pick One of K

Turn scores into K probabilities with softmax, and bend them with a temperature

A language model picks the next word from its vocabulary. An image classifier picks one of 1,000 classes. A Bernoulli has two outcomes. The categorical distribution has K outcomes, each with its own chance pi, and the K chances add up to 1. Its PMF is a lookup: P(X = i) = pi.

A network does not output probabilities. It outputs one score per option, called a logit. Call the logit of option i zi, and a positive knob that flattens or sharpens the result the temperature T. The softmax turns the scores into a categorical distribution:

Say it aloud

p-i equals e to the z-i over T, divided by the sum over j of e to the z-j over T.

pi
p-i the chance of option i, between 0 and 1.
ezi/T
e to the z-i over T the score z-i of option i, divided by the temperature T, then made positive by the exponential.
Σj ezj/T
the sum over j the same quantity added over all K options, so that the chances add up to 1.
In plain words

Divide every score z by T. Raise e to each one, so every option gets a positive weight. Divide each weight by the total weight.

With numbers

With made-up numbers: logits 2.0, 1.0, 0.5 and T = 1. The weights are 7.389, 2.718 and 1.649, total 11.756. So p = 0.628, 0.231 and 0.140. At T = 0.5 they become 0.844, 0.114 and 0.042.

Bend the softmax

Warm bars: the softmax over five tokens. Blue bars: 100 sampled picks. Drag T down toward greedy, or up toward the uniform.

1.0

Illustrative logits 2.0, 1.0, 0.5, 0.0 and −1.0. Samples come from a seeded generator.

The entropy, minus the sum of pi ln pi, measures how spread out the picks are. For the three tokens at T = 1 it is 0.906 nats. Its largest value is ln K, reached when every option has chance 1/K. That flat case is the discrete uniform. A fair die is uniform on 1 to 6: mean 3.5, variance (62 − 1)/12 = 2.92. In general, m equally spaced integers have variance (m2 − 1)/12.

Cross-entropy loss is −ln p of the true option: 0.464 if the first token is right. An ε-greedy agent with 8 actions and ε = 0.1 picks each action uniformly 0.1/8 = 1.25% of the time. Top-k and top-p sampling cut the tail before sampling; see Sampling & Decoding.

Failure: softmax overflows.

Symptom: a model with logits near 1,000 outputs NaN probabilities.

Measure: e1000 is larger than the largest float, so it becomes infinity, and infinity over infinity is NaN.

Fix: subtract the largest logit from every logit first. Adding the same number to every score leaves the softmax unchanged, and now every weight is at most 1.

You lower the temperature from 1 to 0.5. What happens to the top token's probability?

Chapter 8

Count Every Category at Once

Repeat a categorical pick n times, count each category, and see the counts pull against each other

A classifier sorts 200 documents into 3 topics with chances 0.5, 0.3 and 0.2. How many land in each topic? The binomial counted hits in n Bernoulli trials. The multinomial counts each of K categories in n independent categorical picks. The answer is a vector of counts x1 to xK that adds up to n.

Take one ordering with x1 picks of category 1, x2 of category 2, and so on. Its chance is p1x1 × … × pKxK. Count the orderings, as for the binomial:

Say it aloud

P of x-one through x-K equals n factorial over x-one factorial through x-K factorial, times p-one to the x-one, through p-K to the x-K.

P(x1, …, xK)
P of x-one through x-K the chance of this exact vector of counts, one count per category, adding up to n.
n! / (x1! ··· xK!)
the multinomial coefficient the number of orderings of n picks that give these counts.
pixi
p-i to the x-i the chance of category i, multiplied once for each of its x-i picks.
In plain words

Find the chance of one ordering: multiply each p-i by itself x-i times, and multiply those together. Then multiply by the number of orderings with the same counts.

With numbers

With made-up numbers: n = 4 picks, chances 0.5, 0.3, 0.2, counts (2, 1, 1). Orderings: 4! / (2! 1! 1!) = 12. One ordering: 0.52 × 0.3 × 0.2 = 0.015. So P = 12 × 0.015 = 0.18.

With K = 2 it is the binomial. With n = 1 it is one categorical pick, written as a one-hot vector. Each count alone is binomial: xi is Bin(n, pi), with mean npi and variance npi(1 − pi). But the counts share one total, so they are not independent:

Cov(xi, xj) = −n pi pj for two different categories i and j

Watch the counts compete

Left: one sample of n documents in 3 topics (blue) against the means (yellow ticks). Right: each dot is one sample's topic 1 and topic 2 counts. Resample and watch the cloud tilt down.

200

Seeded, illustrative samples with topic chances 0.5, 0.3 and 0.2. The means and the theoretical correlation are exact.

For n = 200: the mean counts are 100, 60 and 40. Topic 1 has variance 50 and topic 2 has 42. Their covariance is −200 × 0.5 × 0.3 = −30, a correlation of −30 / √(50 × 42) = −0.655. Large counts against expected counts are the basis of the chi-square goodness-of-fit test.

Failure: error bars that ignore the covariance.

Symptom: the gap between topic 1 and topic 2 counts looks significant, but repeats of the study disagree.

Measure: Var(x1 − x2) = 50 + 42 − 2(−30) = 152, standard deviation 12.3. Treating the counts as independent gives 92, standard deviation 9.6.

Fix: when two shares come from the same sample, subtract twice the covariance; for a gap, that adds 2npipj.

The multinomial is to the categorical as the binomial is to the ___?

Chapter 9

Name the Distribution Behind the Data

Read the story, compare the variance with the mean, fit, and look at the bars

Real data does not come with a label. You get 200 counts and a story. Three questions narrow the choice:

  1. What does the story count? Hits in a fixed number of trials points to the binomial; draws from a finite pool without putting back, the hypergeometric. Misses before a hit is the geometric; events in a window, the Poisson.
  2. How does the variance compare with the mean? Below it: binomial or hypergeometric. About equal: Poisson. Above it: geometric or negative binomial.
  3. Do the fitted bars match the data? Fit by moments, then check the bars and the tail.

Fit the data

Pick a data set and read its story. Then pick a candidate. Blue bars are the data; purple dots are the fitted distribution.

Each data set is 200 values we simulated with a fixed seed from a known distribution, so the right answer is known. Fits use the method of moments; the binomial and hypergeometric take n, N and K from the story.

Two cases deserve a second look. The retry data fits both the geometric and the negative binomial, because the moment fit lands on r = 0.98, almost exactly the geometric's r = 1. The chip data looks binomial, but the chips are not put back. Its variance is 1.63; Bin(10, 0.3) predicts 2.10 and the hypergeometric 1.62.

The numbers that decide it come from the story as much as the data. A count with a hard top cannot be Poisson, whatever its variance. A pool you draw from without putting back calls for the hypergeometric, even when the binomial looks close.

Failure: choosing by the shape alone.

Symptom: a Poisson fits quiz scores out of 20 and predicts a 4.7% chance of scores above 20.

Measure: the variance is 4.43 and the mean 13.96, a ratio of 0.32, far below the Poisson's 1. The story also has a top at 20.

Fix: start from what the story counts. Use the variance check to confirm the choice.

Counts with no upper limit have mean 4 and variance 11. Which candidate do you try first?

Chapter 10

The Field Guide

Keep the questions, the formulas and the library conventions in one place

Every distribution here answers one counting question, and the table lists them. Find the question first. Then check the variance against the mean.

DistributionQuestionPMFMeanVariance
Bernoulli(p)Hit or miss?pk(1 − p)1 − kpp(1 − p)
Binomial(n, p)Hits in n trials?C(n, k) pk(1 − p)n − knpnp(1 − p)
Poisson(λ)Events in a window?λke−λ/k!λλ
Geometric(p)Misses before a hit?(1 − p)kp(1 − p)/p(1 − p)/p2
NegBin(r, p)Misses before r hits?C(k + r − 1, k) pr(1 − p)kr(1 − p)/pr(1 − p)/p2
Hypergeometric(N, K, n)Specials in a hand?C(K, k)C(N − K, n − k)/C(N, n)nK/Nn(K/N)(1 − K/N)(N − n)/(N − 1)
Categorical(p1..K)Which one of K?piindicator i: piindicator i: pi(1 − pi)
Uniform{a..b}No preference?1/m, m = b − a + 1(a + b)/2(m2 − 1)/12
Multinomial(n, p1..K)Counts of K categories?n!/(∏xi!) ∏pixinpinpi(1 − pi); Cov −npipj

How they connect

Corrections to the old version of this page

The core as code

pythonimport numpy as np
from scipy import stats

# SciPy conventions: geom counts TRIES (from 1); nbinom(n=r, p) counts MISSES;
# hypergeom(M=pool N, n=specials K, N=draws n) -- the letters are swapped.
stats.binom(200, 0.05).pmf(15)            # 0.0338
stats.poisson(3).pmf(5)                    # 0.1008
stats.geom(0.3, loc=-1).mean()              # 2.33 misses (loc=-1 shifts tries to misses)
stats.nbinom(3, 0.2).var()                  # 60.0
stats.hypergeom(1000, 50, 200).cdf(4)        # 0.016

def softmax(z, T=1.0):
    z = np.asarray(z, float) / T
    w = np.exp(z - z.max())                    # subtract the max: no overflow
    return w / w.sum()

def moment_fit(x):
    """Variance against mean: below 1 binomial-like, near 1 Poisson, above 1 NegBin."""
    m, v = np.mean(x), np.var(x)
    if v <= m:
        return "poisson", {"mu": m}             # below 1: check the story for a cap
    p = m / v
    return "nbinom", {"n": m * p / (1 - p), "p": p}

Keep going

The takeaway. Find the counting question first: one trial, n trials, a window, a wait, a pool, or K options. Then check the variance against the mean before you trust the fit.

Now press Present or Teach and explain four things from memory. Explain why the binomial coefficient appears, with C(10, 3) = 120. Explain how Bin(n, λ/n) becomes the Poisson. Explain why the geometric forgets past misses. Explain why a wobbling rate makes counts negative binomial. Then go back to the hero, ask the coin for the tails before 3 heads, and drag p down.

Discrete Distributions
Next: Continuous Distributions · Back to Gleams