Level 3 In-Depth AI · Math Foundations
Probability Distributions
A probability distribution lists every possible outcome and how likely each one is. A handful of shapes — Bernoulli, categorical, uniform and the Gaussian bell curve — appear everywhere in AI, and softmax turns any list of scores into a distribution a model can sample from.
- Level
- ●●●●● Easy
- Reading
- 12 min
- To learn it well
- 50 minutes to read, an hour to practise
- Builds on
- 1 concept →
- Quiz
- 5 questions ↓
Read first
Probability BasicsThe full path from zero — 1 concept before this one
- Probability Basics
- Probability Distributions
Read them roughly in this order. See it on the concept map →
Why it matters
In Probability Basics we asked about one event at a time: what's the chance of a six? A probability distribution answers the question for every outcome at once. It is the complete description of something uncertain.
AI is full of distributions:
- A classifier's output is a distribution over classes: 0.81 cat, 0.12 tiger, 0.03 lynx, …, all adding up to 1.
- A language model outputs a distribution over its whole vocabulary, about 50,000 to 200,000 tokens, every time it predicts the next token. Generating text means sampling from that distribution again and again.
- Neural network weights start out as random draws from a Gaussian or uniform distribution (Weight Initialization).
- Diffusion Models learn to remove Gaussian noise. Variational autoencoders squeeze images into Gaussian distributions.
- Losses come from distributions: squared error assumes Gaussian noise and cross-entropy assumes a categorical distribution, as the Maximum Likelihood Estimation chapter shows.
A small family of distributions covers most of what you'll meet. This chapter introduces them, explains the subtle idea of density for continuous values, and ends with softmax and temperature, the knobs behind every chatbot's creativity setting.
The intuition
Picture a long row of buckets, one for each possible outcome, and pour a fixed amount of sand into them, exactly one kilogram in total. How you share the sand among the buckets is the distribution. A fair die puts 1/6 kg in each of six buckets. A loaded die piles more sand into one bucket. A classifier confident it's looking at a cat puts most of its sand in the "cat" bucket. The total is always 1, because something must happen.
That works when the outcomes can be listed: heads or tails, the six faces of a die, the words of a vocabulary. These are discrete distributions.
But some quantities can take any value on a scale: a person's height, the temperature tomorrow, a pixel brightness between 0 and 1. There are infinitely many possible values, so you can't have a bucket for each. Instead, imagine spreading the kilogram of sand along a line, piling it higher where values are more likely. The height of the pile at each point is the probability density. The probability of landing in a range is the amount of sand over that range, the area under the curve. These are continuous distributions.
Key idea A distribution shares out a total probability of 1 across all possible outcomes. Discrete distributions give each outcome a probability. Continuous distributions give a density, and probabilities are areas under the density curve.
How it works
Discrete distributions
A discrete distribution is a list of outcomes with a probability for each, all non-negative and adding to 1. Formally, this list is called the probability mass function, .
Bernoulli. The simplest possible distribution: one trial with two outcomes, 1 ("yes", "success", "spam") with probability and 0 with probability . A coin flip is Bernoulli with . A spam filter's output "0.92 spam" describes a Bernoulli distribution with . Its average value is .
Categorical. One trial with possible outcomes, with probabilities that add up to 1. A fair die is categorical with six equal probabilities of . An image classifier with 1,000 classes outputs a categorical distribution with 1,000 probabilities. A language model's next-token prediction is categorical over the whole vocabulary.
(Two relatives you'll meet: the binomial distribution counts the number of successes in independent Bernoulli trials, such as the number of heads in 10 flips. The multinomial does the same for categorical trials.)
Continuous distributions and density
For a continuous quantity, the probability of any exact value is zero. The chance that someone is exactly 170.000000… cm tall is nil. So instead we use a probability density , a curve whose area over a range gives the probability of landing in that range:
The total area under the whole curve is 1. (In calculus notation the area is an integral, , but "area under the curve" is all you need here.)
A consequence that surprises people: a density can be larger than 1. A uniform distribution on the range has density 2 everywhere in that range, because width height $2 = $ area 1. Densities are not probabilities. Areas are.
Uniform. Every value in a range is equally likely, so the density is flat at height . np.random.random() draws from the uniform distribution on . It is the raw material from which computers generate all other random numbers.
The Gaussian (normal) distribution
The most important continuous distribution is the Gaussian distribution, also called the normal distribution or the bell curve. It has two parameters:
- the mean ("mu"): where the centre of the bell is;
- the standard deviation ("sigma"): how wide it is. (The Statistics: Mean, Variance and Sampling chapter shows how to compute both from data.)
Its density is
Don't be put off. Read it from the inside out. is the squared distance from the centre. Dividing by measures that distance in units of the spread. (that is, ) turns it into a value that is 1 at the centre and drops quickly towards 0 as you move away. The fraction in front just scales the curve so that its total area is 1. We write for "X is Gaussian with mean and variance ".
The shape always obeys the 68–95–99.7 rule: about 68% of values fall within one standard deviation of the mean, 95% within two, and 99.7% within three.
A worked example: adult heights in some population are roughly Gaussian with cm and cm. Then about 68% of people are between 160 and 180 cm, and about 95% between 150 and 190 cm. Someone 200 cm tall is three standard deviations above the mean, which puts them among roughly the tallest 0.15%.
Why is the Gaussian everywhere? The central limit theorem says that when you add up many small, independent random effects, the total tends towards a Gaussian, whatever the individual effects look like. Measurement noise, heights and test scores are all sums of many small influences. In AI, Gaussians are used to initialise weights, to model noise in regression, as the noise in Diffusion Models, and as the "standard normal" that many methods sample from.
Real data often isn't Gaussian, though. Incomes, word frequencies and city sizes have long tails, with rare values far larger than a bell curve would allow.
Sampling
Sampling means drawing a random value according to a distribution: more probable values come up more often. For a categorical distribution with probabilities , think of a line of length 1 cut into pieces of length 0.6, 0.3 and 0.1. Draw a uniform random number between 0 and 1 and see which piece it lands in. Draw 10,000 times and you get the first outcome about 6,000 times.
Sampling is how a language model writes. At each step it computes a categorical distribution over tokens, samples one, appends it to the text, and repeats. Because of the sampling, the same prompt can give a different answer each time. Decoding: Temperature, Top-k and Top-p covers the variations, such as always taking the most probable token ("greedy") or sampling only from the top few.
Softmax: from scores to a distribution
A neural network's last layer produces arbitrary real numbers, one per class, called logits. They can be negative and needn't add to anything. To turn them into a categorical distribution we need numbers that are positive and sum to 1. Softmax does exactly that: exponentiate each score (making it positive, and exaggerating differences), then divide by the total.
By hand, with logits for "cat", "dog", "car":
- Exponentiate: , , .
- Add them up: .
- Divide each by the total: , , .
The probabilities add to 1, keep the order of the scores, and the biggest score gets a disproportionately large share. (The name means a "soft" version of the max function, which would give everything to the top score.) Softmax is also how Attention turns similarity scores into weights.
Temperature
Temperature is a single number that divides the logits before softmax: .
- leaves the distribution unchanged.
- makes the differences between scores bigger, so the distribution becomes sharper: the top choice dominates. As it becomes "always pick the top choice".
- shrinks the differences, so the distribution becomes flatter and more random.
The "temperature" setting in language-model tools (Hugging Face, Ollama, many APIs) is exactly this; some newer hosted reasoning models no longer expose it. Low temperature gives focused, repeatable answers. High temperature gives more varied, surprising and error-prone text.
In code
import numpy as np
rng = np.random.default_rng(0)
# Bernoulli(p = 0.3): 1 with probability 0.3, else 0
coin = rng.random(10_000) < 0.3
print(coin.mean()) # 0.3008
# Categorical over 3 classes
probs = [0.6, 0.3, 0.1]
draws = rng.choice(3, size=10_000, p=probs)
print(np.bincount(draws) / len(draws)) # [0.5925 0.3095 0.098 ]
# Gaussian with mean 170, standard deviation 10 (heights in cm, say)
h = rng.normal(loc=170, scale=10, size=100_000)
print(h.mean().round(2), h.std().round(2)) # 169.97 10.02
print(np.mean(np.abs(h - 170) < 10)) # 0.68289 within 1 sd: about 68%
print(np.mean(np.abs(h - 170) < 20)) # 0.95398 within 2 sd: about 95%
def softmax(logits, temperature=1.0):
z = np.asarray(logits) / temperature
z = z - z.max() # for numerical safety; doesn't change the result
e = np.exp(z)
return e / e.sum()
logits = [2.0, 1.0, 0.1]
for T in [1.0, 0.5, 2.0]:
print(T, softmax(logits, T).round(3))
# 1.0 [0.659 0.242 0.099]
# 0.5 [0.864 0.117 0.019]
# 2.0 [0.502 0.304 0.194]
In PyTorch, softmax and sampling are built in, and torch.distributions provides ready-made distributions with densities and samplers:
import torch
logits = torch.tensor([2.0, 1.0, 0.1])
probs = torch.softmax(logits, dim=-1)
print(probs) # tensor([0.6590, 0.2424, 0.0986])
next_token = torch.multinomial(probs, num_samples=1) # sample one class index
normal = torch.distributions.Normal(loc=0.0, scale=1.0)
print(normal.log_prob(torch.tensor(0.0)).exp()) # tensor(0.3989) density at the mean
The line z = z - z.max() in the NumPy softmax matters. overflows to infinity, but subtracting the largest logit first makes every exponent zero or negative, and gives exactly the same probabilities.
Common pitfalls
- Treating densities as probabilities. A Gaussian with has density about 4 at its centre. That is not a probability of 4. Only areas under a density are probabilities.
- Assuming everything is Gaussian. Many real quantities are skewed or heavy-tailed. A model that assumes Gaussian noise will be badly surprised by outliers. Plot a histogram before assuming.
- Softmax overflow. Implementing softmax as
np.exp(z) / np.exp(z).sum()givesnanfor large logits. Subtract the max first, or use the library function. - Applying softmax twice. PyTorch's
nn.CrossEntropyLossexpects raw logits and applies (log-)softmax itself. Feeding it probabilities gives a model that trains, but badly. - Reading softmax outputs as calibrated confidence. Softmax always produces numbers that look like probabilities. Whether they match reality is a separate question (calibration; see Evaluation Metrics).
- Variance versus standard deviation. NumPy's
scaleand PyTorch'sNormal(loc, scale)take the standard deviation , but the notation shows the variance. Mixing them up squares your spread.
Watch out Temperature does not make a model more knowledgeable. Lower temperature makes it more consistent, not more correct. If the model's top choice is wrong, temperature 0 will give the same wrong answer every time.
Where it leads
- Statistics: Mean, Variance and Sampling: estimating a distribution's mean and spread from data, and how sure you can be.
- Maximum Likelihood Estimation: fitting a distribution's parameters to data, and where squared-error and cross-entropy losses come from.
- Entropy, Cross-Entropy and KL Divergence: entropy measures how spread out a distribution is; cross-entropy and KL divergence compare two distributions.
- Logistic Regression: the sigmoid (two-class softmax) turns a score into a Bernoulli probability.
- Decoding: Temperature, Top-k and Top-p: greedy, temperature, top-k and top-p sampling from a language model.
- What Generative Models Do, Variational Autoencoders and Diffusion Models: models that learn whole distributions of images or text and sample new examples from them.
A bit of history
Abraham de Moivre found the bell curve in 1733 as an approximation to coin-tossing counts. Pierre-Simon Laplace proved an early central limit theorem around 1810, and Carl Friedrich Gauss used the curve in 1809 to model errors in astronomical measurements, which is why it bears his name. Jacob Bernoulli's work on repeated yes/no trials appeared in 1713. The softmax function comes from statistical physics, where Ludwig Boltzmann used the same formula in the 1870s for the probability of a system being in each energy state. That is where the word "temperature" comes from. It entered neural networks around 1989–1990, when John Bridle named it "softmax" and used it for classification outputs.
Try it
- By hand, compute the softmax of and of . What happens to the second at temperature 10?
- Draw 1,000 samples from a uniform distribution on and add them in groups of 12, giving 1,000 sums. Plot a histogram of the sums. What shape do you see, and why?
- Heights are . Using the 68–95–99.7 rule, roughly what fraction of people are taller than 180 cm? Check with a simulation.
Hint for 2: that is the central limit theorem at work. The sums have mean 6 and standard deviation 1. For 3: half of the 32% outside , so about 16%.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Seeing Theory
A visual introduction to probability and statistics with interactive animations.
Statistics and Probability
A full school-to-university course on data summaries, probability, distributions, sampling and inference, with practice problems.
Stat 110: Probability
A legendary probability course with free lectures, a free textbook and problem sets.
Probabilistic Machine Learning
A comprehensive two-volume reference viewing ML through probability. Free drafts online.
Mathematics for Machine Learning
The linear algebra, calculus, probability and optimisation that ML uses, in one free book.
Review of Probability Theory
A short reference covering events, random variables, common distributions, expectation and multivariate Gaussians, written for ML students.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/math/distributions.md