Random Variables and Distributions

If we want to extract meaningful insights from our datasets, we need to understand their underlying patterns and structure. But how can we make sense of thousands or even millions of data points?

The answer lies in probability distributions.

This Lesson Will Cover
  • 📊 How distributions are used in ML/AI
  • 🎲 How random variables are used in ML/AI
  • 🔔 The Gaussian (Normal) distribution
  • 📈 The Central Limit Theorem
  • 📏 Other common distributions (Bernoulli, Poisson, Chi-Squared)
  • 🎛️ Random variates and their applications

How distributions are used in ML/AI

Distributions help us characterize data by revealing crucial properties:

  • Is the data normally distributed?
  • Are there outliers?
  • What’s the variance?

These insights guide our modeling decisions and help us choose appropriate algorithms.

Here are some aspects of ML/AI that rely on distributions:

  • Feature Scaling and Normalization

    • Standardization transforms features to follow a normal distribution with zero mean and unit variance.
  • Model Training

    • Initial weights are often sampled from normal or uniform distributions.
  • Probabilistic Modeling

    • Logistic regression outputs follow a Bernoulli distribution for binary classification.

How random variables are used in ML/AI

Our discussion of distributions goes hand in hand with random variables. In fact, I already made a reference to random variables above when I talked about “sampling from a normal or uniform distribution.”

Here are some aspects of ML/AI that rely on random variables:

  • Training/Validation Splits

    • When randomly splitting a dataset into training and validation sets (e.g., an 80/20 split), we’re sampling from a uniform distribution to determine which data points go into each set.
  • ML Algorithms

    • Random forests randomly select features and data points to build each decision tree.
    • Dropout in neural networks randomly samples which neurons to deactivate during training.
  • LLM Token Prediction

    • When an LLM predicts the next token, it outputs a probability distribution over all possible tokens.
    • The actual token selection process typically involves temperature-based sampling, where:
      • Higher temperatures make the distribution more spread out, allowing for more varied and creative outputs.
      • Lower temperatures encourages the model to select high-probability tokens, reducing randomness.

The Gaussian Distribution (Normal Distribution)

The Gaussian distribution is expressed mathematically as the following PDF (Probability Density Function):

f(x)=12πσ2e−(x−μ)22σ2 f(x) = \frac{1}{\sqrt{2\pi\sigma^2}} e^{-\frac{(x-\mu)^2}{2\sigma^2}}

Where f(x)f(x) is the value of the probability distribution for some xx, and there are two parameters:

  • Mean μ\mu: The center of the distribution.
  • Standard deviation σ\sigma: Measures the spread or variability.
Gaussian Distribution with Mean 0 and Standard Deviation 1
The Gaussian (Normal) Distribution with mean = 0 and standard deviation = 1.

I know it looks wild, but it’s really not. The basic form is:

f(x)=e−x2 f(x) = e^{-x^2}

We could plot this and see the well-known bell curve shape of the normal distribution.

Finally, we can turn this back into the full Gaussian by adding some parameters:

f(x)=αe−βxμ2 f(x) = \alpha e^{-\beta x_{\mu}^2}

Where:

  • α=12πσ2\alpha = \frac{1}{\sqrt{2\pi\sigma^2}}
  • β=12σ2\beta = \frac{1}{2\sigma^2}
  • xμ=x−μx_{\mu} = x - \mu

Many things in nature follow a Gaussian distribution, like human height measurements, IQ scores, and blood pressure readings – to name a few.

The real significance of the normal distribution, however, comes from the Central Limit Theorem.

The Central Limit Theorem

For independent, identically distributed samples with finite mean μ\mu and finite, nonzero variance σ2\sigma^2, the Central Limit Theorem says that the standardized sample mean n(Xˉn−μ)/σ\sqrt{n}(\bar{X}_n-\mu)/\sigma converges in distribution to a standard normal as sample size nn grows. For large samples, the unstandardized mean is approximately normal with mean μ\mu and variance σ2/n\sigma^2/n.

This is a pretty weird thing to wrap your head around. Let’s consider how this applies to a really simple example: a weighted coin that gives a 90% chance of heads and a 10% chance of tails.

If we flip it 100 times, we expect 90 heads and 10 tails, but of course, what we actually get is probably something different. Let’s say that we get 85 heads and 15 tails. Then we repeat it again, and this time we get 93 heads and 7 tails.

If we keep repeating this, we’ll generate a dataset that (get this) is normally distributed (mic drop).

Consider this set of trials, where each trial has 100 measurements:

Trial Heads Tails
1 85 15
2 93 7
3 88 12
4 91 9
5 87 13
6 92 8
7 89 11
8 86 14
9 94 6
10 90 10

The heads measurements are normally distributed around 90, and the tails measurements are normally distributed around 10.

Central Limit Theorem Evolution - Means of Weighted Coin Flips
Simulating the weighted coin flip example above as we increase the number of trials. Note that each trial includes 1,000 flips (whereas above we only did 100 flips per trial - more on that below).

This might seem intuitive, but the implications of this are pretty wild. It covers many non-Gaussian distributions, including binomial, Poisson, chi-squared and exponential distributions, when these assumptions hold. The original distribution need not have a convenient analytical formula.

The quality of the finite-sample approximation depends on the underlying distribution and sample size. In the weighted-coin example, a mean over only 10 flips is discrete and noticeably skewed. Increasing the number of flips improves the normal approximation; there is no universal sample-size threshold that works equally well for every distribution.

Central Limit Theorem Evolution - Means of Weighted Coin Flips - Low N
Simulating the weighted coin flip example above for trials of only 10 flips (the top figure). The normal approximation is poor at this sample size, even though the theorem’s assumptions hold. Notice that even with 100 flips per trial (the bottom figure) we are still seeing a slightly right-skewed distribution.

The assumptions matter. A Cauchy distribution has no finite mean or variance, so this version of the theorem does not apply to it. A large sample alone does not fix a failed assumption.

Practically speaking, even if we have no idea about the underlying distribution of our data, we can rely on the Central Limit Theorem to justify approximating the sampling distribution of the mean with a normal distribution, when its assumptions hold and the sample is large enough for an adequate approximation.

For non-analytical or unknown distributions, this property is particularly useful for statistical inference, hypothesis testing, and constructing confidence intervals.

It also explains why the normal distribution appears so frequently in real-world data:

  • Sample means from any population will be approximately normally distributed
  • Measurement errors, which are often the sum of many small random effects, tend to be normal
  • Many biological and physical phenomena that result from multiple small influences follow normal distributions

Other Common Distributions

Wow, we really got carried away there. Let’s round out this lesson with a few other distributions that we’ll see in the wild:

Bernoulli Distribution

The Bernoulli distribution models binary outcomes—events that have only two possible results (success/failure, yes/no, 1/0).

We talked about this already, with the coin flip example, but I never showed you what it looks like mathematically.

Its PMF (Probability Mass Function) is:

P(X=x)=px(1−p)1−x, where x∈{0,1} P(X = x) = p^x(1-p)^{1-x}, \text{ where } x \in \{0,1\}

Where:

  • pp is the probability of success (x = 1)
  • 1−p1-p is the probability of failure (x = 0)
Bernoulli Distribution with Probability of Success 0.7
The Bernoulli Distribution with probability of success = 0.7 and failure = 0.3.

Common applications include:

  • Click/no-click in online advertising
  • Spam/not-spam email classification
  • Patient survival/death outcome prediction in medical studies

Poisson Distribution

The Poisson distribution models the number of events occurring in a fixed interval of time or space, assuming these events occur independently at a constant average rate.

Its PMF is:

P(X=k)=λke−λk! P(X = k) = \frac{\lambda^k e^{-\lambda}}{k!}

Where:

  • λ\lambda is the average number of events in the interval
  • kk is the number of events we’re calculating the probability for
  • ee is Euler’s number
Poisson Distribution with Lambda Equal to 3
The Poisson Distribution with lambda = 3 (average event rate).

Common applications include:

  • Number of customers arriving at a store per hour
  • Number of defects in a length of material
  • Number of network packets arriving at a router

Chi-Squared Distribution

The chi-squared distribution is the distribution of the sum of squares of kk independent standard normal random variables.

The last two distributions modeled discrete data, but this one (like the Gaussian) models continuous data.

Its PDF is:

f(x;k)=xk/2−1e−x/22k/2Γ(k/2) f(x; k) = \frac{x^{k/2-1}e^{-x/2}}{2^{k/2}\Gamma(k/2)}

Where:

  • kk is the degrees of freedom
  • Γ\Gamma is the gamma function
  • x>0x > 0
Chi-Squared Distribution with 4 Degrees of Freedom
The Chi-Squared Distribution with 4 degrees of freedom.

Common applications include:

  • Feature selection in machine learning
  • Hypothesis testing in model validation
  • Evaluating model residuals

Random Variates

Random variates are specific values sampled from a probability distribution. As we talked about at the start of this section, they are needed all over place in ML/AI.

Generating true random numbers is actually pretty tricky, but we can generate pseudo-random numbers really easily.

For a uniform distribution:

import numpy as np
u = np.random.uniform(0, 1)
print(u)

# Output (example): 0.23850876315526814

We can also use numpy to generate us a (pseudo) random samples from a normal distribution:

mu = 0
sigma = 1
samples = np.random.normal(mu, sigma, size=10)
print(samples)

# Output (example):
# [-1.15792309 -0.89141746 -0.52147722  0.17207065 -0.8497819   2.0878442
#  0.16309437  0.3698146  -1.04814567 -1.81385651]

For the normal distribution, this can actually be done in quite an interesting and straightforward way[1]:

def box_muller():
    """
    Box-Muller Transform: Take two uniform random numbers and convert them to two normal random numbers
    """
    u1 = np.random.uniform(0, 1)
    u2 = np.random.uniform(0, 1)
    z1 = np.sqrt(-2 * np.log(u1)) * np.cos(2 * np.pi * u2)
    z2 = np.sqrt(-2 * np.log(u1)) * np.sin(2 * np.pi * u2)
    return z1, z2


print(box_muller())

# Output (example):
# (-1.5272703953672073, -0.9528606882956586)
Box Muller Algorithm for Random Normal Variates - Visualization
Box Muller algorithm visualization, generated on-film during Claude Sub Agents ZazenCodes video.

However, numpy actually uses faster methods under the hood to sample from a normal distribution.

Generally speaking, distributions are sampled using efficient numerical methods that are optimized for each particular distribution!

Conclusion

If you can’t tell, I’m one of those people who likes talking about probability and stats at the dinner table.

Did you know that the probability of getting dealt a royal flush in poker is about 1 in 650,000? You’re literally more likely to be struck by lightning. Twice. (Chances of getting struck twice are ~1/15k x ~1/15k = 1/225k, over your lifetime.)

People looooove talking math & stats. They definitely don’t think I’m super annoying.

Key Takeaways

📊 Distributions help characterize patterns in data.

🔔 The Gaussian distribution appears frequently due to the Central Limit Theorem.

🎲 Random variables and their distributions are fundamental to ML/AI.

Next: Bayesian Thinking

Next up is an absolute classic dinner-table topic: bayesian thinking.

Footnotes


  1. I discovered the Box-Muller transform when writing this lesson. I find it fascinating that requires two uniform random numbers in order to work! In following the math, I discovered that a chi-squared distribution can be thought of as a standard normal distribution squared (meaning if you take a standard normal variable and square it, you get a chi-squared distribution with 1 degree of freedom). Well anyway, this chi-squared distribution is key to understanding how the loglog appears in the Box-Muller transform, and the sinsin & coscos appear when transforming from polar to Cartesian coordinates. If you’re still reading then you should really just check out this 10 minute YouTube video on the Box-Muller derivation. ↩︎

Comments (0)

No comments yet.