The Expected Value
local graph
In the last chapter, we learned about probability distributions, the objects that represent probabilistic models as sequences or functions. After all, there is the entire field of calculus to help us deal with functions, so they open up a wide array of mathematical tools.
However, we might not need all the information available. Sometimes, simple descriptive statistics such as mean, variance, or median suffice. Even in machine learning, loss functions are given in terms of them. For instance, the famous mean-squared error

is the variance of the prediction error. Deep down, these familiar quantities are rooted in probability theory, and we’ll devote this chapter to learning about them.
Bookmark
20.1 Discrete random variables
Section titled “20.1 Discrete random variables”Let’s play a simple game. I toss a coin, and if it comes up heads, you win $1 . If it is tails, you lose $2 .
Up until now, we were dealing with questions like the probability of winning. Say, for the coin toss, whether you win or lose, we have

Despite the equal chances of winning and losing, should you play this game? Let’s find out.
After n rounds, your earnings can be calculated by the number of heads times $1 minus the number of tails times $2 . If we divide total earnings by n, we obtain your average winnings per round. That is,

where #heads and #tails denote the number of heads and tails respectively.
Recall the frequentist interpretation of probability from Section 18.2.7? According to our intuition, we should have

This means that if you play long enough, your average winnings per round is

So, as you are losing half a dollar per round on average, you definitely shouldn’t play this game.
Let’s formalize this argument with a random variable. Say, if X describes your winnings per round, we have

so the average winnings can be written as

With a bit of a pattern matching, we find that for a general discrete random variable X, the formula looks like

And from this, the definition of expected value is born.
Definition 92. (The expected value of discrete random variables)
Let (Ω,Σ,P) be a probability space, and X : Ω →{x1,x2,…} be a discrete random variable. The expected value of X is defined by
![𝔼 [X ] := ∑ x P (X = x ). k k k](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1901.png)
(Note that if X assumes finitely many values, the sum only contains a finite number of terms.)
In English, the expected value describes the average value of a random variable in the long run. The expected value is also called the mean and is often denoted by μ. Instead of using random variables, we’ll often use the expected value symbol by plugging in distributions, like 𝔼[Bernoulli(p)]. Although this is mathematically not precise, 1) it is simpler in certain cases, 2) and the expected value only depends on the distribution anyway.
It’s time for examples.
Example 1. Expected value of the Bernoulli distribution. (See the definition of the Bernoulli distribution in Section 19.2.1.) Let X ∼ Bernoulli(p). Its expected value is quite simple to compute, as
![𝔼[X] = 0⋅P (X = 0 )+ 1⋅P (X = 1) = = 0⋅(1 − p)+ 1 ⋅p = p.](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1902.png)
We’ve seen this before: the introductory example with the simple game is the transformed Bernoulli distribution 3 ⋅ Bernoulli(1∕2) − 2.
Example 2. Expected value of the binomial distribution. (See the definition of the binomial distribution in Section 19.2.2.) Let X ∼ Binomial(n,p). Then
![∑n 𝔼[X] = kP (X = k ) k=0 ∑n (n ) = k pk(1 − p)n−k k=0 k ∑n = k----n!--- pk(1 − p)n−k. k=0 k!(n − k)!](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1903.png)
The plan is the following: absorb that k with the fraction
, and adjust the sum such that its terms form the probability mass function for Binomial(n − 1,p). As n −k = (n − 1) − (k − 1), we have
![∑n 𝔼[X ] = k ---n!----pk(1− p)n−k k=0 k!(n − k)! ∑n = np ---------(n-−-1)!--------pk−1(1 − p)(n−1)−(k−1) k=1(k − 1)!((n − 1)− (k − 1))! n−1 = np ∑ ---(n-−-1)!--pk(1− p)(n−1−k) k!(n − 1− k)! k=0 n∑−1 = np P (Binomial(n− 1,p) = k) k=0 = np.](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1905.png)
This computation might not look like the simplest, but once you get familiar with the trick, it’ll be like second nature for you.
Example 3. Expected value of the geometric distribution. (See the definition of the geometric distribution in Section 19.2.3.) Let X ∼ Geo(p). We need to calculate
![∑∞ 𝔼[X ] = k (1 − p)k−1p. k=1](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1906.png)
Do you remember the geometric series (19.2)? This is almost it, except for the k term, which throws a monkey wrench into our gears. To fix that, we’ll use another magic trick. Recall that

Now, we are going to differentiate the geometric series, thus obtaining

where we used the linearity of the derivative and the pleasant analytic properties of the geometric series. Mathematicians would scream upon the sight of switching the derivative and the infinite sum, but don’t worry, everything here is correct as is. (Mathematicians are really afraid of interchanging limits. Mind you, for a good reason!)
On the other hand,

thus

Combining all of these, we finally have
![∑∞ 𝔼[X ] = k (1 − p)k−1p k=1 ∞∑ = p k(1− p)k−1 k=1 1 1 = p-2 = -. p p](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1911.png)
Example 4. Expected value of the constant random variable. Let c ∈ℝ be an arbitrary constant, and let X be the random variable that assumes the value c everywhere. As X is a discrete random variable, its expected value is simply
![𝔼[X ] = c⋅P (X = c) = c.](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1912.png)
I know, this example looks silly, but it can be quite useful. When it is clear, we abuse the notation by denoting the constant c as the random variable itself.
20.1.1 The expected value in poker
Section titled “20.1.1 The expected value in poker”One more example before we move on. I was a mediocre no-limit Texas hold’em player a while ago, and the first time I heard about the expected value was years before I studied probability theory.
According to the rules of Texas hold’em, each player holds two cards on their own, while five more shared cards are dealt. The shared cards are available for everyone, and the player with the strongest hand wins.
Figure 20.1 shows how the table looks before the last card (the river) is revealed.

Figure 20.1: The poker table before the river card
There is money in the pot to be won, but to see the river, you have to call the opponent’s bet. The question is, should you? Expected value to the rescue.
Let’s build a probabilistic model. We would win the pot with certain river cards but lose with all the others. If X represents our winnings, then

Thus, the expected value is
![𝔼[X] = pot⋅P (X = pot )− bet⋅P (X = − bet) #winning cards #losing cards = pot⋅ ----------------− bet⋅----------------. #remaining cards #remaining cards](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1915.png)
When is the expected value positive? With some algebra, we obtain that 𝔼[X]>0 if and only if

which is called positive pot odds. If this is satisfied, making the bet is the right call. You might lose a hand with positive pot odds, but in the long term, your winnings will be positive.
Of course, pot odds are extremely hard to determine in practice. For instance, you don’t know what others hold, and counting the cards that would win the pot for you is not possible unless you have a good read on the opponents. Poker is much more than just math. Good players choose their bet specifically to throw off their opponents’ pot odds.
Now that we understand the idea behind the expected value, let’s move on to the general case!
Bookmark
20.2 Continuous random variables
Section titled “20.2 Continuous random variables”So far, we have only defined the expected value for discrete random variables. As 𝔼[X] describes the average value of X in the long run, it should exist for continuous random variables as well.
The interpretation of the expected value was simple: outcome times probability, summed over all potential values. However, there is a snag with continuous random variables: we don’t have such a mass distribution, as the probabilities of individual outcomes are zero: P(X = x) = 0. Moreover, we can’t sum uncountably many values.
What can we do?
Wishful thinking. This is one of the most powerful techniques in mathematics, and I am not joking.
Here’s the plan. We’ll pretend that the expected value of a continuous random variable is well-defined, and let our imagination run free. Say goodbye to mathematical precision, and allow our intuition to unfold. Instead of the probability of a given outcome, we can talk about X landing in a small interval. First, we divide up the set of real numbers into really small parts. To be more precise, let x0>x1>…>xn be a granular partition of the real line. If the partition is refined enough, we should have
𝔼[X] ≈ ∑k=1n xk P(xk−1 ≤ X ≤ xk) (20.1)
The probabilities in (20.1) can be expressed in terms of the CDF:

These increments remind us of the difference quotients. We don’t quite have these inside the sum, but with a “fancy multiplication with one,” we can achieve this:

If the xi-s are close to each other (and we can select them to be arbitrarily close), the difference quotients are close to the derivative of FX, which is the density function fX. Thus,

This is a Riemann-sum, defined by (14.7)! Hence, the last sum is close to a Riemann-integral:

Although we were not exactly precise in our argument, all of the above can be made mathematically correct. (But we are not going to do it here, as it is not relevant to us.) Thus, we finally obtain the formula of the expected value for continuous random variables.
Definition 93. (The expected value of continuous random variables)
Let (Ω,Σ,P) be a probability space, and X : Ω →ℝ be a continuous random variable. The expected value of X is defined by
![∫ ∞ 𝔼 [X ] := xfX(x)dx. −∞](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1921.png)
As usual, let’s see some examples first.
Example 1. Expected value of the uniform distribution. (See the definition of the uniform distribution in Section 19.3.4.) Let X ∼ Uniform(a,b). Then
![∫ ∞ 1 𝔼[X ] = x-----dx − ∞ b∫− a --1-- b = b − a xdx [ a ]x=b = ---1---x2 2(b − a) x=a a + b = --2--,](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1922.png)
which is the midpoint of the interval [a,b], where the Uniform(a,b) lives.
Example 2. Expected value of the exponential distribution. (See the definition of the exponential distribution in Section 19.3.5.) Let X ∼ exp(λ). Then, we need to calculate the integral
![∫ ∞ − λx 𝔼[X ] = xλe dx. 0](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1923.png)
We can do this via integration by parts (Theorem 95): by letting f(x) = x and g′(x) = λe−λx, we have
![∫ ∞ 𝔼 [X ] = xλe−λxdx 0 [ ]x=∞ ∫ ∞ = − xe−λx x=0 + e− λxdx ◟-----◝=◜0-----◞ 0 [ ]x=∞ = − 1-e−λx λ x=0 1- = λ.](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1924.png)
Bookmark
20.3 Properties of the expected value
Section titled “20.3 Properties of the expected value”As usual, the expected value has several useful properties. Most importantly, the expected value is linear with respect to the random variable.
Theorem 129. (Linearity of the expected value)
Let (Ω,Σ,P) be a probability space, and let X,Y : Ω → ℝ be two random variables. Moreover, let a,b ∈ℝ be two scalars. Then
![𝔼[aX + bY ] = a𝔼 [X ]+ b𝔼 [Y ]](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1925.png)
holds.
We are not going to prove this theorem here, but know that linearity is an essential tool. Do you recall the game that we used to introduce the expected value for discrete random variables? I toss a coin, and if it comes up heads, you win $1. Tails, you lose $2. If you think about it for a minute, this is the

distribution, and as such,
![𝔼[X] = 𝔼[3⋅Bernoulli(1 ∕2)− 2] = 3⋅𝔼 [Bernoulli(1 ∕2)]− 2 = 3⋅ 1− 2 2 1- = − 2.](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1927.png)
Of course, linearity goes way beyond this simple example. As you’ve gotten used to this already, linearity is a crucial property in mathematics. We love linearity.
Remark 20.
Notice that Theorem 129 did not say that X and Y have to be both discrete or both continuous. Even though we have only defined the expected value in such cases, there is a general definition that works for all random variables.
The snag is, it requires a familiarity with measure theory, falling way outside of our scope. Suffice to say, the theorem works as is.
If the expected value of a sum is the sum of the expected values, does the same apply to the product? Not in general, but fortunately, this works for independent random variables. (See Definition 84 for the definition of independent random variables.)
Theorem 130. (Expected value of the product of independent random variables)
Let (Ω,Σ,P) be a probability space, and let X,Y : Ω →ℝ be two independent random variables.
Then
![𝔼 [XY ] = 𝔼 [X ]𝔼[Y]](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1928.png)
holds.
This property is extremely useful, as we’ll see in the next section, where we’ll talk about variance and covariance.
One more property that’ll help us to calculate the expected value of functions of the random variable, such as X2 or sinX:
Theorem 131. (Law of the unconscious statistician)
Let (Ω,Σ,P) be a probability space, let X : Ω → ℝ be a random variable, and let g : ℝ →ℝ be an arbitrary function.
(a) If X is discrete with possible values x1,x2,…, then
![∑ 𝔼[g(X)] = g(xn)P (X = xn). n](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1929.png)
(b) If X is continuous with the probability density function fX(x), then
![∫ ∞ 𝔼[g(X )] = g(x)f (x)dx. −∞ X](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1930.png)
Thus, calculating 𝔼[X2] for a continuous random variable can be done by simply taking
![∫ ∞ 𝔼[X2] = x2fX (x)dx, −∞](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1931.png)
which will be used all the time.
Bookmark
20.4 Variance
Section titled “20.4 Variance”Plainly speaking, the expected value measures the average value of the random variable. However, even though both Uniform(−1,1) and Uniform(−100,100) have zero expected value, the latter is much more spread out than the former. Thus, 𝔼[X] is not a good descriptor of the random variable X.
To add one more layer, we measure the average deviation from the expected value. This is done via the variance and the standard deviation.
Definition 94. (Variance and standard deviation)
Let (Ω,Σ,P) be a probability space, let X : Ω →ℝ be a random variable, and let μ = 𝔼[X] be its expected value. The variance of X is defined by
![[ 2] Var [X ] := 𝔼 (X − μ ) ,](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1932.png)
while its standard deviation is defined by
![Std[X] := ∘Var--[X-].](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1933.png)
Take note that in the literature, the expected value is often denoted by μ, while the standard deviation is denoted by σ. Together, they form two of the most important descriptors of a random variable.
Figure 20.2 shows a visual interpretation of the mean and standard deviation in the case of a normal distribution. The mean shows the average value, while the standard deviation can be interpreted as the average deviation from the mean. (We’ll talk about the normal distribution in detail later, so don’t worry if it is not yet familiar to you.)

Figure 20.2: Mean (μ) and standard deviation
of the standard normal distribution
The usual method of calculating variance is not taking the expected value of (X −μ)2, but taking the expected value of X2 and subtracting μ2 from it. This is shown by the following proposition.
Proposition 5.
Let (Ω,Σ,P) be a probability space, and let X : Ω →ℝ be a random variable.
Then
![Var[X] = 𝔼[X2 ]− 𝔼[X ]2.](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1936.png)
Proof. Let μ = 𝔼[X]. Because of the linearity of the expected value, we have
![Var[X ] = 𝔼[(X − μ)2] = 𝔼[X2 − 2μX + μ2] = 𝔼[X ]2 − 2μ𝔼 [X ]+ μ2 2 2 2 = 𝔼[X ] − 2μ + μ = 𝔼[X2 ]− μ2 = 𝔼[X2 ]− 𝔼[X ]2,](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1937.png)
which is what we had to show.
Is the variance linear as well? No, but there are some important identities regarding scalar multiplication and addition.
Theorem 132. (Variance and the linear operations)
Let (Ω,Σ,P) be a probability space, and let X : Ω →ℝ be a random variable.
(a) Let a ∈ℝ be an arbitrary constant. Then
![2 Var[aX ] = a Var[X ].](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1938.png)
(b) Let Y : Ω →ℝ be a random variable that is independent from X. Then
![Var[X + Y ] = Var[X ]+ Var[Y].](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1939.png)
Proof. (a) Let μX = 𝔼[X]. Then we have
![[ ] [ ] Var[aX ] = 𝔼 (aX − a μX)2 = 𝔼 a2(X − μX )2 [ ] = a2𝔼 (X − μX )2 = a2Var[X ],](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1940.png)
which is what we had to show. (b) Let μY = 𝔼[Y ]. Then, due to the linearity of the expected value, we have
![[ 2] Var[X + Y ] = 𝔼 (X + Y − (μX + μY )) [ 2] = 𝔼 ((X − μX ) + (Y − μY)) = 𝔼 [(X − μX)2]+ 2𝔼[(X − μX )(Y − μY)] + 𝔼[(Y − μY )2].](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1941.png)
Now, as X and Y are independent, 𝔼[XY ] = 𝔼[X]𝔼[Y ]. Thus, due to the linearity of the expected value,
![[ ] [ ] 𝔼 (X − μX )(Y − μY) = 𝔼 XY − X μY − μX Y + μX μY = 𝔼[XY ] − 𝔼[X μ ]− 𝔼 [μ Y ]+ μ μ [ ] [ ] [Y ] X [ ] X Y = 𝔼 X 𝔼 Y − 𝔼 X μY − μX 𝔼 Y + μX μY = μXμY − μXμY − μXμY + μXμY = 0.](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1942.png)
Thus, continuing the first calculation,
![Var[X + Y ] = 𝔼 [(X − μ )2]+ 2𝔼[(X − μ )(Y − μ )] + 𝔼[(Y − μ )2] X X Y Y = 𝔼 [(X − μX)2]+ 𝔼[(Y − μY )2],](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1943.png)
which is what we had to show.
20.4.1 Covariance and correlation
Section titled “20.4.1 Covariance and correlation”Expected value and variance measure a random variable in isolation. However, in real problems, we need to discover relations between separate measurements. Say, X describes the price of a given real estate, while Y measures its size. These are certainly related, but one does not determine the other. For instance, the location might be a differentiator between the prices.
The simplest statistical way of measuring similarity is the covariance and correlation.
Definition 95. (Covariance and correlation)
Let (Ω,Σ,P) be a probability space, let X,Y : Ω → ℝ be two random variables, and let μX = 𝔼[X],μY = 𝔼[Y ] be their expected values and σX = Std[X],σY = Std[Y ] their standard deviations.
(a) The covariance of X and Y is defined by
![[ ] Cov [X,Y ] := 𝔼 (X − μX )(Y − μY ).](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1944.png)
(b) The correlation of X and Y is defined by
![Cov[X, Y] Corr [X, Y ] := ---------. σXσY](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1945.png)
Similarly to variance, the definition of covariance can be simplified to provide an easier way of calculating its exact value.
Proposition 6.
Let (Ω,Σ,P) be a probability space, let X,Y : Ω → ℝ be two random variables, and let μX = 𝔼[X],μY = 𝔼[Y ] be their expected values.
Then
![Cov[X, Y] = 𝔼[XY ]− μX μY .](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1946.png)
Proof. This is just a simple calculation. According to the definition, we have
![[ ] Cov[X, Y] = 𝔼 (X − μX )(Y − μY) [ ] = 𝔼 XY − X μY − μX Y + μX μY = 𝔼[XY ] − 𝔼[X μ ]− 𝔼[μ Y ]+ μ μ [ ] [ ]Y X[ ] X Y = 𝔼 XY − 𝔼 X μY − μX 𝔼 Y + μX μY [ ] = 𝔼 XY − μX μY − μX μY + μX μY = 𝔼[XY ]− μX μY ,](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1947.png)
which is what we had to show.
One of the most important properties of covariance and correlation is that they are zero for independent random variables.
Theorem 133.
Let (Ω,Σ,P) be a probability space, and let X,Y : Ω →ℝ be two independent random variables.
Then, Cov[X,Y ] = 0. (And consequently, Corr[X,Y ] = 0 as well.)
The proof follows straight from the definition and Theorem 130, so this is left as an exercise for you.
Take note, as this is extra important: independence implies zero covariance, but zero covariance does not imply independence. Here is an example.
Let X be a discrete random variable with the probability mass function

and let Y = X2.
The expected value of X is
![𝔼 [X ] = (− 1)⋅P (X = − 1)+ 0 ⋅P (X = 0)+ 1 ⋅P (X = 1) = − 1-+ 0 + 1- 3 3 = 0,](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1949.png)
while the law of the unconscious statistician (Theorem 131) gives that
![2 𝔼[Y ] = 𝔼[X ] = 1 ⋅P(X = − 1) + 0⋅P (X = 0) + 1⋅P (X = 1 ) 1- 1- = 3 + 0+ 3 2 = -, 3](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1950.png)
and
![𝔼[XY ] = 𝔼[X3] = 0.](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1951.png)
Thus,
![Cov [X,Y ] = 𝔼 [XY ]− 𝔼[X ]𝔼 [Y ] 3 2 = 𝔼 [X ]− 𝔼 [X ]𝔼[X ] 2- = 0 − 0⋅ 3 = 0.](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1952.png)
However, X and Y are not independent, as Y = X2 is a function of X. (I shamelessly stole this example from a brilliant Stack Overflow thread, which you should read here for more on this question: https://stats.stackexchange.com/questions/179511/why-zero-correlation-does-not-necessarily-imply-independence)
Do you recall that we interpreted the concept of probability as the relative frequency of occurrences? Now that we have the expected value under our belt, we can finally make this precise. Let’s look at the famous law of large numbers!
Bookmark
20.5 The law of large numbers
Section titled “20.5 The law of large numbers”We’ll continue our journey with a quite remarkable and famous result: the law of large numbers. You have probably already heard several faulty arguments invoking the law of large numbers. For instance, gamblers are often convinced that their bad luck will end soon because of said law. This is one of the most frequently misused mathematical terms, and we are here to clear that up.
We’ll do this in two passes. First, we are going to see an intuitive interpretation, then add the technical but important mathematical details. I’ll try to be gentle.
20.5.1 Tossing coins…
Section titled “20.5.1 Tossing coins…”First, let’s toss some coins again. If we toss coins repeatedly, what is the relative frequency of heads in the long run?
We should have a pretty good guess already: the average number of heads should converge to P(heads) = p as well. Why? Because we saw this when studying the frequentist interpretation of probability in Section 18.2.7.
Our simulation showed that the relative frequency of heads does indeed converge to the true probability. This time, we’ll carry the simulation a bit further.
First, to formulate the problem, let’s introduce the independent random variables X1,X2,… that are distributed along Bernoulli(p), where Xi = 0 if the toss results in tails, while Xi = 1 if it is heads. We are interested in the long-term behavior of

Xn is called the sample average. We have already seen that the sample average gets closer and closer to p as n grows. Let’s see the simulation one more time, before we go any further. (The parameter p is selected to be 1∕2 for the sake of the example.)
import numpy as npfrom scipy.stats import bernoulli
n_tosses = 1000idx = range(n_tosses)
coin_tosses = [bernoulli.rvs(p=0.5) for _ in idx]coin_toss_averages = [np.mean(coin_tosses[:k+1]) for k in idx]And here is the plot.
import matplotlib.pyplot as plt
with plt.style.context("seaborn-v0_8"): plt.figure(figsize=(10, 5)) plt.title("Relative frequency of the coin tosses ") plt.xlabel("Relative frequency") plt.ylabel("Number of tosses")
# plotting the averages plt.plot(range(n_tosses), coin_toss_averages, linewidth=3) # the averages
# plotting the true expected value plt.plot([-100, n_tosses+100], [0.5, 0.5], c="k") plt.xlim(-10, n_tosses+10) plt.ylim(0, 1) plt.show()
Figure 20.3: Relative frequency of the coin tosses
Nothing new so far. However, if you have a sharp eye, you might ask the question: is this just an accident? After all, we are studying the average

which is (almost) a binomially distributed random variable! To be more precise, if Xi ∼ Bernoulli(p), then

(We saw this earlier when discussing the sums of discrete random variables in Section 19.2.7.)
At this point, it is far from guaranteed that this distribution will be concentrated around a single value. So, let’s do some more simulations. This time, we’ll toss a coin a thousand times to see the distribution of the averages. Quite meta, I know.
more_coin_tosses = bernoulli.rvs(p=0.5, size=(n_tosses, n_tosses))more_coin_toss_averages = np.array([[np.mean(more_coin_tosses[i][:j+1]) for j in idx] for i in idx])We can visualize the distributions on histograms.
with plt.style.context("seaborn-v0_8"): fig, axs = plt.subplots(1, 3, figsize=(12, 4), sharey=False) fig.suptitle("The distribution of sample averages") for ax, i in zip(axs, [5, 100, 999]): x = [k/i for k in range(i+1)] y = more_coin_toss_averages[:, i] ax.hist(y, bins=x) ax.set_title(f"n = {i}")
plt.show()
Figure 20.4: Sample average distributions of coin tosses
In other words, the probability of Xn falling far from p becomes smaller and smaller. For any small 𝜀, we can formulate the probability of “Xn falling farther from p than 𝜀” as P(|Xn −p|𝜀).
Thus, mathematically speaking, our guess is

Again, is this just an accident, and were we just lucky to study an experiment where this is true? Would the same work for random variables other than Bernoulli ones? What will the sample averages converge to? (If they converge at all.)
We’ll find out.
20.5.2 …rolling dice…
Section titled “20.5.2 …rolling dice…”Let’s play dice. To keep things simple, we are interested in the average value of a roll in the long run. To build a proper probabilistic model, let’s introduce random variables!
A single roll is uniformly distributed on {1,2,…,6}, and each roll is independent from the others. So, let X1,X2,… be independent random variables, each distributed according to Uniform({1,2,…,6}).
How does the sample average Xn behave? Simulation time. We’ll randomly generate 1000 rolls, then explore how Xn behaves.
from scipy.stats import randint
n_rolls = 1000idx = range(n_rolls)
dice_rolls = [randint.rvs(low=1, high=7) for _ in idx]dice_roll_averages = [np.mean(dice_rolls[:k+1]) for k in idx]Again, to obtain a bit of an insight, we’ll visualize the averages on a plot.
with plt.style.context("seaborn-v0_8"): plt.figure(figsize=(10, 5)) plt.title("Sample averages of rolling a six-sided dice")
# plotting the averages plt.plot(idx, dice_roll_averages, linewidth=3) # the averages
# plotting the true expected value plt.plot([-100, n_rolls+100], [3.5, 3.5], c="k")
plt.xlim(-10, n_rolls+10) plt.ylim(0, 6) plt.show()
Figure 20.5: Sample averages of rolling a six-sided dice
The first thing to note is that these are suspiciously close to 3.5. This is not a probability, but the expected value:
![𝔼[X1 ] = 𝔼[X2] = ⋅⋅⋅ = 3.5.](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1960.png)
For Bernoulli(p) distributed random variables, the expected value coincides with the probability p. However, this time, Xn does not have a nice and explicit distribution like in the case of coin tosses, where the sample averages were binomially distributed. So, let’s roll some more dice to estimate how Xn is distributed.
more_dice_rolls = randint.rvs(low=1, high=7, size=(n_rolls, n_rolls))more_dice_roll_averages = np.array([[np.mean(more_dice_rolls[i][:j+1]) for j in idx] for i in idx])with plt.style.context("seaborn-v0_8"): fig, axs = plt.subplots(1, 3, figsize=(12, 4), sharey=False) fig.suptitle("The distribution of sample averages ") for ax, i in zip(axs, [5, 100, 999]): x = [6*k/i for k in range(i+1)] y = more_dice_roll_averages[:, i] ax.hist(y, bins=x) ax.set_title(f"n = {i}")
plt.show()
Figure 20.6: Sample average distributions of dice rolls
It seems like, once more, the distribution of Xn is concentrated around 𝔼[X1]. Our intuition tells us that this is not an accident; that this phenomenon is true for a wide range of random variables.
Let me spoil the surprise: this is indeed the case, and we’ll see this now.
20.5.3 …and all the rest
Section titled “20.5.3 …and all the rest”This time, let X1,X2,… be a sequence of independent and identically distributed (i.i.d.) random variables. Not coin tosses, not dice rolls, but any distribution. We saw that the sample average Xn seems to converge to the joint expected value of the Xi-s:
![′′- ′′ Xn → 𝔼[X1]](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1962.png)
Note the quotation marks: Xn is not a number but a random variable. Thus, we can’t (yet) speak about convergence.
In mathematically precise terms, what we saw previously is that for large enough n-s, the sample average Xn is highly unlikely to fall far from the joint expected value μ = 𝔼[X1]; that is,
limn→∞ P(|Xn − μ| > 𝜀) = 0 (20.2)
holds for all 𝜀>0.
The limit (20.2) seems hard to prove right now even in the simple case of coin tossing. There, Xn ∼
Binomial(n,p), thus

where the symbol ⌊x⌋ denotes the largest integer that is smaller than x. This does not look friendly at all. (I leave the verification as an exercise.)
Thus, our plan is the following.
- Find a way to estimate P(jXn−μj>𝜀) in a way that is independent from the distribution of the Xi-s.
- Use the upper estimate to show limn→∞P(jXn −μj>𝜀) = 0.
Let’s go.
20.5.4 The weak law of large numbers
Section titled “20.5.4 The weak law of large numbers”First, the upper estimates. There are two general inequalities that’ll help us to deal with P(jXn −μj ≥𝜀).
Theorem 134. (Markov’s inequality)
Let (Ω,Σ,P) be a probability space and let X : Ω → [0,∞) be a nonnegative random variable. Then
![𝔼[X ] P (X ≥ t) ≤ ----- t](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1965.png)
holds for any t ∈ (0,∞).
Proof. We have to separate the discrete and the continuous cases. The proofs are almost identical, so I’ll only do the discrete case here, while the continuous is left for you as an exercise to test your understanding.
So, let X : Ω → {x1,x2,…} be a discrete random variable (where xk ≥ 0 for all k), and t ∈ (0,∞) be an arbitrary positive real number.
Then
𝔼[X]
= ∑ k=1∞x kP(X = xk)
= ∑ k:xk>txkP(X = xk) + ∑ k:xk≥txkP(X = xk),
where the sum ∑ k:xk>t only accounts for k-s with xk>t, and similarly, ∑ k : xk ≥t only accounts for k-s with xk ≥t.
As the xk-s are nonnegative by assumption, we can estimate 𝔼[X] from below by omitting one of them. Thus,
![∑ ∑ 𝔼[X ] = xkP (X = xk )+ xkP (X = xk) k < k ≥t ∑k k ≥ xkP (X = xk ) k≥t ∑ ≥ t P (X = xk ) k≥t = tP(X ≥ t),](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1966.png)
from which Markov’s inequality
![P (X ≥ t) ≤ 𝔼[X-] t](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1967.png)
follows.
The law of large numbers is only one step away from Markov’s inequality. This last step is so useful that it deserves to be its own theorem. Meet the famous inequality of Chebyshev.
Theorem 135. (Chebyshev’s inequality)
Let (Ω,Σ,P) be a probability space and let X : Ω →ℝ be a random variable with finite variance σ2 = Var[X]>∞and expected value 𝔼[X] = μ.
Then

holds for all t ∈ (0,∞).
Proof. As |X −μ| is a nonnegative random variable, we can apply Theorem 134 to obtain
![P (|X − μ| ≥ t) = P(|X − μ|2 ≥ t2) 2 ≤ 𝔼[|X--−-μ|-]. t2](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1969.png)
However, as 𝔼[|X −μ|2] = Var[X] = σ2, we have
![2 2 P(|X − μ | ≥ t) ≤ 𝔼-[|X-−2μ-|] = σ2 t t](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1970.png)
which is what we had to show.
And with that, we are ready to precisely formulate and prove the law of large numbers. After all this setup, the (weak) law of large numbers is just a small step away. Here it is in its full glory.
Theorem 136. (The weak law of large numbers)
Let X1,X2,… be a sequence of independent and identically distributed random variables with finite expected value μ = 𝔼[X1] and variance σ2 = Var[X1], and let

be their sample average. Then

holds for any 𝜀>0.
Proof. As the Xi-s are independent, the variance of the sample average is
![-- [ X1 + ⋅⋅⋅+ Xn ] Var[Xn ] = Var ------------- n = -1-Var[X1 + ⋅⋅⋅+ Xn] n2 = -1-(Var[X ]+ ⋅⋅⋅+ Var[X ]) n2 1 n n σ2 σ2 = -n2- = n-.](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1973.png)
Now, by using Chebyshev’s inequality from Theorem 135, we obtain
![-- -- Var[Xn-] -σ2- P (|Xn − μ | ≥ 𝜀) ≤ 𝜀2 = n 𝜀2.](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1974.png)
Thus,

hence

which is what we needed to show.
Theorem 136 is not all that can be said about the sample averages. There is a stronger result, showing that the sample averages do in fact converge to the mean with probability 1.
20.5.5 The strong law of large numbers
Section titled “20.5.5 The strong law of large numbers”Why is Theorem 136 called the “weak” law? Think about the statement
limn→∞ P(|Xn − μ| ≥ 𝜀) = 0 (20.3)
for a moment. For a given ω ∈ Ω, this doesn’t tell us anything about the convergence of a concrete sample average

it just tells us that in a probabilistic sense, Xn is concentrated around the joint expected value μ. In a sense, (20.3) is a weaker version of

hence the terminology weak law of large numbers.
Do we have a stronger result than Theorem 136? Yes, we do.
Theorem 137. (The strong law of large numbers)
Let X1,X2,… be a sequence of independent and identically distributed random variables with finite expected value μ = 𝔼[X1] and variance σ2 = Var[X1], and let

be their sample average. Then

We are not going to prove this, just know that the sample average will converge to the mean with probability one.
Remark 21. (Convergence of random variables)
What we have seen in the weak and strong laws of large numbers are not unique to sample averages. Similar phenomena can be observed in other cases, thus, these types of convergences have their own exact definitions.
If X1,X2,… is a sequence of random variables, we say that
(a) Xn converges in probability towards X if

for all 𝜀>0. Convergence in probability is denoted by Xn
X.
(b) Xn converges almost surely towards X if

holds. Almost sure convergence is denoted by Xn
X.
Thus, the weak and strong laws of large numbers state that in certain cases, the sample averages converge to the expected value both in probability and almost surely.
Bookmark
20.6 Information theory
Section titled “20.6 Information theory”If you have already trained a machine learning model in your practice, chances are you are already familiar with the mean-squared error

where f : ℝn →ℝ represents our model, x ∈ℝn is the vector of one-dimensional observations, and y ∈ℝn is the ground truth. After learning all about the expected value, this sum should be familiar: if we assume a probabilistic viewpoint and let X and Y be the random variables describing the data, then the mean-squared error can be written as the expected value
![[ ] MSE (x, y) = 𝔼 (f(X )− Y )2.](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1986.png)
However, the mean-squared error is not suitable for classification problems. For instance, if the task is to classify the object of an image, the output is a discrete probability distribution for each sample. In this situation, we could use the so-called cross-entropy, defined by
![n H [p,q] = − ∑ p logq i i i=1](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1987.png)
where p ∈ℝn denotes the one-hot encoded vector of the class label for a single data sample, and q ∈ℝn is the class label prediction, forming a probability distribution. (One-hot encoding is the process where we represent a finite set of possible class labels, such as {a,b,c} as zero-one vectors, like

We do this because it’s easier to work with vectors and matrices than with strings.)
Not that surprisingly, H[p,q] is also an expected value, but it’s much more than that: it quantifies the information content of the distribution q compared to the ground truth distribution q.
But what is information in a mathematical sense? Let’s dive in.
20.6.1 Guess the number
Section titled “20.6.1 Guess the number”Let’s start with a simple game. I have thought of an integer between 0 and 7, and your job is to find out which one by asking yes-no questions.

Figure 20.7: Which number am I thinking of?
One possible strategy is to guess the numbers one by one. In other words, the sequence of your questions are:
- Is it 0?
- Is it 1?

- Is it 7?
Although this strategy works, it is not an effective one. Why? Consider the average number of questions. Let the random variable X denote the number I have picked. As X is uniformly distributed — that is, P(X = k) = 1∕8 for all k = 0,…,7 — the probability of asking exactly k questions is

as well. Thus, the number of questions needed is also uniformly distributed on {1,…,8}, thus
![∑8 𝔼[#questions] = kP (#questions = k ) k=1 8 = 1-∑ k 8 k=1 = 1-8⋅9-= 9-, 8 2 2](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1992.png)
where we have used that ∑ k=1n =
.
Can we do better than this? Yes. In the previous sequential strategy, each question has a small chance of hitting, and a large chance of eliminating, only one potential candidate. It’s easy to see that the best would be to eliminate half the search space with each question.
Say, the number I thought of is 2. By asking “is the number larger than 3”?, the answer trims out four of the candidates.

Figure 20.8: The search space after the question is the number larger than 3?
Each subsequent question cuts the remaining possibilities in half. In the case of X = 2, the three questions are the following:
- Is X ≥ 4? (no)
- Is X ≥ 2? (yes)
- Is X ≥ 3? (no)
This is the so-called binary search, illustrated by Figure 20.9.

Figure 20.9: Figuring out the answer with binary search
If we write down the answers for our three consecutive questions (X ≥ 4, X ≥ 2, X ≥ 3) as a zero-one sequence, we obtain 010. If this looks familiar, it’s not an accident: 010 is 2 in binary. In fact, all of the answers can be coded using their binary form:

Thus, we can reformulate our three questions:
- Is 1 the 1st digit of X in binary?
- Is 1 the 2nd digit of X in binary?
- Is 1 the 3rd digit of X in binary?
As the above example shows, guessing the number is equivalent to finding the binary representation of the objects to be guessed. Each digit represents exactly one bit of information. (In this case, the representation is the actual binary form.) Binary codings have an additional perk: we no longer have to sequentially go through the questions, we can ask them simultaneously. From now on, instead of questions, we’ll talk about binary representations (codings) and their bits.
Notice that the number of bits is the same for each outcome of X. Thus, as this strategy always requires three bits, their average number is three as well:
![7 7 𝔼 [#bits] = ∑ 3⋅P (X = k ) = ∑ 3⋅ 1-= 3. 8 k=0 k=0](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1997.png)
Can we do better than the three questions on average? No. I invite you to come up with your arguments, but we’ll see this later.
Where does the number three in the above come from? In general, if we have 2k possible choices, then log 22k = k questions will be enough to find the answer. (As each question cuts the set of possible answers in half.) In other words, we have
![∑7 𝔼[#bits] = P (X = k )log2 23 k=0 7 = ∑ P (X = k )log P(X = k)−1. 2 k=0](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1998.png)
Thus, the value log 2P(X = k)−1 is the number of bits needed to represent k in our coding. In other words,
![𝔼[#bits] = 𝔼[log2P (X = k)−1].](https://static.packt-cdn.com/products/9781837027873/graphics/media/file1999.png)
Let’s get a bit ahead of ourselves: this is the famous entropy of the random variable X, and the quantity log 2P(X = k)−1 is the so-called information content of the event X = k.
However, at this point, these concepts are quite unclear. What does log 2P(X = k)−1 have to do with information? Why can’t we represent k better than log 2P(X = k)−1 bits? We’ll see the answers soon.
20.6.2 Guess the number 2: Electric Boogaloo
Section titled “20.6.2 Guess the number 2: Electric Boogaloo”Let’s play the guessing game again but with a twist this time. Now, I have picked a number from {0,1,2}, and you have to guess which one. The catch is, I am twice as likely to select 0 than the others.
In probabilistic terms, if X denotes the number I picked, then P(X = 0) = 1∕2, while P(X = 1) = P(X = 2) = 1∕4.
What is the best strategy? There are two key facts to recall:
- good questions cut the search space in half,
- and asking questions is equivalent to finding a binary encoding of the outcomes.
However, as we are looking for the encoding that is optimal on average, cutting the search space in half with each digit is not meant in a numeric way. Rather, in a probabilistic one. Thus, if 0 is indeed twice as likely, representing 0,1,2 by

the average number of bits is
![𝔼[#bits] = P (X = 0) ⋅1+ P (X = 1) ⋅2+ P (X = 2) ⋅2 = P (X = 0) log22 + P (X = 1)log24 + P (X = 2)log24 2 ∑ −1 = P(X = k)log2P (X = k) k=0 = 3-. 2](https://static.packt-cdn.com/products/9781837027873/graphics/media/file2001.png)
Once more, we have arrived at the familiar logarithmic formula. We are one step closer to grasping the meaning of the mysterious quantity log 2P(X = k)−1. The smaller it is, the more questions we need; equivalently, the more bits we need to represent k within our encoding to avoid information loss.
So, what are these mysterious quantities exactly?
20.6.3 Information and entropy
Section titled “20.6.3 Information and entropy”It is time to formulate the general problem. Suppose that our random variable X assumes a number from the set {1,2,…,N}, each with probability pk = P(X = k). Upon repeatedly observing X, what is the average information content of our observations?
According to what we’ve learned, we are looking for the quantity
![∑N 𝔼 [I (X )] = − p logp , k=1 k k](https://static.packt-cdn.com/products/9781837027873/graphics/media/file2002.png)
where I : ℕ →ℝ denotes the information I(k) = −log pk. Previously, we have seen two special cases where I(k) is the average number of questions needed to guess k. (Equivalently, the information is the average number of bits in k using the optimal encoding.)
What is the information in general?
Let’s look for I as an unknown function of the probabilities: I(x) = f(P(X = x)). What can f be? There are two key properties of that’ll lead us to the answer. First, the more probable an event is, the less information content there is. (Recall the previous example, where the most probable outcome required the least amount of bits in our binary representation.)
Second, as a function of the probabilities, the information is additive: f(pq) = f(p) + f(q). Why? Suppose that I have picked two numbers, independently from each other, and now you have to guess those two. You can do this sequentially, applying the optimal strategy to the first one, then the second one.
In mathematical terms, f(p) is
- continuous,
- strictly increasing, that is, f(p)>f(q) for any p>q,
- and additive, that is, f(pq) = f(p) + f(q) for any p,q.
I’ll spare you the mathematical details, but with a bit of calculus magic, we can confidently conclude that the only option is f(p) = −log ap, where a>1. Seemingly, information depends on the base, but as

the choice of base only influences the information and entropy up to a multiplicative scaling factor. Thus, using the natural logarithm is the simplest choice.
So, here is the formal definition at last.
Definition 96. (Information)
Let X be a discrete random variable with probability mass function {P(X = xk)}k.
The information of the event X = xk is defined by

(Note that whenever the base of log is not indicated, we are using the natural base e.) To emphasize the dependency of the information on X, we’ll sometimes explicitly denote the connection by IX(xk).
Armed with the notion of information, we are ready to define entropy, the average amount of information per observation. This quantity is named after Claude Shannon, who essentially founded information theory in his epic paper “A Mathematical Theory of Communication.”
Definition 97. (Shannon entropy)
Let X be a discrete random variable with probability mass function {P(X = xk)}k.
The entropy of X is defined by
![H[X ] := 𝔼[I(X )] ∑∞ = − P(X = xk)logP (X = xk). k=1](https://static.packt-cdn.com/products/9781837027873/graphics/media/file2007.png)
Even though H[X] is called the Shannon entropy, we’ll just simply refer to it as entropy, unless an explicit distinction is needed.
One of the first things we can notice is that H[X] ≥ 0. This is shown in the following proposition.
Proposition 7. (The nonnegativity of entropy)
Let X be an arbitrary discrete random variable. Then H[X] ≥ 0.
Proof. By definition,
![∑ H [X ] = P(X = xk)logP (X = xk)−1. k](https://static.packt-cdn.com/products/9781837027873/graphics/media/file2008.png)
First, suppose that P(X = xk)≠0 for all k. Then, as 0 P(X = xk) ≤ 1, the information is nonnegative: log P(X = xk)−1 ≥ 0. Hence, as all terms in the defining sum are nonnegative, H[X] is nonnegative as well.
If P(X = xk) = 0 for some k, then, as limx→0+xlog x = 0, the expression 0 ⋅ log 0 is taken to be 0. Thus, H[X] is still nonnegative.
Computing the entropy in practice is hard, as we have to evaluate sums that involve logarithms. However, there are a few special cases that shed some much needed light on the concept of entropy. Let’s look at them!
Example 1. The discrete uniform distribution. (See the definition of the discrete uniform distribution in Section 19.2.4.) Let X ∼ Uniform({1,…,n}). Then
![∑n H [X ] = − -1log 1- k=1n n ∑n = 1logn k=1 n = log n.](https://static.packt-cdn.com/products/9781837027873/graphics/media/file2009.png)
By now, we have an intuitive understanding of entropy as the average amount of information per observation. Take a wild guess: how does the entropy of the uniform distribution compare amongst all other distributions concentrated on {1,2,…,n}? Is it above or below average? Is it perhaps minimal or maximal?
We’ll reveal the answer by the end of this chapter, but take a minute to ponder this question before moving on to the next example.
Example 2. The single-point distribution. (See the definition of the single-point distribution in Section 19.2.5) Let X ∼δ(a). Then
![H [X ] = − 1 ⋅log 1 = 0.](https://static.packt-cdn.com/products/9781837027873/graphics/media/file2010.png)
In other words, as the event X = a is certain, no information is gained upon observing X. Now think back to the previous example. As X ∼δ(k) is concentrated on {1,2,…,n} for all k = 1,2,…,n, give the previous question one more thought.
Let’s see a partial answer in the next example.
Example 3. The Bernoulli distribution. (See the definition of the Bernoulli distribution in Section 19.2.1). Let X ∼ Bernoulli(p). Then, it is easy to see that
![H [X ] = − plogp − (1− p)log(1− p).](https://static.packt-cdn.com/products/9781837027873/graphics/media/file2011.png)
Which value of p maximizes the entropy? To find the maxima of H[X], we can turn to the derivatives. (Recall how the derivative and second derivative can be used for optimization, as claimed by Theorem 87.)
Thus, let f(p) = H[X] = −plog p − (1 −p)log(1 −p). Then,

By solving f′(p) = 0, we obtain that p = 1∕2, which is the only potential extrema of f(p). As f′′(1∕2) = −4>0, we see that p = 1∕2 is indeed a local maximum. Let’s plot f(p) to obtain a visual confirmation as well.
def bernoulli_entropy(p): return -p*np.log(p) - (1 - p)*np.log(1 - p)
X = np.linspace(0.001, 0.999, 100)y = bernoulli_entropy(X)with plt.style.context(’seaborn-v0_8’): plt.figure(figsize=(8, 8)) plt.xlabel("p") plt.ylabel("H[X]") plt.title("The entropy of Bernoulli(p) ") plt.plot(X, y) plt.show()
Figure 20.10: The entropy of the Bernoulli distribution
For p = 1∕2, that is, where the entropy of Bernoulli(p) is maximal, we have a uniform distribution on the two-element set {0,1}. On the other hand, for p = 0 or p = 1, where the entropy is minimal, Bernoulli(p) is a single-point distribution.
As every random variable on {0,1} is Bernoulli-distributed, we seem to have a partial answer to our question: the uniform distribution maximizes entropy, while single-point ones minimize it.
As the following theorem indicates, this is true in general as well.
Theorem 138. (The uniform distribution and maximal entropy)
Let E = {x1,…,xn}be a finite set, and let X : Ω →E be a random variable that assumes values in E. Then,
![H [X] ≤ H [Uniform (E)],](https://static.packt-cdn.com/products/9781837027873/graphics/media/file2014.png)
and H[X] = H[Uniform(E)] if and only if X is uniformly distributed on E.
We are not going to show this here, but there are several proofs out there. For instance, Bishop’s classic Pattern Recognition and Machine Learning uses the Lagrange multiplier method to explicitly find the maximum of the multivariable function f(p1,…,pn) = −∑ k=1npk log pk; feel free to check it out for the details.
What if we don’t restrict our discrete random variable to a finite set? In that case, the Shannon entropy has no upper limit. In the problem set of this chapter, you’ll see that the entropy of the geometric distribution is
![H [Geo (p)] = − plogp-+-(1−-p)-log(1-−-p). p](https://static.packt-cdn.com/products/9781837027873/graphics/media/file2015.png)
It is easy to see that limp→0H[Geo(p)] = ∞. Let’s plot this!
def geom_entropy(p): return -(p*np.log(p) + (1 - p)*np.log(1 - p))/p
X = np.linspace(1e-16, 1-1e-16, 1000)y = geom_entropy(X)
with plt.style.context(’seaborn-v0_8’): plt.figure(figsize=(8, 8)) plt.xlabel("p") plt.ylabel("H[X]") plt.title("The entropy of Geo(p)") plt.plot(X, y) plt.show()
Figure 20.11: The entropy of the geometric distribution
Thus, the Shannon entropy can assume any nonnegative value.
20.6.4 Differential entropy
Section titled “20.6.4 Differential entropy”So far, we have only defined the entropy for discrete random variables.
Does it translate to continuous ones as well? Yes. The formula 𝔼[ − log fX(X)] can be directly applied for continuous random variables, yielding the so-called differential entropy. Here is the formal definition.
Definition 98. (Differential entropy)
Let X be a continuous random variable. The differential entropy of X is defined by the formula
![∫ ∞ H [X ] := − f (x )log f (x)dx, −∞ X X](https://static.packt-cdn.com/products/9781837027873/graphics/media/file2017.png)
where fX denotes the probability density function of X.
Now comes the surprise. Can we derive the formula from the Shannon entropy? We are going to approach the problem like we did when we defined the expected value for continuous random variables in Section 20.2: approximate the continuous random variable with a discrete one, then see where the Shannon entropy converges.
Thus, let X : Ω →ℝ be a continuous random variable, and let [a,b] ⊆ℝ be a (large) interval, so large that P(X
[a,b]) is extremely small. We’ll subdivide [a,b] into n equal parts by

and define the approximating random variable X(n) by
![ ( (n) |{ xk if x ∈ (xk −1,xk] for some k = 1,2,…,n, X (ω ) := | ( 0 otherwise. ](https://static.packt-cdn.com/products/9781837027873/graphics/media/file2020.png)
This way, the entropy of X(n) is given by
![(n) ∑n (n) (n) H [X ] = − P (X = xk)logP (X = xk). k=1](https://static.packt-cdn.com/products/9781837027873/graphics/media/file2021.png)
However, due to how we defined X(n),

where fX is the density function of X. Now, the mean value theorem for definite integrals (Theorem 93) gives that there is a ξk ∈ [xk−1,xk] such that

thus, in conclusion,

(Recall that as the partition x0>x1>…>xn is equidistant, xk −xk−1 = 1∕n.)
Now, using P(X(n) = xk) =
, we obtain
![∑n H[X (n)] = − P (X (n) = xk )log P(X (n) = xk) k=1 n = − ∑ fX-(ξk)-log fX-(ξk)- n n k=n1 n = − ∑ fX-(ξk)-log f (ξ )+ log n∑ fX(ξk). n X k n k=1 k=1](https://static.packt-cdn.com/products/9781837027873/graphics/media/file2026.png)
Both of these terms are Riemann-sums, approximating the integral of the functions inside. If n is large, and the interval [a,b] is big enough, then
![n ∫ − ∑ fX-(ξk)logf (ξ ) ≈ − ∞ f (x)logf (x)dx = h[X ], n X k −∞ X X k=1](https://static.packt-cdn.com/products/9781837027873/graphics/media/file2027.png)
and

implying
![H [X (n)] ≈ h [X ]+ logn.](https://static.packt-cdn.com/products/9781837027873/graphics/media/file2029.png)
This is quite surprising, as one would expect H[X(n)] to converge towards h(X). This is not the case. In fact,
![lim (H [X (n)]− log n) = h[X ] n→ ∞](https://static.packt-cdn.com/products/9781837027873/graphics/media/file2030.png)
holds.
It’s time for the examples.
Example 1. The uniform distribution. (See the definition of the uniform distribution in Section 19.3.4.) Let X ∼ Uniform(a,b). Then,
![∫ b -1--- --1-- h[X ] = − b− a log b− a dx a = log(b− a),](https://static.packt-cdn.com/products/9781837027873/graphics/media/file2031.png)
which is similar to the discrete uniform case. However, there is one notable difference: h(X) is negative when b−a>1. This is in stark contrast with the Shannon entropy, which is always nonnegative.
Example 2. The normal distribution. (See the definition of the normal distribution in Section 19.3.6.) Let X ∼𝒩(μ,σ2). Then,
![∫ ∞ 1 (x−μ)2 ( 1 (x−μ)2) h[X ] = − -√---e− 2σ2 log -√----e− 2σ2 dx − ∞ σ 2π∫ σ 2π ∫ ( √ ---) ∞ --1---− (x−2σμ2)2- ∞ (x−-μ-)2---1---− (x−2μσ)22 = log σ 2π −∞ σ√ 2πe dx+ − ∞ 2σ2 σ√ 2πe dx ◟--------◝◜--------◞ ◟------------◝◜------------◞ =1 = 21σ2Var[X ]= 12 1 ( 2 ) = 2- 1+ log(σ 2π ) .](https://static.packt-cdn.com/products/9781837027873/graphics/media/file2032.png)
Depending on the value of σ, the value of h[X] can be negative here as well.
Previously, we have seen that for discrete distributions on a given finite set, the uniform distribution maximizes entropy, as Theorem 138 claims.
What is the analogue of Theorem 138 for continuous distributions? Take a wild guess. If we let X be any continuous distribution, then, as we have seen,
![h[Uniform (a,b)] = log(b− a),](https://static.packt-cdn.com/products/9781837027873/graphics/media/file2033.png)
which can assume any real number. Similarly to the discrete case, we have to make restrictions; this time, we’ll fix the variance. Here is the result.
Theorem 139. (Maximizing the differential entropy)
Let X be a continuous random variable with variance σ2. Then
![h[X ] ≤ h [𝒩 (0,σ2)],](https://static.packt-cdn.com/products/9781837027873/graphics/media/file2034.png)
and h[X] = h[𝒩(0,σ2)] if and only if X ∼𝒩(μ,σ2).
Again, we are not going to prove this. You can check Bishop’s Pattern Recognition and Machine Learning for more details.
Bookmark
20.7 The Maximum Likelihood Estimation
Section titled “20.7 The Maximum Likelihood Estimation”I am an evangelist for simple ideas. Stop me any time you want, but whichever field I was in, I’ve always been able to find a small set of mind-numbingly simple ideas making the entire shebang work. (Not that you could interrupt me, as this is a book. Joke’s on you!)
Let me give you a concrete example that’s on my mind. What do you think enabled the rise of deep learning, including neural networks with billions of parameters? Three ideas as simple as ABC:
- that you can optimize the loss function by going against its gradient (no matter the number of parameters),
- that you can efficiently compute the gradient with a clever application of the chain rule and matrix multiplication,
- and that we can perform matrix operations blazingly fast on a GPU.
Sure, there’s a great tower of work built upon these ideas, but these three lie at the very foundation of machine learning today. Ultimately, these enable you to converse with large language models. To have your car cruise around town while you read the newspaper. To predict the exact shape of massive amino-acid chains called proteins, responsible for building up every living thing. (Including you.)
Gradient descent, backpropagation, and high-performance linear algebra are on the practical side of the metaphorical machine learning coin. If we conjure up a parametric model, we can throw some extremely powerful tools at it.
But where do our models come from?
As I’ve said, there is a small set of key ideas that go a long way. We are about to meet one: the maximum likelihood estimation.
20.7.1 Probabilistic modeling 101
Section titled “20.7.1 Probabilistic modeling 101”As a self-proclaimed evangelist of simple ideas, I’ll start with a simple example to illustrate a simple idea.
Pick up a coin and toss it a few times, recording each outcome. The question is, once more, simple: what’s the probability of heads? We can’t just immediately assume p = 1∕2, that is, a fair coin. For instance, one side of our coin could be coated with lead, resulting in a bias. To find out, let’s perform some statistics. (Rolling up my sleeves, throwing down my gloves.)
Mathematically speaking, we can model coin tosses with the Bernoulli distribution (Section 19.2.1):

where
- X is the random variable representing the outcome of a single toss,
- X = 1 for heads and X = 0 for tails,
- and p ∈ [0,1] is the probability of heads.
That’s just the model. We’re here to estimate the parameter p, and this is what we have statistics for.
Tossing up the coin n times yields the zero-one sequence x1,x2,…,xn, where each xi is a realization of a Bernoulli-distributed random variable Xi ∼ Bernoulli(p), independent of each other.
As we saw previously when discussing the law of large numbers (Theorem 137), one natural idea is to compute the sample mean to estimate p, which is coincidentally the expected value of X. To move beyond empirical estimates, let’s leverage that, this time, we have a probabilistic model.
The key question is this: which parameter p is the most likely to produce our sample?
In the language of probability, this question is answered by maximizing the likelihood function

where P(Xi = xi∣p) represents the probability of observing xi given a fixed parameter p. The larger the LLH(p;x1,…,xn), the more likely the parameter p is. In other words, our estimate of p is going to be
![ˆp = argmaxp ∈[0,1]LLH (p;x1,...,xn).](https://static.packt-cdn.com/products/9781837027873/graphics/media/file2037.png)
Let’s find it.
In our concrete case, P(Xi = xi∣p) can be written as

Algebra doesn’t welcome if-else type functions, so with a clever mathematical trick, we write P(Xi = xi∣p) as

making the likelihood function be

(We’ll often write LLH(p) to minimize notational complexity.)
This is still not easy to optimize, as it is composed of the product of exponential functions. So, here’s another mathematical trick: take the logarithm to turn the product into a sum.
As the logarithm is increasing, it won’t change the optima, so we’re good to go:
![∏n log LLH (p) = log pxi(1− p )1−xi i=1 ∑n [ ] = log pxi(1 − p)1−xi i=1 ∑n [ ] = logpxi + log(1− p)1−xi i=1 ∑n ∑n = logp xi + log(1 − p) (1− xi). i=1 i=1](https://static.packt-cdn.com/products/9781837027873/graphics/media/file2041.png)
Trust me, this is much better. According to the second derivative test (Theorem 87), we can find the maxima by
- solving
log LLH(p) = 0 to find the critical point p̂ , - then showing that p̂ is a maximum because
log LLH(p)>0.
Let’s get to it.
As
log p =
and
log(1 −p) = −
, we have

Solving
log LLH(p;x1,…,xn) = 0 yields a single solution

(Pick up a pen and paper and calculate the solution yourself.) Regarding the second derivative, we have

which is uniformly negative. Thus, p̂ =
∑ i=1nxi is indeed a (local) maximum. Yay!
In this case, the maximum likelihood estimate is identical to the sample mean. Trust me, this is one of the rare exceptions. Think of it as validating the sample mean: we’ve obtained the same estimate through different trains of thought, so it must be good.
20.7.2 Modeling heights
Section titled “20.7.2 Modeling heights”Let’s continue with another example. The coin-tossing example demonstrated the discrete case. It’s time to move into the continuous domain!
This time, we are measuring the heights of a high school class, and we want to build a probabilistic model of it. A natural idea is to assume the heights to come from a normal distribution X ∼𝒩(μ,σ2). (Check Section 19.3.6 for the normal distribution.)
Our job is to estimate the expected value μ and the variance σ2. Let’s go, maximum likelihood!
To make the problem mathematically precise, we have the measurements x1,…,xn, coming from independent and identically distributed random variables Xi ∼𝒩(μ,σ2). However, there’s a snag: as our random variables are continuous,

(As all terms of the product are zero.) How can we define the likelihood function, then? No worries: even though we don’t have a mass function, we have density! Thus, the likelihood function defined by

where fXi(x) is the probability density function of Xi.
Let’s maximize it. The idea is similar: take the logarithm, find the critical points, then use the second derivative test. Here we go:

Just the usual business from now on. The derivatives are given by

With a bit of number-crunching (that you should attempt to carry out by yourself), we get that ∂μ log LLH(μ,σ) = 0 implies

and
log LLH(μ,σ) implies

We won’t do the second derivative test here, but trust me: it’s a maximum, leaving us with the estimates

Again, the sample mean and variance. Think of it this way: defaulting to the sample mean and variance is the simplest thing to do, yet even clever methods like the maximum likelihood estimation yield them as parameter estimates.
After working out the above two examples in detail, we are ready to abstract away the details and introduce the general problem.
20.7.3 The general method
Section titled “20.7.3 The general method”We’ve seen how maximum likelihood estimation works. Now, it’s time to construct the abstract mathematical framework.
Definition 99. (The likelihood function)
Let P𝜃 be a probability distribution parametrized by the parameter 𝜃 ∈ℝk, and let x1,…,xn ∈ ℝd be an independent realization of the probability distribution. (That is, the samples are coming from independent and identically distributed random variables X1,…,Xn, distributed according to P𝜃.)
The likelihood function of 𝜃 given the sample x1,…,xn is defined by
(a)

if P𝜃 is discrete, and
(b)

if P𝜃 is continuous, where f𝜃 is the probability density function of P𝜃.
We’ve already seen two examples of the likelihood function: for the Bernoulli-distribution Bernoulli(p), given by

and for the normal distribution 𝒩(μ,σ), given by

Intuitively, the likelihood function LLH(𝜃;x1,…,xn) expresses the probability of our observation x1,…,xn if the parameter 𝜃 is indeed true. The maximum likelihood estimate is the parameter
that maximizes this probability; that is, under which the observation is the most likely.
Definition 100. (The maximum likelihood estimate)
Let P𝜃 be a probability distribution parametrized by the parameter 𝜃 ∈ℝk, and let x1,…,xn ∈ ℝd be an independent realization of the probability distribution.
The maximum likelihood estimate of 𝜃 is given by

In both examples, we used the logarithm to turn the product into a sum. Use it once and it’s a trick; use it (at least) twice and it’s a method. Here’s the formal definition.
Definition 101. (The log-likelihood function)
Let P𝜃 be a probability distribution parametrized by the parameter 𝜃 ∈ℝk, and let x1,…,xn ∈ ℝd be an independent realization of the probability distribution.
The log-likelihood function of 𝜃 given the sample x1,…,xn is defined by

where LLH(𝜃;x1,…,xn) is the likelihood function.
In a classical statistical setting, the maximum likelihood estimation is done via
- pulling a parametric probabilistic model out from the mathematician’s hat,
- massaging the (log-)likelihood function until we obtain an analytically manageable form,
- and solving ∇LLH = 0 (or ∇log LLH = 0) to obtain the parameter estimate.
Statistics can be extremely powerful under specific circumstances, but let’s face it: the above method has quite a few weaknesses. First, constructing a tractable probabilistic model is a challenging task, burdened by the experts’ inherent bias. (It’s no accident that I indirectly compared the modeling process to pulling a rabbit out of a hat.) Moreover, the more complex the model, the more complex the likelihood function is. Which, in turn, increases the complexity of our optimization problem.
Why did we spend quite a few pages learning this ancient technique, then?
Because its idea is fundamental in machine learning, we’ll arrive at (somewhere near the) state of the art by breaking down its barriers one by one. Is modeling hard? Let’s construct a function with BILLIONS of parameters that’ll do the job. Is optimization computationally intensive? Fear not. We have clusters of GPUs at our disposal.
20.7.4 The German tank problem
Section titled “20.7.4 The German tank problem”One more example before finishing up, straight from World War II. Imagine you are an Allied intelligence officer tasked to estimate the size of a German armored division. (That is, to guess the number of tanks.)
There was no satellite imagery back in the day, so there’s only a little to go on, except for a tiny piece of information: the serial numbers of the enemy’s destroyed tanks. What can we do with these?
Without detailed knowledge of the manufacturing process, we can assume that the tanks are labeled sequentially as they roll out from the factory. We also don’t know how the tanks are distributed between the battlefields.
These two pieces of knowledge (or lack of knowledge, to be more precise) translate to a simple probabilistic model: encountering an enemy tank is the same as drawing from the distribution Uniform(N), where N is the total number of tanks. Thus, if x1,…,xn are the serial numbers of destroyed tanks, we can use the maximum likelihood method to estimate N.
Let’s do it. The likelihood function for the discrete uniform distribution Uniform(N) is given by

where the probability P(Xi = xi) has a quite peculiar form:

Keeping in mind that x1,…,xn ≤N (as no observed serial number can be larger than the total number of tanks), we have

Ponder on this a minute: the larger the N, the smaller the LLH(N) is. Thus, the maximum likelihood estimate is the smallest possible choice

In other words, our guess about the number of tanks is the largest serial number we’ve encountered.
What do you think about this estimate? I won’t lie; I am not a big fan. The German tank problem highlights the importance of modeling assumptions in statistics. The final estimate
is the outcome of our choice of Uniform(N). Common wisdom in machine learning is “garbage in, garbage out.” It is true for modeling as well.
Bookmark
20.8 Summary
Section titled “20.8 Summary”In this chapter, we have learned about the concept of the expected value. Mathematically speaking, the expected value is defined by
![∑ 𝔼[X ] = xkP (X = xk) k](https://static.packt-cdn.com/products/9781837027873/graphics/media/file2077.png)
for discrete random variables and
![∫ ∞ 𝔼[X ] = xfX(x)dx −∞](https://static.packt-cdn.com/products/9781837027873/graphics/media/file2078.png)
for continuous ones. Although these formulas involve possibly infinite sums and integrals, the underlying meaning is simple: 𝔼[X] represents the average outcome of X, weighted by the underlying probability distribution.
According to the law of large numbers, the expected value also describes a long-term average: if the independent and identically distributed random variables X1,X2,… describe the outcomes of a repeated experiment — say, betting a hand in poker — then the sample average converges to the joint expected value, that is,
![1 ∑n lim -- Xi = 𝔼[X1 ] n→ ∞ n i=1](https://static.packt-cdn.com/products/9781837027873/graphics/media/file2079.png)
holds with probability 1. In a sense, the law of large numbers allows you to glimpse into the future and see what happens if you make the same choice. In the case of poker, if you only make bets with a positive expected value, you’ll win in the long run.
In machine learning, the LLN also plays an essential role. Check out the mean-squared error

once more. If the number of samples (n) is in the millions, computing the gradient of this sum is not feasible. However, the mean-squared error is the sample average of the prediction errors; thus, it’s enough to sample a smaller amount. This is the core principle behind stochastic gradients, an idea that makes machine learning on a large scale feasible.
With this chapter, our journey comes to a close. Still, there’s so much to learn; I could probably write this book until the end of time. Sadly, we have to stop somewhere. Now, instead of giving a summary of all that’s in the book, let’s talk about the most important message: learning never ends.
It’s a spiral that you continue to ascend, meeting familiar landscapes from higher and higher vantage points. If you keep going, you’ll know what I’m talking about.
If you lead an intellectually challenging life, you’ll also find that knowledge is like keeping a dozen leaky cups full of water. If your focus shifts from one, it’ll empty faster than you think. In other words, you’ll lose it if you don’t use it. This is completely normal. The good news is, if you already have a good foundation, refilling the cup can be done quickly. Sometimes, simply glancing at a page from a book you read long ago can do the trick.
This is how I know that it’s not goodbye. If you have found the book useful and continue down the rabbit hole that is machine learning, we’ll meet again with probability one. You just have to keep going.
Bookmark
20.9 Problems
Section titled “20.9 Problems”Problem 1. Let X,Y : Ω →ℝ be two random variables.
(a) Show that if X ≥ 0, then 𝔼[X] ≥ 0.
(b) Show that if X ≥Y , then 𝔼[X] ≥𝔼[Y ].
Problem 2. Let X : Ω →ℝ be a random variable. Show that if Var[X] = 0, then X assumes only a single value. (That is, the set X(Ω) = {X(ω) : ω ∈ Ω} has only a single element.)
Problem 3. Let X ∼ Geo(p) be a geometrically distributed (Section 19.2.3) discrete random variable. Show that
![H [X] = − plogp-+-(1−-p)log(1−-p)-. p](https://static.packt-cdn.com/products/9781837027873/graphics/media/file2081.png)
Hint: Use that for any q ∈ (0,1), ∑ k=1∞kqk−1 = (1 −q)−2.
Problem 4. Let X ∼ exp(λ) be an exponentially distributed continuous random variable. Show that
![h [X ] = 1 − logλ.](https://static.packt-cdn.com/products/9781837027873/graphics/media/file2082.png)
Problem 5. Find the maximum likelihood estimation for the λ parameter of the exponential distribution.