Distributions
Random variables and the shapes their outcomes take.
Create a free account Try part of it here
Why it matters
When a language model writes, it doesn't pick one word for sure. At each step it gives a chance to every possible next token (a word or a piece of a word), and there are roughly 100,000 of them. That list of chances is a distribution. Writing text means drawing from it, again and again. Everyday numbers work the same way: sales per day, orders per hour, the size of the next order. Once you know the common shapes, you can tell normal ups and downs from a real change. This lesson gives you the words. The next ones measure where a distribution sits and how widely it spreads.
What you'll be able to do
- Describe a random variable and its distribution: which values, how likely
- Tell discrete distributions (counts) from continuous ones (measurements)
- Recognize Bernoulli, binomial, Poisson and categorical distributions in marketing data
- Sample from a categorical distribution, the way a language model picks its next token
What it covers
- A number that comes from chance
- Counts and measurements
- Four shapes worth knowing
- Worked example: buyers in a small shop
- Sampling the next token
A number that comes from chance
Toss a coin twice and count the heads. You might get 0, 1 or 2. You can't know which before you toss. But you do know the chances.
A number like this is called a random variable. It is a number produced by a chance process. Other examples:
- how many of the next 100 visitors to a shop buy something;
- the dollar value of the next order;
- which word a language model writes next.
A random variable's distribution is its full menu: every value it can take, and how likely each one is. For two coin tosses the menu is short:
| heads | chance |
|---|---|
| 0 | 0.25 |
| 1 | 0.5 |
| 2 | 0.25 |
Getting exactly one head is twice as likely as the others. There are two ways to do it: heads-then-tails or tails-then-heads. The chances add up to 1, because something always happens.
Math books name a random variable with a capital letter, usually . They write the chance that it equals some value like this:
In plain words: "the probability that X comes out as k." For two coin tosses, .
In Python, a dictionary holds the same menu. Each key is a possible count of heads, and it maps to that count's chance:
pmf = {0: 0.25, 1: 0.5, 2: 0.25} # heads in two coin tosses
print(pmf[1])
print(sum(pmf.values()))It prints 0.5, the chance of one head, and 1.0, the total of all the chances. A menu like this is called the probability mass function, or PMF. "Mass" because each value carries its own lump of probability.
Show the answer
0.25
Only one pattern gives two heads (heads, heads), so its chance is 0.25.
Counts and measurements
Random variables come in two kinds.
Discrete ones are counts. You can list their values one by one: 0, 1, 2, 3 sales. Each value gets its own chance, as in the coin table.
Continuous ones are measurements. They can land anywhere in a range, like the seconds a visitor spends on your site. Here something odd happens. The chance of exactly 90.000000 seconds is zero, because there are endless nearby values it could be instead. So you ask about ranges: "How likely is a visit between 85 and 95 seconds?"
A continuous variable has a smooth curve called a density. High parts of the curve are where values are common. The area under the curve between two points is the chance of landing between them. You'll meet the most famous one, the bell curve, in a later lesson.
"At most" questions
For both kinds, you often want the chance of a value at most some amount. That is the cumulative distribution:
In plain words: "the probability that X comes out at x or below." The symbol means "less than or equal to."
For two coin tosses, the chance of at most one head is the chance of 0 plus the chance of 1: 0.25 + 0.5 = 0.75. In Python, you add up every entry whose value is small enough:
pmf = {0: 0.25, 1: 0.5, 2: 0.25}
print(sum(chance for heads, chance in pmf.items() if heads <= 1))
It prints 0.75.
Show the answer
The number of emails in your inbox tomorrow morning
Emails are counted (0, 1, 2, ...). Time, weight and temperature are measurements that can land anywhere in a range.
Four shapes worth knowing
A few distributions turn up again and again. Each one has an everyday picture.
Bernoulli. One yes-or-no try, like one coin toss. Did this visitor buy? The only setting is , the chance of a "yes."
Binomial. Repeat the same yes-or-no try times and count the yeses. The tries must be independent: one doesn't change the others. Two coin tosses is a binomial with . So is "buyers among 200 visitors." The chance of exactly yeses is:
In plain words: count the ways to get k yeses, then multiply by the chance of any one of those ways. The part , said "n choose k," is the number of ways to pick which k of the n tries were yeses.
Check it on two coin tosses, with one head (, , ):
- ways to pick which toss was heads: 2 (the first or the second);
- chance of one particular pattern, such as heads-then-tails: 0.5 × 0.5 = 0.25;
- total: 2 × 0.25 = 0.5.
That matches the table. Python's math.comb does the counting:
import math n, k, p = 2, 1, 0.5 print(math.comb(n, k)) print(math.comb(n, k) * p**k * (1 - p)**(n - k))
It prints 2 (the number of ways) and 0.5 (the chance).
Go deeper Why the formula has three parts
Take one specific pattern with yeses and noes, such as yes, no, no. The tries are independent, so you multiply their chances (the rule from Probability basics). Each yes brings a factor of , and each no brings a factor of . That gives .
Every pattern with the same number of yeses has the same chance. So you multiply by how many such patterns there are, which is . For 5 tries with 2 yeses there are 10 patterns, and math.comb(5, 2) returns 10.
Poisson. Counts of events in a fixed window of time, when they happen independently at a steady average rate. Think orders per hour or support tickets per day. Its one setting is the average rate, written (lambda).
Categorical. One draw from several labeled outcomes, each with its own chance. Which of five products a visitor buys. Which word comes next. This is the distribution a language model outputs.
The code below fakes 10,000 days of a shop. Each day, 200 visitors each buy with a 4% chance (binomial). It also fakes 10,000 hours of orders arriving at 3.5 per hour on average (Poisson). Then it draws a bar chart of each and prints the averages.
import numpy as np import matplotlib.pyplot as plt rng = np.random.default_rng(0) conversions = rng.binomial(n=200, p=0.04, size=10_000) # 10,000 days of 200 visitors each orders_per_hour = rng.poisson(lam=3.5, size=10_000) fig, axes = plt.subplots(1, 2, figsize=(8, 3)) axes[0].hist(conversions, bins=np.arange(0, 21) - 0.5) axes[0].set_title("conversions from 200 visitors (p = 4%)") axes[1].hist(orders_per_hour, bins=np.arange(0, 15) - 0.5) axes[1].set_title("orders per hour (rate 3.5)") print("average conversions:", conversions.mean().round(2), " average orders/hour:", orders_per_hour.mean().round(2))
The averages come out close to 8 and 3.5. The 8 makes sense: 4% of 200 visitors is 8. A conversion here means a visitor who buys.
Now look at the left chart. A typical day has about 8 conversions. Yet anywhere from about 3 to 13 is ordinary noise. Seeing 6 one day and 11 the next isn't news.
Show the answer
Binomial
A fixed number of independent yes/no tries, each with the same chance p: that's binomial.
Worked example: buyers in a small shop
Ten people walk into a small shop. Each one buys with a 20% chance, and they decide independently. What is the chance that exactly 2 buy? What is the chance that at most 1 buys?
import math n, p = 10, 0.2 def chance(k): return math.comb(n, k) * p**k * (1 - p)**(n - k) print("exactly 2:", round(chance(2), 3)) print("at most 1:", round(chance(0) + chance(1), 3)) print("all chances add to:", round(sum(chance(k) for k in range(n + 1)), 3))
This is a binomial with and . Exactly 2 buyers has a chance of about 0.302. That is the single most likely count, which fits: 20% of 10 people is 2. At most 1 buyer means 0 or 1, so you add those two chances to get about 0.376. The last line is a safety check. Every possible count from 0 to 10 together adds up to 1.
Sampling the next token
Here is where distributions meet AI. A language model gives every possible next token a score. A step called softmax turns those scores into chances that add up to 1 (a later lesson covers it). That is a categorical distribution. The program then draws one token from it.
Picture a raffle drum with 100 tickets. 42 say "great," 30 say "good," 15 say "solid," 8 say "fine" and 5 say "amazing." Draw a ticket, read it, and put it back. Do that 1,000 times and "great" comes up about 42% of the time. Any single draw, though, could be any word. That's why the same prompt can give different replies.
The code draws 1,000 tokens this way, prints each token's share, then shows ten draws in a row:
import numpy as np tokens = ["great", "good", "solid", "fine", "amazing"] probs = [0.42, 0.30, 0.15, 0.08, 0.05] rng = np.random.default_rng(7) draws = rng.choice(tokens, size=1000, p=probs) for t in tokens: print(f"{t:<8} {np.mean(draws == t):.3f}") print("ten samples:", " ".join(rng.choice(tokens, size=10, p=probs)))
Each share lands close to its chance, and the ten samples mix different words.
The other option is to always pick the single most likely token. This is called greedy decoding. Math books write the choice as , short for "the option with the biggest value." Greedy decoding is more predictable, but it also repeats itself more. Phase 5 covers how temperature and other settings reshape the distribution before a token is drawn.
words = ["cat", "dog"] probs = [1.0, 0.0] import random print(random.choices(words, probs)[0])
Show the answer
cat
All the weight, 1.0, is on "cat" and none on "dog", so the draw can only give cat. Sampling draws according to the odds, and here all the odds are on one word.
The next token is a random variable: one draw from these odds. Press Sample 100 and the marks settle close to the bars.
Show the answer
"great", every time
Greedy decoding always takes the most likely token, so it picks "great" every time. Sampling would give "great" about 42% of the time.
Practice what you just read
- 6 code examples you can edit and run
- a practice exercise that checks your code
- a 5-question quiz
- 5 review cards for spaced repetition
Try a quiz question
Which is a continuous random variable?