TExcelTAD
Home › Probability Theory › Conditional Expectation

Conditional Expectation

The expected value of XX given what you know about YY is the best prediction of XX from YY. Conditional expectation turns this idea into a random variable, and it is the engine behind first-step analysis, regression and many elegant probability arguments.

Definition

For discrete variables,

E[X∣Y=y]=∑xx Pr⁡[X=x∣Y=y]E[X \mid Y = y] = \sum_x x \, \Pr[X = x \mid Y = y]

and for densities replace the sum by ∫xf(x∣y) dx\int x f(x \mid y)\,dx. As a function of yy this is a number; plugging in the random YY gives the random variable E[X∣Y]E[X \mid Y].

The law of total expectation

Averaging the conditional expectations gives back the plain expectation:

E[X]=E[E[X∣Y]]=∑yE[X∣Y=y]Pr⁡[Y=y]E[X] = E\big[E[X \mid Y]\big] = \sum_y E[X \mid Y = y] \Pr[Y = y]

Example: roll a die to get NN, then toss NN coins. The expected number of heads is E[E[H∣N]]=E[N/2]=3.5/2=1.75E[E[H \mid N]] = E[N/2] = 3.5/2 = 1.75.

python · try it yourself
from fractions import Fraction
from math import comb

EH = sum(Fraction(1, 6) * Fraction(n, 2) for n in range(1, 7))
print("E[heads] by total expectation:", EH)

# brute force: full distribution of H
dist = {}
for n in range(1, 7):
    for h in range(n + 1):
        dist[h] = dist.get(h, 0) + Fraction(1, 6) * Fraction(comb(n, h), 2 ** n)
print("E[heads] from the full distribution:", sum(h * p for h, p in dist.items()))
print("E[N | H = 6] =", sum(n * Fraction(1, 6) * Fraction(comb(n, 6), 2 ** n) for n in range(1, 7)) / dist[6])
E[heads] by total expectation: 7/4
E[heads] from the full distribution: 7/4
E[N | H = 6] = 6

The last line runs the conditioning in reverse: if 6 heads were seen, the die must have shown 6.

Random sums and Wald's identity

If NN is a non-negative integer random variable and X1,X2,…X_1, X_2, \ldots are independent copies of XX, also independent of NN, then

E[∑i=1NXi]=E[N] E[X]E\left[\sum_{i=1}^{N} X_i\right] = E[N]\,E[X]

because conditioning on N=nN = n gives nE[X]nE[X]. A shop with on average 40 customers a day, each spending on average 25, takes in 1000 a day on average. The variance has an extra term: Var⁡=E[N]Var⁡(X)+Var⁡(N)E[X]2\operatorname{Var} = E[N]\operatorname{Var}(X) + \operatorname{Var}(N)E[X]^2 (the law of total variance).

python · try it yourself
import numpy as np

rng = np.random.default_rng(3)
days = 50_000
N = rng.poisson(40, days)
totals = np.array([rng.exponential(25, n).sum() for n in N])
print("mean daily total:", round(totals.mean(), 1), " E[N] E[X] =", 40 * 25)
theory_var = 40 * 25 ** 2 + 40 * 25 ** 2            # E[N]Var(X) + Var(N)E[X]^2
print("sd of daily total:", round(totals.std(), 1), " theory:", round(np.sqrt(theory_var), 1))
mean daily total: 1001.1  E[N] E[X] = 1000
sd of daily total: 224.2  theory: 223.6

Best prediction

Among all functions gg, the one that minimises the mean squared error E[(X−g(Y))2]E[(X - g(Y))^2] is g(Y)=E[X∣Y]g(Y) = E[X \mid Y]. Linear regression approximates this by restricting gg to lines; for a bivariate normal pair the conditional expectation is exactly linear, E[Y∣X=x]=μY+ρσYσX(x−μX)E[Y \mid X = x] = \mu_Y + \rho\frac{\sigma_Y}{\sigma_X}(x - \mu_X). Since ∣ρ∣<1\lvert \rho \rvert < 1, predictions are pulled toward the mean: regression to the mean. Tall parents have tall children, but on average less extremely tall.

python · try it yourself
import numpy as np

rng = np.random.default_rng(5)
rho = 0.5
z1, z2 = rng.standard_normal((2, 400_000))
parent, child = z1, rho * z1 + np.sqrt(1 - rho ** 2) * z2
for lo in [1.0, 2.0]:
    sel = (parent > lo) & (parent < lo + 0.1)
    print(f"parents near {lo + 0.05:.2f} sd: children average {child[sel].mean():.3f} sd   (rho x = {rho * (lo + 0.05):.3f})")
parents near 1.05 sd: children average 0.517 sd   (rho x = 0.525)
parents near 2.05 sd: children average 1.036 sd   (rho x = 1.025)

In software

Every regression or classification model estimates a conditional expectation (E[Y∣features]E[Y \mid \text{features}] or Pr⁡[class∣features]\Pr[\text{class} \mid \text{features}]). Reinforcement learning's value functions are conditional expectations of future reward given the current state. Regression to the mean explains why "the worst-performing servers improved after we restarted them" may say nothing about the restart.

Exercises

Exercise 1: Two-stage dice

Roll a die to get NN, then roll NN dice and add them. What is the expected total?

Answer

3.5⋅3.5=12.253.5 \cdot 3.5 = 12.25.

Solution

Wald's identity: E[N]E[X]=3.5⋅3.5E[N]E[X] = 3.5 \cdot 3.5.

Exercise 2: A miner

A miner trapped in a mine picks one of three doors at random each time. Door 1 leads out in 2 hours; doors 2 and 3 bring him back after 3 and 5 hours. What is the expected time to get out?

Answer

10 hours.

Solution

First-step analysis: T=13(2)+13(3+T)+13(5+T)T = \frac{1}{3}(2) + \frac{1}{3}(3 + T) + \frac{1}{3}(5 + T), so T/3=10/3T/3 = 10/3 and T=10T = 10.

Exercise 3: Check the miner (code)

Simulate the miner problem.

Answer

The average time is close to 10.

Solution
python · try it yourself
import random

rng = random.Random(8)
def escape():
    t = 0
    while True:
        door = rng.randint(1, 3)
        if door == 1:
            return t + 2
        t += 3 if door == 2 else 5

runs = 100_000
print(round(sum(escape() for _ in range(runs)) / runs, 3))
9.947

Test yourself

The law of total expectation states that…

  1. E[X]=E[E[X∣Y]]E[X] = E[E[X \mid Y]]
  2. E[XY]=E[X]E[Y]E[XY] = E[X]E[Y]
  3. E[X∣Y]=E[X]E[X \mid Y] = E[X]
  4. E[X+Y]=E[X]E[X + Y] = E[X]

Which function of YY minimises E[(X−g(Y))2]E[(X - g(Y))^2]?

  1. E[X]E[X]
  2. E[X∣Y]E[X \mid Y]
  3. the median of YY
  4. YY itself