Random Variables and Distributions That Show Up in Model Building
A working guide to the distributions behind common losses and priors, how to pick one for your target, and how to check it.
Key takeaways
- Choose a distribution by what the variable can be: a yes or no, a category, a count, a positive amount, a proportion or any real number.
- A probability mass function gives probabilities directly, while a density gives probability only after integrating over a range.
- Minimizing squared error, absolute error and cross-entropy corresponds to maximum likelihood under particular distributions.
- The conditional distribution of the target given the inputs is what a model describes, not the overall distribution of the target.
- Check an assumed distribution against data before trusting the probabilities it produces.
A random variable is a quantity whose value depends on chance, and its distribution says how probable the possible values are. In model building you meet them constantly: the label you predict, the noise around a regression line, the starting values of the weights, the uncertainty about an error rate.
A handful of distributions cover most of it. Each fits a particular kind of quantity, and many standard loss functions are simply the negative log probability under one of them.
Mass, density and the cumulative function
A discrete variable takes separate values, such as 0, 1, 2. Its probability mass function assigns a probability to each, and these sum to 1.
A continuous variable can take any value in a range. Its probability density function f is not a probability. The probability of landing between a and b is the integral of f from a to b, and any single exact value has probability zero. A density can exceed 1: a variable spread evenly over 0 to 0.5 has density 2 everywhere on that interval.
The cumulative distribution function F(x) = P(X ≤ x) works for both kinds. It rises from 0 to 1.
Two summaries appear everywhere. The expectation E[X] is the probability-weighted average. The variance Var(X) = E[(X − E[X])²] measures spread, and its square root is the standard deviation. Not every distribution has them: the Cauchy distribution has tails so heavy that its mean is undefined.
Yes, no and categories
A Bernoulli variable is 1 with probability p and 0 otherwise. Its mean is p and its variance p(1 − p), largest at p = 0.5. A binary classifier's output is naturally read as the p of a Bernoulli, one for each input.
A categorical variable picks one of K classes with probabilities p₁ to p_K that sum to 1. Softmax output layers parameterize it. If each example can carry several labels at once, a categorical distribution is the wrong model. Use one Bernoulli per label.
A binomial variable counts successes in n independent Bernoulli trials with the same p. Its mean is np and its variance np(1 − p).
Say a classifier is correct with probability 0.9 on each of 100 independent test examples. The number correct has mean 90 and standard deviation √(100 · 0.9 · 0.1) = 3. Seeing 87 one week and 93 the next would be unremarkable.
Counts and waiting times
A Poisson variable counts events in a fixed window when they occur independently at a constant average rate λ.
P(X = k) = λᵏ e^(−λ) / k! mean λ, variance λ
with λ = 2: P(0) ≈ 0.135, P(1) ≈ 0.271, P(2) ≈ 0.271 Its equal mean and variance is a strong claim. Real counts, such as purchases per customer, often vary much more than their mean, which is called overdispersion. The negative binomial distribution adds a parameter that allows it.
The exponential distribution models the waiting time between events in a Poisson process. With rate λ, the mean wait is 1/λ. It is memoryless: having waited a while tells you nothing about the remaining wait. Equipment that wears out violates that, and the Weibull family is a common alternative.
Generalized linear models connect these distributions to inputs through a link function.
Real values and positive amounts
The uniform distribution spreads probability evenly over an interval from a to b, with mean (a + b)/2 and variance (b − a)²/12. It appears in random sampling, some weight initializations and random hyperparameter search.
The Gaussian, or normal, distribution has a mean μ and variance σ². It is the default for additive noise, and its role and limits deserve their own discussion.
The Laplace distribution has a sharper peak and heavier tails than a Gaussian, so it tolerates occasional large errors better.
A log-normal variable is one whose logarithm is Gaussian. It is positive and skewed to the right, a reasonable shape for many prices, durations and sizes. Fitting squared error on ln y and then exponentiating estimates the median of y under that model, not the mean, which is larger by the factor exp(σ²/2).
Which loss goes with which distribution
The negative log likelihood of the data under an assumed distribution is a loss you can minimize.
| Target and assumption | Resulting loss | What a perfect model predicts |
|---|---|---|
| Real, Gaussian noise with fixed variance | Squared error | Conditional mean |
| Real, Laplace noise with fixed scale | Absolute error | Conditional median |
| Binary, Bernoulli | Binary cross-entropy | Probability of class 1 |
| One of K classes, categorical | Cross-entropy | Class probabilities |
| Count, Poisson | ŷ − y ln ŷ, plus a constant | Conditional mean rate |
The last column holds when the model family is flexible enough and data are plentiful. For the Gaussian row, the squared error loss still targets the conditional mean even if the noise is not Gaussian, although it may then be an inefficient or fragile way to estimate it. Loss functions as definitions takes up the choice from the task side.
Distributions over probabilities
The beta distribution lives between 0 and 1, so it can describe uncertainty about an unknown probability. It has two positive shape parameters, a and b, and mean a/(a + b).
It pairs neatly with the Bernoulli. Start with a Beta(1, 1) prior, which is uniform, and observe 7 successes and 3 failures. The posterior is Beta(8, 4), with mean 8/12 ≈ 0.667. The update just adds counts. Such a pairing is called conjugate.
The Dirichlet distribution extends this to K probabilities that sum to 1. It appears in topic models such as latent Dirichlet allocation and as a smoothing prior for category frequencies.
Joint, marginal and conditional
With two variables, the joint distribution p(x, y) covers pairs. The marginal p(y) sums or integrates x away. The conditional p(y | x) = p(x, y)/p(x), defined where p(x) > 0, describes y once x is known.
Supervised learning is mostly about the conditional. A target can look wildly non-Gaussian overall, perhaps with two humps from two kinds of customer, while its spread around a good prediction is close to Gaussian. Judge the assumption on the residuals.
Variables are independent when p(x, y) = p(x) p(y). Training usually assumes that examples are independent draws from one distribution, and that assumption fails for repeated users, time series and duplicated records.
Transforming a random variable
Preprocessing changes distributions, and the rules differ for the two kinds. For a discrete variable, probabilities simply move with the values. For a continuous one, a transformation stretches and squeezes the axis, so the density must be rescaled.
If y = g(x) with g smooth and strictly increasing or decreasing, then p_y(y) = p_x(x) / |g′(x)| at the matching point. Suppose x is uniform on 0 to 1 and y = 2x. The values now cover 0 to 2, and the density halves to 0.5 so that the total stays 1.
This factor matters whenever you compare likelihoods. A model of ln y and a model of y assign densities in different units, and their raw log likelihoods cannot be compared until the correction term is included. Normalizing flows build entire generative models from this rule.
The expectation also fails to pass through a curved function: in general E[g(X)] differs from g(E[X]). For a variable that is −1 or 1 with equal probability, the mean is 0, yet the mean of the square is 1.
Where randomness enters a training run
Distributions describe your own procedure as well as your data. Initial weights are drawn from a uniform or Gaussian distribution whose variance is set from the layer width. Dropout multiplies activations by Bernoulli variables. Mini-batches are random samples of the training set. Data augmentation draws crop positions, angles or noise levels.
Each of these is a choice you can state, vary and record. Two runs with different draws will differ, so a single run is one sample of what your method produces. Fix seeds to reproduce a result, and use several seeds to learn how much it moves.
Sampling and checking
NumPy can simulate any of these, which is a quick way to test your intuition.
import numpy as np
rng = np.random.default_rng(0)
n = 100_000 # samples per distribution
samples = {
"binomial": rng.binomial(100, 0.9, size=n),
"poisson": rng.poisson(2.0, size=n),
"exponential": rng.exponential(scale=0.5, size=n), # scale = 1/rate
"beta": rng.beta(8, 4, size=n),
}
for name, x in samples.items():
print(name, round(x.mean(), 3), round(x.var(), 3)) Compare each printed mean and variance with the formulas. Note that libraries differ on whether a parameter is a rate or a scale, a variance or a standard deviation. Read the signature.
To check a fitted assumption, plot predicted against observed frequencies for discrete targets, compare residual quantiles with theoretical ones for continuous targets, and count how often observations fall inside predicted 90% intervals. Do this on held-out data.
Common mistakes
- Treating a density value as a probability.
- Using squared error on counts that are mostly zero with a few large values, without checking the residual spread.
- Modeling a bounded quantity with a distribution that gives real probability to impossible values.
- Assuming a model's softmax outputs are accurate probabilities. The distributional form does not make the numbers calibrated.
Common questions
Do I need to choose a distribution for a decision tree or a neural network?
Whenever you choose a loss, you make an implicit choice about what is being estimated. It is worth saying aloud, even if you never write down a likelihood.
What if no named distribution fits?
You have options: predict several quantiles, use a mixture of simple distributions, transform the target, or split the problem, for example into whether an amount is zero and how large it is when it is not.