Random Variables and Distributions
local graph
Having a probability space to model our experiments and observations is fine and all, but in almost all of the cases, we are interested in a quantitative measure of the outcome. To give you an example, let’s consider an already familiar situation: tossing coins. Suppose that we are tossing a fair coin n times but we are only interested in the number of heads. How do we model the probability space this time?
By taking things one step at a time; first, we construct an event space by enumerating all possible outcomes in a single set, just like we already did in Section 18.2.1:

Since the coin is fair, each outcome ω has the probability P(ω) =
. This probability space (Ω,Σ,P) is nice and simple so far. Using the additivity of probability measures (see Definition 77), we can calculate the probability of any event. That is, for any A ∈ Σ, we have

where j ⋅j denotes the number of elements in a given set.
However, as mentioned, we are only interested in the number of heads. Should we just incorporate this information somewhere in the probability space? Sure, we could do that, but that would couple the elementary outcomes (that is, a series of heads or tails) with the measurements. This can significantly complicate our model.
Instead of overloading this probability space to directly deal with the desired measurements, we can do something much simpler: introduce a function X : Ω →ℕ, mapping outcomes to measurements.
These functions are called random variables, and they are at the very center of probability theory and statistics. By collecting data, we are observing random variables, and by fitting predictive models, we approximate them using the observations. Now that we understand why we need them, we are going to make this notion mathematically precise.
Bookmark
19.1 Random variables
Section titled “19.1 Random variables”Hold your horses, though; it’s not that simple. Random variables are hard to understand in their general form, so we’ll slow down and focus on special cases, taking one step at a time. This is how learning is done most effectively, and we’ll follow this path as well.
Let’s deal with so-called discrete random variables (such as the above example) first, real random variables second, and the general case last.
19.1.1 Discrete random variables
Section titled “19.1.1 Discrete random variables”Following our motivating example describing the number of heads in n coin tosses, we can create a formal definition.
Definition 80. (Discrete random variables)
Let (Ω,Σ,P) be a probability space and {xk}k=1∞ be an arbitrary sequence of real numbers. The function X : Ω → {x1,x2,…} is called a discrete random variable if the sets

are events for any integer k ∈ℤ (that is, Sk ∈ Σ).
You might ask why we are requiring the sets {ω ∈ Ω : X(ω) = xk} to be events. It seems like just another technical condition, but this plays an essential role. Ultimately, we are defining random variables because we want to measure the probabilities of our observations. This condition ensures that we can do this.
To simplify our notations, we write

whenever we talk about these probabilities. Let’s see a concrete example!
In the case of the coin tossing above, our random variable is defined by

Even though we can define X in terms of formulas by

this is not needed. Often, such a thing is not even possible. Regarding our random variables, we are not interested in knowing the entire mapping, only in questions such as the probability of k heads among n tosses.
If we record the “timestamps” where the outcome is heads, we can encode each ω as a subset of {1,2,…,n}. For instance, if the 1st, 3rd, and 37th tosses are heads and the rest are tails, this is {1,3,37}. To calculate the probability of k heads, we need to count the number of k-sized subsets for a set of n elements. This is given by the binomial coefficient
. So,

We’ll see this in detail when talking about the binomial distribution, whatever it might be. For now, we are ready to generalize our random variables!
19.1.2 Real-valued random variables
Section titled “19.1.2 Real-valued random variables”What if our measurements are not discrete? For instance, suppose that we have a class of students in front of us. We are interested in the distribution of their body height. So, we pick one student at random and measure their height with our shiny new tool, which is capable of measuring height with perfect precision.
In this case, discrete random variables are not enough, but we can define something similar.
Definition 81. (Real-valued random variables)
Let (Ω,Σ,P) be a probability space. The function X : Ω → ℝ is called a random variable if the set

is an event for all a,b ∈ℝ. (That is, X−1((a,b)) ∈ Σ for all a,b ∈ℝ.)
Let’s unwrap this definition. First of all, X is a mapping from the event space Ω to the set of real numbers ℝ, as illustrated by Figure 19.1.

Figure 19.1: A real-valued random variable is a mapping from the event space to the set of real numbers
Similarly to the discrete case, we are interested in the probabilities of events such as X−1((a,b)). Again, for simplicity, we write

You can imagine X−1((a,b) as the subset of Ω that is mapped to (a,b). (In general, sets of the form X−1(A) are called inverse images.)

Figure 19.2: Inverse image of an interval
Let’s see an example right away. Suppose that we are throwing darts at a circular board on the wall. (For simplicity, assume that we are so good that we always hit the board.) As we have seen when discussing σ-algebras in higher dimensions (Section 18.2.6), we can model this by selecting

and

while

Since dart boards are subdivided into concentric circles, scoring is determined by the distance from the center. So, we might as well define our random variable by

X encodes all that we are interested in, in terms of scoring. In general, we have

What if we have more than one measurement? For instance, in the case of the famous Iris dataset (https://en.wikipedia.org/wiki/Iris_flower_data_set) (one that we have seen a few times so far), we have four measurements. Sure, we can just define four random variables, but then we cannot take advantage of all the heavy machinery we have built so far: linear algebra and multivariate calculus.
For this, we will take a look at random variables in the general case.
19.1.3 Random variables in general
Section titled “19.1.3 Random variables in general”Let’s cut to the chase.
Definition 82. (Random variables)
Let (Ω1,Σ1,P1) be a probability space and let (Ω2,Σ2) be another event space Ω2 with σ-algebra Σ2. The function X : Ω1 → Ω2 is a random variable if, for every E ∈ Σ2, the set

is a member of Σ1. (That is, X−1(E) ∈ Σ1.)
In mathematical literature, random variables are usually denoted by either capital Latin letters such as X,Y , or Greek letters (mostly starting from ξ).
Random variables essentially push probability measures forward from abstract probability spaces to more tractable ones. On the event space (Ω2,Σ2), we can define a probability measure P2 by

making it possible to transform one probability space to another while keeping the underlying probabilistic model intact.
This general case covers all the mathematical objects we are interested in for machine learning. Staying with the Iris dataset ( https://en.wikipedia.org/wiki/Iris_flower_data_set), the random variable

describes the generating distribution for the dataset, while for classification tasks, we are interested in approximating the random variable

Now we will take a deeper look at why random variables are defined this way. This will be a bit technical, so feel free to skip it. It won’t adversely affect your ability to work with random variables.
19.1.4 Behind the definition of random variables
Section titled “19.1.4 Behind the definition of random variables”So, random variables are functions, mapping the probability space onto a measurement space. The only question is, why are the sets X−1(E) so special? Let’s revisit one of our motivating examples: picking a random student and measuring their height. We are interested in questions such as the probability of a student having a body height between 155 cm and 185 cm. (If you prefer using the imperial metric system, then 155 cm is roughly 5.09 feet and 185 cm is around 6.07 feet.) Translating this into formulas, we are interested in
![( ( )) P(155 ≤ X ≤ 185) = P X − 1[155,185] .](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1757.png)
(In the above formula, I wrote the same thing using two different notations.)
So, how is X−1([155,185]) an event? To find this out, let’s look at inverse images in general.
Definition 83. (Inverse image of sets with respect to functions)
Let f : E →H be a function between the two sets E and H, and let A ⊆H be an arbitrary set. The inverse image of A with respect to the function f is defined by

We like inverse images of sets because they behave nicely under set operations.
This is formalized by the following theorem.
Theorem 121.
Let f : E → H be a function between the two sets E and H. For any A1,A2,⋅⋅⋅⊆H, the following hold:
(a)

(b)

(c)

Proof. (a) We can easily see this by simply writing out the definitions. That is, we have

which is what we had to show. (If you are not comfortable with working with sets, feel free to review Appendix C on introductory set theory.)
(b) This can be done in the same manner as (a).
(c) The De Morgan laws (Theorem 153) imply that

holds. Combining this with (a) and (b), (c) follows.
Why is this important? Recall that the Borel sets, our standard σ-algebra on real numbers (as seen in Section 18.2.3), is defined by
ℬ := σ({(−∞, x] : x ∈ ℝ}) (19.1)
These contain all the events that we are interested in regarding the measurements. Combined with our previous result, we can reveal what is not in plain sight about random variables.
Theorem 122.
Let (Ω,Σ,P) be a probability space and X : Ω →ℝ be a random variable, and let A ∈ ℬ, where ℬ is the Borel algebra defined by (23.1.4). Then, X−1(A) ∈ Σ.
That is, we can measure the probability of X−1(A) for any Borel set A. Without this, our random variables would not be that useful. To make our notations more intuitive, we write

In plain English, P(X ∈A) is the probability of our measurement X falling into the set A.
Now that we understand what all of this means, let’s see the simple proof!
Proof. This is a simple consequence of the fact that ℬ is the σ-algebra generated by sets of the form (−∞,x], and the inverse images behave nicely under set operations (as Theorem 121 suggests).
19.1.5 Independence of random variables
Section titled “19.1.5 Independence of random variables”When building probabilistic models of the external world, the assumption of independence significantly simplifies the subsequent mathematical analysis. Recall that on a probability space (Ω,Σ,P), the events A,B ∈ Σ are independent if

or equivalently,

In plain English, observing one event doesn’t change our probabilistic belief about the other.
Since a random variable X is described by events of the form X−1(E), we can generalize the notion of independence to random variables.
Definition 84. (Independence of random variables)
Let X,Y : Ω1 → Ω2 be two random variables between the probability space (Ω1,Σ1,P) and σ-algebra (Ω2,Σ2).
We say that X and Y are independent if, for every A,B ∈ Σ2,

holds.
Again, think about two coin tosses. X1 describes the first coin toss and X2 describes the other. Since the tosses are independent, no observation of the first one reveals any extra information about the second one. This is formalized by the definition above.
On the other hand, to show two dependent random variables, consider the following. We’ll roll a six-sided dice, and denote the result as X. After that, we roll with X pieces of six-sided dice and denote the sum total of their values as Y . X and Y are dependent on each other. For instance, consider that P(X = 1,Y >7) = 0, but neither P(X = 1) nor P(Y >7) are zero.
Independence is an assumption that we often make. When working with sequences of random variables represented by X1,X,2,…, we almost always assume that they are independent and identically distributed; that is, i.i.d. random variables.
Now that we understand how to work with random variables, it’s time to show how to represent them in a compact form.
Bookmark
19.2 Discrete distributions
Section titled “19.2 Discrete distributions”Let’s recap what we have learned so far. In probability theory, our goal is to first model real-life scenarios affected by uncertainty and then to analyze them using mathematical tools such as calculus.
For the latter purpose, probability spaces are not easy to work with. A probability measure is a function defined on an σ-algebra, so we can’t really use calculus there.
Random variables bring us one step closer to the solution, but they can also be difficult to work with. Even though a real-valued random variable X : Ω →ℝ maps an abstract probablity space to the set of real numbers, there are some complications. Ω can be anything, and if you recall, we might not even have a tractable formula for X.
For example, if X denotes the lifetime of a lightbulb, we don’t have a formula. So, again, we can’t use calculus. However, there is a way to represent the information contained by a random variable in a sequence, a vector-scalar function, or a scalar-scalar function.
Enter probability distributions and density functions.
Consider a simple experiment, such as tossing a fair coin n times and counting the number of heads, denoting it with X. As we have seen before in Definition 80, X is a discrete random variable with

However, the sequence {P(X = k)}k=0n fully describes the random variable X!
Think about it. As our event space is Ω = {0,1,…,n}, any event is of the form A = {a1,a2,…,al}⊂ Ω for some l ≤n + 1. Thus,

where we used the (
-)additivity of probability. The sequence {P(X = k)}k=0n is all the information we need.
As a consequence, instead of working with X : Ω →ℕ, we can forget about it and use only {P(X = k)}k=0n. Why is this good for us?
Because sequences are awesome. As opposed to the mysterious random variables, we have a lot of tools to work with them. Most importantly, we can represent them in a programming language as an array of numbers. We can’t do such a thing with pure random variables.
Definition 85. (Probability mass function)
Let X be a real-valued discrete random variable. The function pX : ℝ → [0,1] defined by

is called the probability mass function (or PMF in short) of the discrete random variable X.
In general, a sequence of real numbers defines a discrete distribution if its elements are non-negative and it sums up to one.
Definition 86. (Discrete probability distribution)
Let {pk}k=1∞ be a sequence of real numbers. We say that {pk} is a discrete probability distribution if
(a) pk ≥ 0 for all k,
(b) and ∑ k=1∞pk = 1.
Remark 12.
Note that if the random variable assumes finitely many values (such as in our coin tossing example before), only finitely many values are nonzero in the distribution.
As recently hinted, every discrete random variable X defines the distribution {P(X = xk)}k=1∞, where {x1,x2,…} are the possible values that X can take. This also holds in the reverse direction: given a discrete distribution p = {pk}k=1∞, we can construct a random variable X whose probability mass function (PMF) is p.
Thus, the probability mass function of X is also referred to as its distribution. I know, it is a bit confusing, as the word “distribution” is quite overloaded in math. You’ll get used to it.
These discrete probability distributions are well suited for performing quantitative analysis, as opposed to the base form of random variables. As an additional benefit, think about how distributions generalize random variables. No matter whether we talk about coin tosses or medical tests, the rate of success is given by the above discrete probability distribution.
Before moving on to discussing the basic properties of discrete distributions, let’s see some examples!
19.2.1 The Bernoulli distribution
Section titled “19.2.1 The Bernoulli distribution”Let’s start the long line of examples with the most basic probability distribution possible: the Bernoulli distribution, describing a simple coin-tossing experiment. We are tossing a coin having probability p of coming up heads and probability 1 −p of coming up tails. The experiment is encoded in the random variable X, which takes the value 1 if the toss results in heads, 0 otherwise:

Thus,

When a random variable X is distributed according to this, we write

where p ∈ [0,1] is a parameter of the distribution.
Remark 13. (An alternative form of the Bernoulli distribution)
There is a clever alternative formulation of the Bernoulli distribution that gets rid of the if-else definition. As k is either zero or one, P(X = k) can be written as

Keep this form in mind, as it’ll be extremely useful later down the line.
It’s time to talk about distributions in practice. There are several stats packages for Python, but we’ll use the almighty scipy (which is not exactly a stats package, but it has an excellent statistical module):
from scipy.stats import bernoulliWe can generate random values using the rvs method of the bernoulli object (just like for any other distribution from scipy):
[bernoulli.rvs(p=0.5) for _ in range(10)] # ten Bernoulli(0.5)-distributed random numbers[1, 1, 1, 1, 0, 1, 0, 1, 1, 0]In scipy, the probability mass function is implemented in the pmf method.
We can even visualize the distribution using Matplotlib:
import matplotlib.pyplot as plt
params = [0.25, 0.5, 0.75]
with plt.style.context("seaborn-v0_8"): fig, axs = plt.subplots(1, len(params), figsize=(4*len(params), 4), sharey=True) fig.suptitle("The Bernoulli distribution") for ax, p in zip(axs, params): x = range(2) y = [bernoulli.pmf(k=k, p=p) for k in x] ax.bar(x, y) ax.set_title("fp = {p}") ax.set_ylabel("P(X = k)") ax.set_xlabel("k") plt.show()
Figure 19.3: The Bernoulli distribution
If you are interested in the details, feel free to check out the SciPy documentation ( https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.bernoulli.html) for further methods!
19.2.2 The binomial distribution
Section titled “19.2.2 The binomial distribution”Let’s take our previous coin-tossing example one step further. Suppose that we toss the same coin n times, and X denotes the number of heads out of n tosses. What is the probability of getting exactly k heads?
Say, n = 5 and k = 3. For example, the configuration 11010 (where 0 denotes tails and 1 denotes heads) has the probability p3(1 −p)2, as there are three heads and two tails from five independent (Definition 84) tosses.
How many such configurations are available? Selecting the position of the three heads is the same as selecting a three-element subset out of a set of five elements. Thus, there are
possibilities. In general, there are
possibilities for selecting a k-element subset out of a set of n elements.
Combining this, we have

This is called the binomial distribution, one of the most frequently encountered ones in probability and statistics. In notation, we write

where the n ∈ℕ and p ∈ [0,1] are its two parameters. Let’s visualize the distribution!
from scipy.stats.distributions import binom
params = [(20, 0.25), (20, 0.5), (20, 0.75)]
with plt.style.context("seaborn-v0_8"): fig, axs = plt.subplots(1, len(params), figsize=(4*len(params), 4), sharey=True) fig.suptitle("The binomial distribution") for ax, (n, p) in zip(axs, params): x = range(n+1) y = [binom.pmf(n=n, p=p, k=k) for k in x] ax.bar(x, y) ax.set_title("fn = {n}, p = {p}") ax.set_ylabel("P(X = k)) ax.set_xlabel("k")
plt.show()
Figure 19.4: The binomial distribution
19.2.3 The geometric distribution
Section titled “19.2.3 The geometric distribution”A bit more coin tossing. We toss the same coin until a heads turn up. Let X denote the number of tosses needed. With some elementary probabilistic thinking, we can deduce that

(Since if heads turn up first for the k-th toss, we tossed k − 1 tails previously.) This is called the geometric distribution and is denoted as

with p ∈ [0,1] being the only parameter. Similarly, we can plot the histograms to visualize the distribution family:
from scipy.stats import geom
params = [0.2, 0.5, 0.8]
with plt.style.context("seaborn-v0_8"): fig, axs = plt.subplots(1, len(params), figsize=(5*len(params), 5), sharey=True) fig.suptitle("The geometric distribution") for ax, p in zip(axs, params): x = range(1, 20) y = [geom.pmf(p=p, k=k) for k in x] ax.bar(x, y) ax.set_title(f"p = {p}") ax.set_ylabel("P(X = k)") ax.set_xlabel("k")
plt.show()
Figure 19.5: The geometric distribution
Note that none of the probabilities P(X = k) are zero, but as k grows, they become extremely small. (The closer p is to 1, the faster the decay.)
It might not be immediately obvious that ∑ k=1∞(1 −p)k−1p = 1. To do that, we’ll apply a magic trick. (You know. Paraphrasing the famous Arthur C. Clarke quote, “Any sufficiently advanced mathematics is indistinguishable from magic.”)
In fact, for an arbitrary x ∈ (−1,1), the astounding identity
.png)
(19.2)
holds.
This is the famous geometric series. Using (23.2.3), we have

Using the geometric series is one of the most common tricks up a mathematician’s sleeve. We’ll use this, for instance, when talking about expected values for certain distributions.
19.2.4 The uniform distribution
Section titled “19.2.4 The uniform distribution”Let’s discard the coin and roll a six-sided dice instead. We’ve seen this before: the probability of each outcome is the same, that is,

where X denotes the outcome of the roll. This is a special instance of the uniform distribution.
In general, let A = {a1,a2,…,an} be a finite set. The discrete random variable X : Ω →A is uniformly distributed on A, that is,

if

Note that A must be a finite set: no discrete uniform distribution exists on infinite sets. When we have an uniform distribution on {1,2,…,n}, we often abbreviate it as Uniform(n).
Here is the probability mass function for rolling a six-sided dice. Not the most exciting one, I know:
from scipy.stats import randint
with plt.style.context("seaborn-v0_8"): fig = plt.figure(figsize=(10, 5)) plt.title("The uniform distribution"
x = range(-1, 9) y = [randint.pmf(k=k, low=1, high=7) for k in x] plt.bar(x, y) plt.ylim(0, 1) plt.ylabel("P(X = k)") plt.xlabel("k")
plt.show()
Figure 19.6: The (discrete) uniform distribution
19.2.5 The single-point distribution
Section titled “19.2.5 The single-point distribution”We’ve left the simplest one till last: the single-point distribution. For that, let a ∈ℝ be an arbitrary real number. We say that the random variable X is distributed according to δ(a) if

That is, X assumes a with probability 1. Their corresponding cumulative distribution function is

which is a simple step function with a single jump.
Trust me, explicitly naming such a simple distribution is immensely useful. There are two main reasons that come to mind. First, the single-point distribution often arises as the limit distribution of sequences of random variables.
Second, every discrete distribution can be written in terms of single-point distributions. This is not absolutely necessary for you to understand right now, but it’ll be essential on a more advanced level.
Remark 14. (Discrete distributions as the linear combination of single-point distributions)
Let (Ω,Σ,P) be a probability space and let X : Ω →{x1,x2,…} be a discrete random variable with probability mass function pi = P(X = xi).
By introducing the single-point distributions Xi ∼δ(xi), we have

This decomposition can be extremely useful.
19.2.6 Law of total probability, revisited once more
Section titled “19.2.6 Law of total probability, revisited once more”With the help of discrete random variables, we can dress the law of total probability (Theorem 117) in new clothes.
Theorem 123. (Law of total probability, discrete random variable version)
Let (Ω,Σ,P) be a probability space and let A ∈ Σ be an arbitrary event. If X : Ω →{x1,x2,…}is a discrete random variable, then
P(A) = ∑k=1∞ P(A | X = xk) P(X = xk). (19.3)
Proof. For any discrete random variable X : Ω → {x1,x2,…}, the events {X = xk} partition the event space: they are mutually disjoint, and their union gives Ω. Thus, the law of total probability can be applied, obtaining

which is what we had to prove.
In other words, we can study events in the context of discrete random variables. This is extremely useful in practice. (Soon, we’ll see that it’s not only for the discrete case.)
Let’s put (19.3) to work right away.
19.2.7 Sums of discrete random variables
Section titled “19.2.7 Sums of discrete random variables”Since discrete probability distributions are represented by sequences, we can use a wide array of tools from mathematical analysis to work with them. (This was the whole reason behind switching random variables to distributions.) As a consequence, we can easily describe more complex random variables by constructing them from simpler ones.
For instance, consider rolling two dice, where we are interested in the distribution of the sum. So, we can write this as the sum of random variables X1 and X2, denoting the outcome of the first and second toss, respectively. We know that

for i = 1,2. Using (19.3) and the fact that the two outcomes are independent, we have

If this looks familiar, it is not an accident.
What you see here is the famous convolution operation in action.
Definition 87. (Discrete convolution)
Let a = {ak}k=−∞∞ and b = {bk}k=−∞∞ be two arbitrary sequences. Their convolution is defined by

That is, the k-th element of the sequence a ∗b is defined by the sum ∑ l=−∞∞ak−lbl. This might be hard to imagine, but thinking about the probabilistic interpretation makes the definition clear. The random variable X1 + X2 can assume the value k if X1 = k −l and X2 = l, for all possible l ∈ℤ.
Remark 15. Remark 19.2.4 (Switching up the indices)
Due to symmetry,

Thus, an alternative definition of a ∗b

This trick is often extremely useful, as when ak and bk is explicitly given, sometimes ∑ l=−∞∞albk−l is simpler to calculate than ∑ l=−∞∞ak−lbl, and vice versa.
Convolution is supported by NumPy, so with its help, we can visualize the distribution of our X1 + X2:
import numpy as np
dist_1 = [0, 1/6, 1/6, 1/6, 1/6, 1/6, 1/6]dist_2 = [0, 1/6, 1/6, 1/6, 1/6, 1/6, 1/6]sum_dist = np.convolve(dist_1, dist_1)
with plt.style.context("seaborn-v0_8"): plt.figure(figsize=(10, 5)) plt.bar(range(0, len(sum_dist)), sum_dist) plt.title("Distribution of X1 + X2") plt.ylabel("P(X1 + X1 = k)") plt.xlabel("k") plt.show()
Figure 19.7: Distribution of the sum of two random variables
Let’s talk about the general case. The pattern is clear, so we can formulate a theorem.
Theorem 124. (Sums of discrete random variables.)
If X,Y : Ω → ℤ are both integer-valued random variables, then the distribution of X + Y is given by the convolution of the respective distributions:

that is,

Proof. The proof is a straightforward application of the law of total probability (19.3):
P(X + Y = k) = ∑ l=−∞∞P(X + Y = k∣Y = l)P(Y = l) = ∑ l=−∞∞P(X = k −l)P(Y = l) = (pX ∗pY )(k),
which is what we had to prove.
Another example of random variable sums is the binomial distribution itself. Instead of thinking about the number of successes of an experiment out of n independent tries, we can model the core experiment as a Bernoulli distribution. That is, if Xi is a Bernoulli(p) distributed random variable describing the success of the i-th attempt, we have

where the sum ∑ i1+⋅⋅⋅+in=k traverses all tuples (i1,…,in) ∈{0,1}n for which i1 + ⋅⋅⋅ + in = k. (As there are
of such tuples, we have ∑ i1+⋅⋅⋅+in=kpk(1 −p)n−k =
pk(1 −p)n−k in the last step.)
Bookmark
19.3 Real-valued distributions
Section titled “19.3 Real-valued distributions”So far, we have talked about discrete random variables, that is, random variables with countably many values. However, not all experiments/observations/measurements are like this. For instance, the height of a person is a random variable that can assume a continuum of values.
To give a tractable example, let’s pick a number X from [0,1], with each one having an “equal chance.” In this context, equal chance means that

Can we describe X with a single real function? As in the discrete case, we can try

but this wouldn’t work. Why?
Because for each x ∈X, we have P(X = x) = 0. That is, picking a particular number x has zero probability. Instead, we can try FX(x) = P(X ≤x), which is

We can plot this for visualization:
from scipy.stats import uniformX = np.linspace(-0.5, 1.5, 100)y = uniform.cdf(X)
with plt.style.context(’seaborn-v0_8’): plt.figure(figsize=(10, 5)) plt.title("The uniform distribution") plt.plot(X, y) plt.show()
Figure 19.8: The uniform distribution
In the following section, we will properly define and study this object in detail for all real-valued random variables.
19.3.1 The cumulative distribution function
Section titled “19.3.1 The cumulative distribution function”What we have seen in our motivating example is an instance of a cumulative distribution function, or CDF in short. Let’s jump into the formal definition right away.
Definition 88. (Cumulative distribution function)
Let X be a real-valued random variable. The function defined by
FX(x) := P(X ≤ x) (19.4)
is called the cumulative distribution function (CDF) of X.
Again, let’s unpack this. Recall that in the definition of real-valued random variables (Definition 81), we have used the inverse images X−1((a,b)).
Something similar is going on here. P(X ≤x) is the abbreviation for P(X−1((−∞,x])), which we are too lazy to write. Similarly to X−1((a,b))), you can visualize X−1((−∞,x])) by pulling the interval (−∞,x] back to Ω using the mapping X.
Sets of the form X−1((−∞,x]) are called the level sets of X.

Figure 19.9: The level set of a random variable
According to the Oxford English Dictionary, the word cumulative means “increasing or increased in quantity, degree, or force by successive additions.” For discrete random variables, using P(X = k) was enough, but since real random variables are more nuanced, we have to use the cumulative probabilities P(X ≤x) to meaningfully describe them.
Why do we like to work with distribution functions? Because they condense all the relevant information about a random variable in a real function.
For instance, we can express probabilities like

To give an example, let’s revisit the introduction, where we were selecting a random number between zero and one. There, the random variable X with CDF
.png)
(19.5)
is said to be uniformly distributed over [0,1], or X ∼ Uniform(0,1) in short. We’ll see a ton of examples later, but keep note of this, as the uniform distribution will be our textbook example throughout this section.
19.3.2 Properties of the distribution function
Section titled “19.3.2 Properties of the distribution function”Cumulative distribution functions have three properties that characterize them: they are always non-decreasing, right-continuous (whatever that might be), and their limits are 0 and 1 toward −∞ and ∞ respectively. You might have guessed some of this from the definition, but here is the formal theorem that summarizes this.
Theorem 125. (Properties of CDFs)
Let X be a real-valued random variable with CDF FX. Then, FX is
(a) non-decreasing (that is, x ≤y implies FX(x) ≤FX(y)),
(b) right-continuous (that is, limx→x0+FX(x) = FX(x0), or in other words, taking the right limit is interchangeable with FX),
(c) and the limits

hold.
Proof. The proofs are relatively straightforward. (a) follows from the fact that if x>y, then we have
![ ( ) ( ) X −1 (− ∞, x] ⊆ X −1 (− ∞, y]. ](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1837.png)
In other words, the event X ≤ x is a subset of X ≤ y. Thus, due to the monotonicity of probability measures, we have P(X ≤ x) ≤ P(X ≤y).
(b) Here, we need to show that limx→x0+P(X ≤ x) = P(X ≤ x0). For this, note that for any xn → x0 with xn>x0, the event sequence {ω ∈ Ω : X(ω) ≤xn} is decreasing, and
![∩∞ X− 1((− ∞, xn]) = X− 1((− ∞, x0]). n=1 ](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1838.png)
Because of the upper continuity of probability measures (see Theorem 115), the right continuity of FX follows.
(c) Again, this follows from the fact that
![ ( ) ∩ ∞n=1X −1 (− ∞, n ] = ∅ ](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1839.png)
and
![∪∞n=1X −1((− ∞, n]) = Ω. ](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1840.png)
Since P(∅) = 0 and P(Ω) = 1, the statement follows from the upper and lower continuity of probability measures. (See Theorem 114 and Theorem 115.)
Remark 16. (Alternative definition of CDF-s)
In the literature, you can sometimes find that instead of (19.4), the CDF of X is defined by

that is, X>x instead of X ≤ x. This doesn’t change the big picture, but some details are slightly different. For instance, this change makes FX left-continuous instead of right-continuous. These minute details matter if you dig really deep, but in machine learning, we’ll be fine without thinking too much about them.
Theorem 125 is true the other way around: if you give me a non-decreasing right-continuous function F(x) with limx→−∞F(x) = 0 and limx→∞F(x) = 1, I can construct a random variable such that its distribution function matches F(x).
19.3.3 Cumulative distribution functions for discrete random variables
Section titled “19.3.3 Cumulative distribution functions for discrete random variables”The discrete and real-valued case is not entirely disjoint: in fact, discrete random variables have cumulative distribution functions as well. (But not the other way around; that is, real-valued random variables cannot be described with sequences.)
Say, if X is a discrete random variable taking the values x1,x2,…, then its CDF is

which is a piecewise continuous function. For example, Figure 19.10 illustrates the CDF of the binomial distribution.

Figure 19.10: The CDF of Binomial(10,0.5)
The strength or probability lies in its ability to translate real-world phenomena into coin tosses, dice rolls, dart throws, lightbulb lifespans, and many more. This is possible because of distributions. Distributions are the ribbons stringing together a vast bundle of random variables.
Let’s meet some of the most important ones!
19.3.4 The uniform distribution
Section titled “19.3.4 The uniform distribution”We have already seen a special case of the uniform distribution: selecting a random number from the interval [0,1], such that all outcomes are “equally likely.” The general uniform distribution captures the same concept, except on an arbitrary interval [a,b] for any a>b. That is, the random variable X is uniformly distributed on the interval [a,b], or X ∼ Uniform(a,b) in symbols, if
![ | | P (α <X ≤ β ) = -1—||[a,b]∩(α,β ]|| b− a ](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1844.png)
for all α <β, where |[c,d]| denotes the length of the interval [c,d],
In other words, the probability of our random number falling into a given interval is proportional to the interval’s length. This is how the condition “equally likely” makes sense: as there are uncountably many possible outcomes, the probability of each individual outcome is zero, but equally long intervals have an equal chance.
In line with the definition, the distribution function of X is

19.3.5 The exponential distribution
Section titled “19.3.5 The exponential distribution”Let’s turn our attention toward a different problem: lightbulbs. According to some mysterious (and probably totally inaccurate) lore, lightbulbs possess the so-called memoryless property. That is, their expected lifespan is the same at any point in their life.
To put this into a mathematical form, let X be a random variable denoting the lifespan of a given lightbulb. The memoryless property states that if the lightbulb has already lasted s seconds, then the probability of lasting another t is the same as in the very first moment of its life. That is,

Expanding the left side, we have

as {X>t + s}∩{X>s} = {X>t + s}. Thus, the memoryless property implies that
P(X > t + s) = P(X > t) P(X > s). (19.6)
If we think about the probabilities as a function f(t) = P(X>t), (19.6) can be viewed as a functional equation. And a famous one at that. Without going into the painful details, the only continuous solution is the exponential function f(t) = eat, where a ∈ℝ is a parameter.
As we are talking about the lifespan of a lightbulb here, the probability of it lasting forever is zero. That is,

holds. Thus, as

only the negative parameters are valid in our case. This characterizes the exponential distribution. In general, X ∼ exp(λ) for a λ>0 if

Let’s plot this for visualization!
from scipy.stats import exponX = np.linspace(-0.5, 10, 100)params = [0.1, 1, 10]ys = [expon.cdf(X, scale=1/l) for l in params]
with plt.style.context(’seaborn-v0_8’): plt.figure(figsize=(10, 5))
for l, y in zip(params, ys): plt.plot(X, y, label=f"lambda = {l}")
plt.title("The exponential distribution") plt.legend() plt.show()
Figure 19.11: The exponential distribution
The exponential distribution is extremely useful and frequently encountered in real-life applications. For instance, it models the requests incoming to a server, customers standing in a queue, buses arriving at a bus stop, and many more.
We’ll talk more about special distributions in later chapters, and we’ll add quite a few others as well.
19.3.6 The normal distribution
Section titled “19.3.6 The normal distribution”You have probably seen the bell curve at one point in your life, as it is used to describe a wide range of statistical phenomena. Salaries, prices, height, intelligence: they all seem to follow the same symmetric bell-shaped distribution.
This is described by the famous normal distribution: we say that X is normally distributed, or X ∼𝒩(μ,σ2), if

where μ,σ ∈ℝ. The parameter μ is called the mean of X, while σ2 is its variance and σ is its standard deviation. (We’ll see more about these quantities when talking about the expected value and variance in Chapter 20.)
Let’s see the plot the inner part first, which you know as the famous bell curves:
from scipy.stats import normX = np.linspace(-10, 10, 1000)sigmas = [0.5, 1, 2, 3]ys = [norm.pdf(X, scale=sigma) for sigma in sigmas]
with plt.style.context('seaborn-v0_8'): plt.figure(figsize=(10, 5))
for sigma, y in zip(sigmas, ys): plt.plot(X, y, label=f"sigma = {sigma}")
plt.title("The bell curves") plt.savefig("bell_curve.png", dpi=300) plt.legend() plt.show()
Figure 19.12: The bell curves
Surprisingly, no closed expression exists for its CDF

No, it’s not that mathematicians were not smart enough to figure it out; it provably doesn’t exist. In the ancient days, statisticians used to read out its values from statistical tables, located in massive tomes.
Now, let’s plot FX:
X = np.linspace(-10, 10, 1000)sigmas = [0.5, 1, 2, 3]ys = [norm.cdf(X, scale=sigma) for sigma in sigmas]
with plt.style.context(’seaborn-v0_8’): plt.figure(figsize=(10, 5))
for sigma, y in zip(sigmas, ys): plt.plot(X, y, label=f"sigma = {sigma}")
plt.title("The normal distribution") plt.legend()
plt.show()
Figure 19.13: The normal distribution
Normal distribution is the single most important one in statistics, and we’ll see it appearing everywhere, not just in practice but in theory as well.
To sum up, distributions are the lifeblood of probability theory, and distributions can be represented with cumulative distribution functions.
However, CDFs have a significant drawback: it’s hard to express the probability of more complex events with them. Later, we’ll see several concrete examples of where CDFs fail.
Without going into details, one example points toward multidimensional distributions. (I hope that their existence and importance are not surprising to you.) There, the distribution functions can be used to express the probability of rectangle-shaped events, but not, say, spheres.
To be a bit more precise, if X,Y ∼ Uniform(0,1), then the probability

cannot be directly expressed in terms of the two-dimensional CDF FX,Y (x,y) (whatever that may be). Fortunately, this is not our only tool. Recall the e−
part inside the CDF of the normal distribution? This is a special instance of density functions, which is what we’ll learn about in the next section.
Bookmark
19.4 Density functions
Section titled “19.4 Density functions”Distribution functions are not our only tool to describe real-valued random variables. If you have studied probability theory from a book/lecture/course written by a non-mathematician, you have probably seen a function such as

referred to as “probability” at some point. Let me tell you, this is definitely not a probability. I have seen this mistake so much that I decided to write short X/Twitter threads properly explaining probabilistic concepts, from which this book was grown out of. So, I take this issue to heart.
Here is the problem with cumulative distribution functions: they represent global information about local objects. Let’s unpack this idea. If X is a real-valued random variable, the CDF

describes the probability of X being smaller than a given x. But what if we are interested in what happens around x? Say, in the case of the uniform distribution (19.5), we have

(We used Theorem 115 when taking the limit.)
Thus, as we have already seen, the probability of picking a particular point is zero. Contrary to the discrete case, P(X = x) tells us nothing about how the distribution of X behaves around x.
And the worst thing is, this is the same for a wide array of distributions. For instance, you can check it manually for the exponential distribution.
Isn’t this strange? The probability of individual outcomes is zero for both the uniform and exponential distribution, yet the distributions themselves couldn’t be more different. Let’s examine the problem from another perspective. By definition,

holds. Does this look familiar to you? Increments of FX on the right, probabilities on the left. Where have we seen increments before?
In the fundamental theorem of calculus (Theorem 92), that’s where. That is, if FX is differentiable and its derivative is FX′(x) = fX(x), then
∫ab fX(x) dx = FX(b) − FX(a). (19.7)
The function fX(x) seems to be what we are looking for: it represents the local behavior of X around x. But instead of describing the probability, it describes its rate of change. This is called a probability density function.
By turning this argument around, we can define density functions using (19.7). Here is the mathematically precise version.
Definition 89. (Density functions)
Let (Ω,Σ,P) be a probability space, and X : Ω →ℝ be a real-valued random variable. The function fX : ℝ →ℝ is called the probability density function (PDF) of X, if it is integrable, and
∫ab fX(x) dx = FX(b) − FX(a) (19.8)
holds for all a,b ∈ℝ.
Again, (19.8) is the Newton-Leibniz formula (Theorem 92) in disguise.
The following theorem makes this connection precise.
Theorem 126. (The density function as derivative)
Let X be a real-valued random variable. If the cumulative distribution function FX(x) is everywhere differentiable, then

is a density function for X.
Proof. This is just a simple application of the fundamental theorem of calculus (Theorem 92). If the derivative indeed exists, then

which means that fX(x) =
FX(x) is indeed a density function.
Remark 17. (Density functions are not unique)
Note that density functions are not unique. If X is a random variable with density fX, then, say, modifying fX at a single point still functions as a density function for X.
To be more precise, define

You can check by hand that fX∗ is still a density for X, yet fX≠fX∗.
One more thing before we move on. Recall that discrete random variables are characterized by probability mass functions (Definition 85). Mass functions and densities are two sides of the same coin.
The probability mass function is analogous to the density function, yet we don’t have terminology for random variables with the latter. We’ll fix this now.
Definition 90. (Continuous random variables)
Let (Ω,Σ,P) be a probability space, and X : Ω →ℝ be a real-valued random variable. We say that X is continuous if it has a probability density function.
Discrete and continuous random variables are the backbones of probability theory: the most interesting random variables are falling into either of these two classes. (Later in the chapter, we’ll see that there are more types, but these two are the most important.)
Now we are ready to get our hands dirty and see some density functions in practice.
19.4.1 Density functions in practice
Section titled “19.4.1 Density functions in practice”After all this introduction, let’s see a few concrete examples. So far, we have seen two real-valued non-discrete distributions: uniform and exponential.
Example 1. Let’s start with X ∼ Uniform(0,1). Can we apply Theorem 126 directly? Not without a little snag. Or two, to be more precise.
Why? Because the distribution function

is not differentiable at x = 0 and x = 1. However, it is differentiable everywhere else, and its derivative

is indeed a density function. (You can check this by hand.) This density is patched together from the derivative of FX(x) on the intervals (−∞,0), (0,1), and (1,∞).

Figure 19.14: Density function of the uniform distribution on [0,1]
Example 2. In the case of the exponentially distributed random variable Y ∼ exp(λ), the function

is a proper density function, which we obtained by differentiating FY (x) whenever possible. Again, the density fX(x) is patched together from the derivatives on the intervals (−∞,0) and (0,∞).

Figure 19.15: Density function of the exp(1) distribution
Example 3. Now, I am going to turn everything upside down. Let Z ∼ Bernoulli(1∕2), which is a discrete random variable with probability mass function

and cumulative distribution function

Like the uniform and exponential distributions, this CDF is also differentiable except for a few points (which are 0 and 1).
Thus, it is natural to guess that, like before, we can patch its derivatives together to obtain a density function. However, there is a bigger snag: the derivative of FZ is zero, at least wherever it exists. It turns out that Z does not have a density function at all!
What’s the issue? I’ll tell you: the jump discontinuities of FZ(x) at x = 0 and x = 1. Although the CDFs of the uniform and exponential distributions were not differentiable at finitely many points, they did not include any jump discontinuities.
We are not going to dive deep into the details, but the gist is: if there is a jump discontinuity in the CDF, the density function does not exist.
Remark 18. (The non-existence of density despite the lack of jump discontinuities)
Unfortunately, the reverse direction of “jump discontinuity in the CDF ⇒ no PDF exists” is not true, I repeat, not true.
We can find random variables whose cumulative distribution functions are continuous, but their density does not exist. One famous example is the Cantor function (https://en.wikipedia.org/wiki/Cantor_function), also known as the Devil’s staircase. (Only follow this link if you are brave enough or well-trained in real analysis, which is the same.)
19.4.2 Classification of real-valued random variables
Section titled “19.4.2 Classification of real-valued random variables”So far, we have been focusing on two special kinds of real-valued random variables: discrete random variables (Definition 80) and continuous ones (Definition 90).
We’ve seen all kinds of objects describing them. Every real-valued random variable has a cumulative distribution function (Definition 88), but while discrete ones are characterized by probability mass functions (Definition 85), the continuous ones are by density functions (Definition 89).
Are these two all that’s out there?
No. There are mixed cases. For instance, consider the following example. We are selecting a random number from [0,1], but we add a little twist to the picking process. First, we toss a fair coin, and if it comes up heads, we pick 0. Otherwise, we pick uniformly between zero and one.
To describe this weird process, let’s introduce two random variables: let X be the final outcome and Y be the outcome of the coin toss. Then, using the conditional version of the law of total probability (see Theorem 117), we have

As

and P(X ≤x∣Y = tails) = FUniform(0,1)(x), we ultimately have

Ultimately, FX is the convex combination of two cumulative distribution functions. (A convex combination is a linear combination where the coefficients are positive and their sum is 1.)

Figure 19.16: CDF of the mixed distribution X
Thus, the random variable X is not discrete nor continuous. So, what is it?
It’s time to add order to chaos! In this section, we are going to provide a complete classification for our real-valued random variables. This is a beautiful, albeit advanced, topic so feel free to skip it on a first read.
Let’s start at a seemingly distant topic: subsets of ℝ that are so small that they practically vanish. Since ℝ is a one-dimensional object, we are usually talking about length here, but let’s forget that terminology and talk about measure instead. We’ll denote the measure of a set A ⊆ℝ by λ(A), whatever that might be.
We are not going too deep into the details and will keep on using the notion of measure intuitively. For instance, the measure of an interval [a,b] is λ([a,b]) = b−a.
Our measure λ has some fundamental properties, for instance,
- λ(∅) = 0,
- λ(A) ≤λ(B) if A ⊆B,
- and λ(∪k=1∞Ak) = ∑ k=1∞λ(Ak) if Ai ∩Aj = ∅.
This almost behaves like a probability measure, with one glaring exception: λ(ℝ) = ∞. This is not an accident.
What is the measure of a finite set {a1,…,an}? Intuitively, it is zero, and from this example, we’ll conjure up the concept of sets of zero measure.
Theorem 127. (Sets of zero measure)
Let A ⊆ℝ be an arbitrary set. Suppose that for any arbitrarily small 𝜀>0, there exists a union of intervals E = ∪k=1∞(ai,bi) such that
(a) λ(E)>𝜀, (b) and A ⊆E,
then, λ(A) = 0.
Proof. As A ⊆E, λ(A) ≤λ(E) 𝜀. This means that λ(A) is smaller than any positive real number, thus it must be zero.
Let’s see some examples.
Example 1. A set of a single element has zero measure. As any {a} can be covered by the interval (a−𝜀,a + 𝜀) for some 𝜀>0. As λ((a−𝜀,a + 𝜀)) = 2𝜀, the conditions of Theorem 127 apply, thus λ({a}) = 0.
Example 2. A finite set has zero measure. To see this, let A = {a1,…,an} be our finite set. The system of intervals

will do the job, as the intervals are mutually disjoint for a small enough 𝜀,
thus

Example 3. A countable set has zero measure. For any A = {a1,a2,…}, the system of intervals

work perfectly, as

For instance, as the set of integers and rational numbers are both countable, λ(ℤ) = λ(ℚ) = 0.
Overall, sets of zero measure are true to their name: they are small. (They are not necessarily countable though.) Why are these important? We’ll see this in the next section.
Remark 19. (Density functions are not unique, take two)
Do you recall Remark 17, where we saw that changing the density function of X at a single point is also a density for X?
Turns out that you can actually modify fX at an entire set of measure zero. Say,

is still a density function for X. Unfortunately, we don’t have the tools to show this, as it would require moving beyond the good old Riemann integral, which is way beyond our scope.
The main difference between a discrete and a continuous random variable is the set where they live. Fundamentally, they are both real-valued random variables, but the range of a discrete variable is a set of measure zero.
Let’s introduce the concept of singular random variables to make this notion precise.
Definition 91. (Singular random variables)
Let (Ω,Σ,P) be a probability space and X : Ω →ℝ be a real-valued random variable. We say that X is singular if its range X(Ω) = {X(ω) : ω ∈ Ω}⊆ℝ is a set of zero measure, that is,

holds.
All discrete random variables are singular, but not the other way around. For instance, the Cantor function (https://en.wikipedia.org/wiki/Cantor_function) is a good example.
Why are singular random variables so special? Because every distribution can be written as the sum of a singular and a continuous one! Here is the famous Lebesgue decomposition theorem.
Theorem 128. (Lebesgue’s decomposition theorem)
Let (Ω,Σ,P) be a probability space and X : Ω →ℝ be a real-valued random variable. Then, there exists a singular random variable Xs and a continuous random variable Xc such that

where α + β = 1, and FX, FXs, FXc are the corresponding cumulative distribution functions.
We are not going to prove this here but the gist is this: there are singular random variables, continuous ones, and their sum.
Bookmark
19.5 Summary
Section titled “19.5 Summary”With the introduction of random variables, we learned to represent abstract probability spaces as random variables, mapping a sufficiently expressive collection of events to the real numbers. Instead of σ-algebras and probability measures, now we can deal with numbers. As I told you, “The strength or probability lies in its ability to translate real-world phenomena into coin tosses, dice rolls, dart throws, lightbulb lifespans, and many more.”
Most common random variables come in two forms: discrete or continuous, meaning that either it can be described with a probability mass function

or with a density function fX, satisfying

Translating experiments to distributions is the secret sauce of probability theory and statistics. For instance, the time between call center calls, bus arrivals, earthquakes, and insurance claims are all modeled with the exponential distribution, a mathematical object we can work with.
I know that learning takes a lifetime, but we must wrap this book up at some point. There is one more concept left that I want to tell you about: the expected value, enabling us to measure the statistical properties of our distributions. See you in the next chapter!
Bookmark
19.6 Problems
Section titled “19.6 Problems”Problem 1. Let X and Y be two independent random variables, and let a,b ∈ℝ be two arbitrary constants. Show that X −a and Y −b are also independent from each other.
Problem 2. Let X be a continuous random variable. Show that P(X = x) = 0 for any x ∈ℝ.
Problem 3. Let X ∼ Bernoulli(p) and Y ∼ Binomial(n,p). Calculate the probability distribution of X + Y .
Problem 4. Let X ∼ Bernoulli(p) be the result of a coin toss. We select a random number Y from [0,2] based on the result of the toss: if X = 0, we pick a number from [0,1] using the uniform distribution, but if X = 1, we pick a number from [1,2], once more using the uniform distribution. Find the cumulative distribution function of Y . Does Y have a density function? If yes, find it.