Module contents
Lesson 12 of 24Advanced 110 min

Conditional expectation

Conditional expectation given a σ-algebra is the best prediction with available information: it exists by Radon-Nikodym and is an orthogonal projection in L². It underlies RL value functions, optimal diffusion denoisers, derivative prices and martingales. Resolve the Borel-Kolmogorov paradox using regular conditional distributions.

After this lesson you can

  • Define 𝔼[Y | G] given a σ-algebra and prove existence and almost-sure uniqueness.
  • Interpret 𝔼[Y | X] as an orthogonal projection in L² and the best squared-error predictor.
  • Use the tower property, taking out what is known, independence and conditional Jensen in derivations.
  • Apply the laws of total expectation and total variance.
  • Explain the Borel-Kolmogorov paradox and the role of regular conditional distributions.

Before you start

Motivation: predicting with what you know

One object appears under different names in nearly everything you will build:

  • A state value in RL. A policy’s value function is V(s)=E[Gt∣St=s]V(s) = \E[G_t \given S_t = s], the expected future discounted reward from ss. It is not a fixed number: it is a function of state and, evaluated at random state StS_t, a random variable. Bellman equations follow from one property of this object, studied here.
  • The optimal diffusion denoiser. A diffusion model trains a network D(xt)D(\vb{x}_t) receiving noisy image xt=x0+σε\vb{x}_t = \vb{x}_0 + \sigma\vb{\eps} and minimizing E∥D(xt)−x0∥2\E\norm{D(\vb{x}_t) - \vb{x}_0}^2. Whatever the architecture, the best it can learn is E[x0∣xt]\E[\vb{x}_0 \given \vb{x}_t], and Tweedie’s formula relates it to the gradient of log⁡pt\log p_t.
  • A derivative price. At interest rate rr, the time-tt price of a contract paying HH at TT is e−r(T−t) EQ[H∣Ft]e^{-r(T - t)}\,\E_{\mathbb{Q}}[H \given \mathcal{F}_t], an expectation under the risk-neutral measure depending on the entire market history to tt, not one value.
  • Any squared-loss regression. A network minimizing E[(Y−f(X))2]\E[(Y - f(X))^2] estimates E[Y∣X]\E[Y \given X] (the functional that loss elicits).

In all four cases the question is the same: what is the best prediction of a variable YY given available information? Information may be another variable’s value, a vector or an entire history. The answer is conditional expectation. This lesson constructs it with the rigor required by martingales and RL theory while retaining the simple intuition: average YY over everything unknown, holding what you know fixed.

The plan:

  1. The discrete case, averaging within groups, and the density case.
  2. The general definition given a σ-algebra, with Radon-Nikodym existence and almost-sure uniqueness.
  3. Geometry: in L2L^2, conditional expectation is an orthogonal projection and therefore the best predictor.
  4. Properties used throughout derivations: tower, taking out what is known, independence and Jensen.
  5. The laws of total expectation and total variance.
  6. Conditioning on probability-zero events: regular conditional distributions and the Borel-Kolmogorov paradox.
  7. The best predictor versus the best linear predictor, and when they agree.

The discrete case: an average within each group

Roll two dice. Let XX be the first and YY their sum. If you know X=4X = 4, the sum is 44 plus an unseen die, and your best prediction is 4+3.5=7.54 + 3.5 = 7.5. In general, using elementary conditional probability,

E[Y∣X=x]=∑yy P(Y=y∣X=x)=E[Y 1{X=x}]P(X=x)=x+3.5,P(X=x)>0.\E[Y \given X = x] = \sum_y y\,\Pr(Y = y \given X = x) = \frac{\E[Y\,\ind_{\{X = x\}}]}{\Pr(X = x)} = x + 3.5, \qquad \Pr(X = x) > 0.

This is a number for each xx: a function g(x)=x+3.5g(x) = x + 3.5. But what happens when you do not fix xx beforehand and evaluate gg at the random variable itself?

E[Y∣X]:=g(X)=X+3.5.\E[Y \given X] := g(X) = X + 3.5.

E[Y∣X]\E[Y \given X] is a random variable: it takes value 4.54.5 if a 1 is rolled, 5.55.5 for a 2, and so on up to 9.59.5. It is the prediction of YY you would make after seeing XX, viewed before seeing it. Two facts characterize it and seed the general definition:

  1. It depends only on XX. It is constant on each event {X=x}\{X = x\}.
  2. It is correct on average within each event determined by XX. For each xx, E[g(X) 1{X=x}]=g(x)P(X=x)=E[Y 1{X=x}]\E\big[g(X)\,\ind_{\{X = x\}}\big] = g(x)\Pr(X = x) = \E[Y\,\ind_{\{X = x\}}], and summing gives E[g(X) 1{X∈B}]=E[Y 1{X∈B}]\E\big[g(X)\,\ind_{\{X \in B\}}\big] = \E[Y\,\ind_{\{X \in B\}}] for every set BB.

Geometrically, XX partitions Ω\Omega into six pieces {X=1},…,{X=6}\{X = 1\}, \dots, \{X = 6\}, and E[Y∣X]\E[Y \given X] replaces YY by its mean on each piece. What XX knows is retained; what it does not know (the second die) is averaged. Summing over pieces gives the law of total expectation, the expectation version of total probability:

E[Y]=∑xE[Y∣X=x] P(X=x)=E[E[Y∣X]].\E[Y] = \sum_x \E[Y \given X = x]\,\Pr(X = x) = \E\big[\E[Y \given X]\big].

With densities

If (X,Y)(X, Y) has joint density p(x,y)p(x, y) and marginal pX(x)>0p_X(x) > 0, conditional density p(y∣x)=p(x,y)/pX(x)p(y \given x) = p(x, y)/p_X(x) gives

E[Y∣X=x]=∫y p(y∣x) ⁣dy=:g(x),E[Y∣X]=g(X).\E[Y \given X = x] = \int y\,p(y \given x)\dd y =: g(x), \qquad \E[Y \given X] = g(X).

For example, if (X,Y)(X, Y) is uniform on triangle 0<y<x<10 < y < x < 1, the joint density is 22 there, pX(x)=2xp_X(x) = 2x and p(y∣x)=1/xp(y \given x) = 1/x on (0,x)(0, x): given X=xX = x, YY is uniform on (0,x)(0, x) and E[Y∣X]=X/2\E[Y \given X] = X/2. The second property still holds, now with integrals: for Borel BB,

E[g(X) 1{X∈B}]=∫Bg(x) pX(x) ⁣dx=∫B ⁣∫y p(x,y) ⁣dy ⁣dx=E[Y 1{X∈B}].\E\big[g(X)\,\ind_{\{X \in B\}}\big] = \int_B g(x)\,p_X(x)\dd x = \int_B\!\int y\,p(x, y)\dd y\dd x = \E[Y\,\ind_{\{X \in B\}}].

But there is a problem absent in the discrete case: each event {X=x}\{X = x\} has probability zero, so E[Y∣X=x]\E[Y \given X = x] cannot be defined as a ratio. The density formula works, but what is it calculating? Changing pp on a null set (another version of the same density) changes g(x)g(x) at those points. Without densities—singular laws, conditioning on an infinite history or a process—there is no formula. Kolmogorov’s 1933 solution is to condition not on events but on information: a σ-algebra.

Average with available information

Recall that the generated σ-algebra σ(X)\sigma(X) is the collection of events determined by knowing XX. More generally a σ-algebra G⊂F\mathcal{G} \subset \mathcal{F} is a state of information: events A∈GA \in \mathcal{G} are those whose occurrence you know. The figure makes this concrete with Ω=[0,1]\Omega = [0, 1], uniform probability and G\mathcal{G} generated by a partition into intervals.

InteractiveAverage with available information
−1010.540.58−0.49−0.5100.250.50.751ω
  • Y(ω)Y(\omega)
  • Z=E[Y∣G]Z = \E[Y \given \mathcal{G}], piecewise mean
Variable Y(ω)Y(\omega)
Partition
4 pieces
Tower property
Pieces of G\mathcal{G}4
E[(Y−E[Y∣G])2]\E[(Y - \E[Y \given \mathcal{G}])^2]0.1354
Explained variance Var⁡(Z)/Var⁡(Y)\Var(Z)/\Var(Y)67.4 %
E[Z]\E[Z] versus E[Y]\E[Y]0.0293 = 0.0293
max⁡A∣E[(Y−Z) 1A]∣\max_A \abs{\E[(Y - Z)\,\ind_A]}, A∈GA \in \mathcal{G}0.000000
E[(Y−Z) ω]\E[(Y - Z)\,\omega]−0.0043
The blue curve is a variable Y(ω)Y(\omega) on Ω=[0,1]\Omega = [0, 1] with uniform probability. Cuts divide Ω\Omega into pieces and generate a finite σ-algebra G\mathcal{G}; knowing G\mathcal{G} means knowing which piece contains ω\omega. Magenta shows E[Y∣G]\E[Y \given \mathcal{G}]: the average of YY on each piece. Add or remove cuts, or increase the dyadic level, and watch squared error fall. The final two readings compare residual Y−ZY - Z with piece indicators (always zero) and with ω\omega, which is not G\mathcal{G}-measurable (almost never zero). Enable the tower: if H\mathcal{H} cuts are among G\mathcal{G} cuts, averaging twice equals averaging once; otherwise it fails. With the stepped shape, choose cuts at jumps.

Three observations the definition will capture:

  1. E[Y∣G]\E[Y \given \mathcal{G}] is G\mathcal{G}-measurable: constant on each piece because G\mathcal{G} information cannot distinguish points in that piece.
  2. It is correct on average on each G\mathcal{G} event: reading max⁡A∣E[(Y−Z)1A]∣\max_A \abs{\E[(Y - Z)\ind_A]} is zero for every union of pieces.
  3. More information, better prediction: refining the partition lowers error, and in the dyadic limit E[Y∣Gk]→Y\E[Y \given \mathcal{G}_k] \to Y. Without cuts, G={∅,Ω}\mathcal{G} = \{\varnothing, \Omega\} and prediction is the mean E[Y]\E[Y], the best guess without information. Sequence E[Y∣G0],E[Y∣G1],…\E[Y \given \mathcal{G}_0], \E[Y \given \mathcal{G}_1], \dots with increasingly fine dyadic partitions is a first example of a martingale, and its convergence to YY is an instance of the martingale convergence theorem.

General definition: existence and uniqueness

Condition 1 says “use only what you know”; condition 3 says “be correct on average over everything you know.” Notice YY satisfies 2 and 3, but generally not 1: the problem is precisely to find the G\mathcal{G}-measurable variable behaving like YY on G\mathcal{G} events.

If G=σ(X)\mathcal{G} = \sigma(X), the Doob-Dynkin lemma from lesson 4 says every σ(X)\sigma(X)-measurable variable has form g(X)g(X) with Borel gg. Thus E[Y∣X]=g(X)\E[Y \given X] = g(X), and define E[Y∣X=x]:=g(x)\E[Y \given X = x] := g(x). This gg is the regression function of YY on XX and, as we will see, is determined only PX\Pr_X-almost surely: at an isolated xx with P(X=x)=0\Pr(X = x) = 0 its value has no intrinsic meaning.

Proof

Uniqueness. Z−Z′Z - Z' is G\mathcal{G}-measurable, so Aε={Z−Z′>ε}∈GA_\eps = \{Z - Z' > \eps\} \in \mathcal{G} for each ε>0\eps > 0. By condition 3 applied to both,

0=E[Y 1Aε]−E[Y 1Aε]=E[(Z−Z′) 1Aε]≥ε P(Aε),0 = \E[Y\,\ind_{A_\eps}] - \E[Y\,\ind_{A_\eps}] = \E[(Z - Z')\,\ind_{A_\eps}] \ge \eps\,\Pr(A_\eps),

thus P(Aε)=0\Pr(A_\eps) = 0. Since {Z>Z′}=⋃nA1/n\{Z > Z'\} = \bigcup_n A_{1/n} is a countable union of null sets, P(Z>Z′)=0\Pr(Z > Z') = 0, and symmetrically P(Z<Z′)=0\Pr(Z < Z') = 0.

Existence. First suppose Y≥0Y \ge 0. Define two finite measures on measurable space (Ω,G)(\Omega, \mathcal{G}), not on (Ω,F)(\Omega, \mathcal{F}): restriction PG=P∣G\Pr_{\mathcal{G}} = \Pr|_{\mathcal{G}} and

ν(A)=E[Y 1A],A∈G.\nu(A) = \E[Y\,\ind_A], \qquad A \in \mathcal{G}.

ν\nu is a measure by monotone convergence, finite because ν(Ω)=E[Y]<∞\nu(\Omega) = \E[Y] < \infty, and absolutely continuous with respect to PG\Pr_{\mathcal{G}}: if P(A)=0\Pr(A) = 0, then Y1A=0Y\ind_A = 0 almost surely and ν(A)=0\nu(A) = 0. By the Radon-Nikodym theorem applied on (Ω,G)(\Omega, \mathcal{G}), there exists Z= ⁣dν/ ⁣dPG≥0Z = \dd\nu/\dd\Pr_{\mathcal{G}} \ge 0, G\mathcal{G}-measurable, with ν(A)=∫AZ ⁣dPG\nu(A) = \int_A Z \dd\Pr_{\mathcal{G}} for every A∈GA \in \mathcal{G}. For a G\mathcal{G}-measurable function, integration with respect to PG\Pr_{\mathcal{G}} or P\Pr agrees (true for G\mathcal{G} event indicators, by linearity for simple functions and by monotone convergence in general), so E[Z 1A]=E[Y 1A]\E[Z\,\ind_A] = \E[Y\,\ind_A]. Taking A=ΩA = \Omega, E[Z]=E[Y]<∞\E[Z] = \E[Y] < \infty. For general YY, Y=Y+−Y−Y = Y^+ - Y^- and E[Y+∣G]−E[Y−∣G]\E[Y^+ \given \mathcal{G}] - \E[Y^- \given \mathcal{G}] satisfies all three conditions.

∎

Consider why the proof works. Applying Radon-Nikodym on (Ω,F)(\Omega, \mathcal{F}) would give  ⁣dν/ ⁣dP=Y\dd\nu/\dd\Pr = Y, adding nothing. Restricting both measures to G\mathcal{G} forces the density to be G\mathcal{G}-measurable: conditional expectation is the Radon-Nikodym derivative of Y  ⁣dPY\,\dd\Pr viewed at G\mathcal{G}‘s resolution. That is exactly what the figure did: distribute each piece’s mass ν(A)\nu(A) uniformly (according to P\Pr) within it.

Three extreme cases clarify the idea:

  • No information, G={∅,Ω}\mathcal{G} = \{\varnothing, \Omega\}: the only G\mathcal{G}-measurable variables are constants, and condition 3 with A=ΩA = \Omega forces the constant to be E[Y]\E[Y].
  • Complete information, G=F\mathcal{G} = \mathcal{F} (or YY already G\mathcal{G}-measurable): E[Y∣G]=Y\E[Y \given \mathcal{G}] = Y.
  • Countable partition {B1,B2,… }\{B_1, B_2, \dots\} of Ω\Omega generating G\mathcal{G}: E[Y∣G]=∑kE[Y1Bk]P(Bk)1Bk\E[Y \given \mathcal{G}] = \sum_k \frac{\E[Y\ind_{B_k}]}{\Pr(B_k)}\ind_{B_k}, summing pieces with P(Bk)>0\Pr(B_k) > 0 (any value works on null pieces). This is the elementary formula and the figure.

Geometry: an orthogonal projection in L2L^2

For Y∈L2Y \in L^2 there is a second construction, independent of Radon-Nikodym, that also explains why conditional expectation is the best prediction. Lesson 5 showed that L2L^2, with ⟨U,V⟩=E[UV]\inner{U}{V} = \E[UV], is a Hilbert space (LpL^p spaces are complete). Within it, G\mathcal{G}-measurable variables form

L2(G)={W∈L2:W has a G-measurable version},L^2(\mathcal{G}) = \{W \in L^2 : W \text{ has a } \mathcal{G}\text{-measurable version}\},

a vector subspace. It is closed: L2(Ω,G,P∣G)L^2(\Omega, \mathcal{G}, \Pr|_{\mathcal{G}}) is complete by the same Riesz-Fischer theorem applied to that probability space, and its norm is the L2L^2 norm; a complete subspace of a metric space is closed.

Proof

The projection exists. Let d=inf⁡W∈L2(G)∥Y−W∥2d = \inf_{W \in L^2(\mathcal{G})} \norm{Y - W}_2 and WnW_n be a minimizing sequence. By the parallelogram identity, ∥Wn−Wm∥2=2∥Y−Wn∥2+2∥Y−Wm∥2−4∥Y−Wn+Wm2∥2\norm{W_n - W_m}^2 = 2\norm{Y - W_n}^2 + 2\norm{Y - W_m}^2 - 4\norm{Y - \tfrac{W_n + W_m}{2}}^2, and since Wn+Wm2∈L2(G)\tfrac{W_n + W_m}{2} \in L^2(\mathcal{G}), the final term is at least 4d24d^2. Thus ∥Wn−Wm∥2≤2∥Y−Wn∥2+2∥Y−Wm∥2−4d2\norm{W_n - W_m}^2 \le 2\norm{Y - W_n}^2 + 2\norm{Y - W_m}^2 - 4d^2, and this bound tends to 2d2+2d2−4d2=02d^2 + 2d^2 - 4d^2 = 0: the sequence is Cauchy, converges in L2L^2 to ΠY\Pi Y, and ΠY∈L2(G)\Pi Y \in L^2(\mathcal{G}) because the subspace is closed. By norm continuity, ∥Y−ΠY∥=d\norm{Y - \Pi Y} = d. For any W∈L2(G)W \in L^2(\mathcal{G}), function t↦∥Y−ΠY−tW∥2=d2−2t⟨Y−ΠY,W⟩+t2∥W∥2t \mapsto \norm{Y - \Pi Y - tW}^2 = d^2 - 2t\inner{Y - \Pi Y}{W} + t^2\norm{W}^2 has its minimum at t=0t = 0, so ⟨Y−ΠY,W⟩=0\inner{Y - \Pi Y}{W} = 0: this is the orthogonal projection, as in finite-dimensional orthogonal projection.

The projection is conditional expectation. For A∈GA \in \mathcal{G}, W=1A∈L2(G)W = \ind_A \in L^2(\mathcal{G}) and orthogonality says E[(Y−ΠY)1A]=0\E[(Y - \Pi Y)\ind_A] = 0. ΠY\Pi Y is G\mathcal{G}-measurable and integrable (L2⊂L1L^2 \subset L^1 on a probability space), so it meets all three conditions and uniqueness gives ΠY=Z\Pi Y = Z. This proves both Z∈L2(G)Z \in L^2(\mathcal{G}) and point 1. Points 2 and 3 follow from Pythagoras: for W∈L2(G)W \in L^2(\mathcal{G}), Z−W∈L2(G)Z - W \in L^2(\mathcal{G}) is orthogonal to Y−ZY - Z, so E[(Y−W)2]=E[(Y−Z)2]+E[(Z−W)2]\E[(Y - W)^2] = \E[(Y - Z)^2] + \E[(Z - W)^2]; W=0W = 0 gives point 3.

∎

This gives a second existence proof, used by Williams in Probability with Martingales: construct E[Y∣G]\E[Y \given \mathcal{G}] in L2L^2 as a projection, and for Y∈L1Y \in L^1, Y≥0Y \ge 0, approximate by Yn=min⁡(Y,n)∈L2Y_n = \min(Y, n) \in L^2; projections E[Yn∣G]\E[Y_n \given \mathcal{G}] increase (by monotonicity shown shortly) and their limit satisfies the definition by monotone convergence.

The theorem also quantifies the gain from information. If H⊂G\mathcal{H} \subset \mathcal{G}, then L2(H)⊂L2(G)L^2(\mathcal{H}) \subset L^2(\mathcal{G}) and the minimum over a larger set is lower: E[(Y−E[Y∣G])2]≤E[(Y−E[Y∣H])2]\E[(Y - \E[Y \given \mathcal{G}])^2] \le \E[(Y - \E[Y \given \mathcal{H}])^2]; more information never worsens prediction on average. The first figure showed this decrease as the partition was refined.

InteractiveConditional expectation is a projection
  • YY
  • E[Y∣X]\E[Y \given X]
  • residual Y−ZY - Z
  • G\mathcal{G}-measurable variables
Information G\mathcal{G}
Probabilities
0.50
0.20
p3=0.30p_3 = 0.30
Variable YY
1.60
-0.60
0.90
ZZ(0.97, 0.97, 0.90)
E[(Y−Z) 1B]\E[(Y - Z)\,\ind_B] per block0.0000, 0.0000
E[Y2]\E[Y^2]1.595
E[Z2]+E[(Y−Z)2]\E[Z^2] + \E[(Y - Z)^2]0.904 + 0.691
E[Z]\E[Z] and E[Y]\E[Y]0.950 and 0.950
With Ω={ω1,ω2,ω3}\Omega = \{\omega_1, \omega_2, \omega_3\}, a random variable is a vector (Y(ω1),Y(ω2),Y(ω3))(Y(\omega_1), Y(\omega_2), Y(\omega_3)) in R3\R^3 and the L2L^2 inner product is ⟨U,V⟩=∑ipiUiVi\inner{U}{V} = \sum_i p_i U_i V_i. Each axis is scaled by 3pi\sqrt{3p_i}, transforming that product to the screen's Euclidean product up to constant factor 33, preserving angles and perpendiculars. The σ(X)\sigma(X)-measurable variables, constant in each XX block, form the yellow plane, and E[Y∣X]\E[Y \given X] (magenta) is the foot of the perpendicular from YY. Move YY and probabilities: the residual remains perpendicular and E[(Y−Z)1B]\E[(Y - Z)\ind_B] readings remain zero. Disable L2L^2 geometry with nonuniform pp: the Euclidean perpendicular lands at the unweighted average, not conditional expectation. Also try the trivial σ-algebra (the line of constants) and tower.

The figure shows an often-forgotten detail: L2L^2 geometry depends on P\Pr. In original coordinates, “perpendicular” means with weighted product ∑ipiUiVi\sum_i p_i U_i V_i, not the Euclidean one. For block {ω1,ω2}\{\omega_1, \omega_2\} and p=(0.5,0.2,0.3)p = (0.5, 0.2, 0.3), conditional expectation on the block is (0.5 Y1+0.2 Y2)/0.7(0.5\,Y_1 + 0.2\,Y_2)/0.7, the weighted average; simple average (Y1+Y2)/2(Y_1 + Y_2)/2 would be the projection for uniform probability.

Properties: the algebra of conditional expectation

Almost all derivations with conditional expectations (Bellman, martingales, ELBO, policy gradients, Kalman) use only the following list.

Property 5 is the tower property: of two nested information states, the coarser one prevails. Projecting onto a subspace and then a smaller one inside it equals directly projecting onto the smaller; projecting onto the smaller and then the larger changes nothing because you were already inside. This appeared in the first figure’s nested partition and fails when H⊄G\mathcal{H} \not\subset \mathcal{G}.

Proof

(1) The right side is G\mathcal{G}-measurable and integrable, and condition 3 is linear. (2) Let Z=E[Y∣G]Z = \E[Y \given \mathcal{G}] and A={Z<0}∈GA = \{Z < 0\} \in \mathcal{G}. Then 0≥E[Z1A]=E[Y1A]≥00 \ge \E[Z\ind_A] = \E[Y\ind_A] \ge 0, so Z1A=0Z\ind_A = 0 almost surely and P(A)=0\Pr(A) = 0. The absolute-value bound follows from applying (1) and (2) to ∣Y∣−Y≥0\abs{Y} - Y \ge 0 and ∣Y∣+Y≥0\abs{Y} + Y \ge 0. (3) This is condition 3 with A=ΩA = \Omega. (4) YY itself satisfies the definition.

(5) E[Y∣H]\E[Y \given \mathcal{H}] is H\mathcal{H}-measurable and hence G\mathcal{G}-measurable, so the second equality is (4). For the first, E[Y∣H]\E[Y \given \mathcal{H}] is H\mathcal{H}-measurable and integrable, and for A∈HA \in \mathcal{H}, since also A∈GA \in \mathcal{G},

E[E[Y∣H] 1A]=E[Y 1A]=E[E[Y∣G] 1A],\E\big[\E[Y \given \mathcal{H}]\,\ind_A\big] = \E[Y\,\ind_A] = \E\big[\E[Y \given \mathcal{G}]\,\ind_A\big],

which is the definition of E[E[Y∣G]∣H]\E\big[\E[Y \given \mathcal{G}] \given \mathcal{H}\big]. The only place H⊂G\mathcal{H} \subset \mathcal{G} is used is applying condition 3 for E[Y∣G]\E[Y \given \mathcal{G}] to A∈HA \in \mathcal{H}.

(6) For X=1BX = \ind_B with B∈GB \in \mathcal{G} and any A∈GA \in \mathcal{G}: E[1BE[Y∣G]1A]=E[E[Y∣G]1A∩B]=E[Y1A∩B]=E[1BY1A]\E[\ind_B\E[Y \given \mathcal{G}]\ind_A] = \E[\E[Y \given \mathcal{G}]\ind_{A \cap B}] = \E[Y\ind_{A \cap B}] = \E[\ind_B Y\ind_A], because A∩B∈GA \cap B \in \mathcal{G}. By linearity this holds for simple XX. If X,Y≥0X, Y \ge 0, take simple G\mathcal{G}-measurable XnX_n with Xn↑XX_n \uparrow X; since E[Y∣G]≥0\E[Y \given \mathcal{G}] \ge 0, monotone convergence on both sides of E[XnE[Y∣G]1A]=E[XnY1A]\E[X_n\E[Y \given \mathcal{G}]\ind_A] = \E[X_n Y\ind_A] gives the result. The general case follows by splitting XX and YY into positive and negative parts.

(7) Constant E[Y]\E[Y] is G\mathcal{G}-measurable and, for A∈GA \in \mathcal{G}, independence of YY and 1A\ind_A gives E[Y1A]=E[Y]P(A)=E[E[Y] 1A]\E[Y\ind_A] = \E[Y]\Pr(A) = \E[\E[Y]\,\ind_A].

(8) A convex function on R\R is the supremum of a countable family of affine functions ℓn(x)=anx+bn\ell_n(x) = a_n x + b_n (supporting lines at rational points). For each nn, by (1), (2) and (4), E[φ(Y)∣G]≥E[ℓn(Y)∣G]=ℓn(E[Y∣G])\E[\varphi(Y) \given \mathcal{G}] \ge \E[\ell_n(Y) \given \mathcal{G}] = \ell_n(\E[Y \given \mathcal{G}]) outside a null set NnN_n. Outside ⋃nNn\bigcup_n N_n, still null, all hold simultaneously, and taking the supremum over nn yields the inequality. With φ(x)=∣x∣p\varphi(x) = \abs{x}^p and taking expectations, E∣E[Y∣G]∣p≤E[E[∣Y∣p∣G]]=E∣Y∣p\E\abs{\E[Y \given \mathcal{G}]}^p \le \E\big[\E[\abs{Y}^p \given \mathcal{G}]\big] = \E\abs{Y}^p.

(9) Let Vn=sup⁡k≥n∣Yk−Y∣V_n = \sup_{k \ge n}\abs{Y_k - Y}, decreasing to 00 and bounded by 2V2V. By (2), ∣E[Yn∣G]−E[Y∣G]∣≤E[Vn∣G]\abs{\E[Y_n \given \mathcal{G}] - \E[Y \given \mathcal{G}]} \le \E[V_n \given \mathcal{G}], which decreases almost surely to a limit L≥0L \ge 0. By unconditional dominated convergence, E[L]≤E[E[Vn∣G]]=E[Vn]→0\E[L] \le \E[\E[V_n \given \mathcal{G}]] = \E[V_n] \to 0, hence L=0L = 0.

∎

Note the detail in Jensen’s proof: the line family must be countable because each conditional-expectation inequality holds only outside a different null set. An uncountable family would not allow combining those null sets. This is the same obstacle as in the earlier warning and will recur.

Property 7 has a frequently used version: if ZZ is independent of pair (X,Y)(X, Y), then E[Y∣X,Z]=E[Y∣X]\E[Y \given X, Z] = \E[Y \given X]; information independent of everything relevant does not change prediction. Property 6 combined with 3 gives the most-used identity: for any bounded h(X)h(X), E[h(X)(Y−E[Y∣X])]=0\E[h(X)(Y - \E[Y \given X])] = 0. The best predictor’s residual is orthogonal to every function of XX. This is property 1 of the projection theorem, now for Y∈L1Y \in L^1.

Laws of total expectation and total variance

Property 3 is the law of total expectation: E[Y]=E[E[Y∣X]]\E[Y] = \E[\E[Y \given X]]. It calculates a difficult expectation by conditioning on something that simplifies it. Variance has an analogous law with one additional term. Define the conditional variance of Y∈L2Y \in L^2 as

Var⁡(Y∣G)=E[(Y−E[Y∣G])2∣G]=E[Y2∣G]−E[Y∣G]2,\Var(Y \given \mathcal{G}) = \E\big[(Y - \E[Y \given \mathcal{G}])^2 \given \mathcal{G}\big] = \E[Y^2 \given \mathcal{G}] - \E[Y \given \mathcal{G}]^2,

where the second form follows by expanding the square and taking out what is known. Like conditional expectation it is a random variable: Var⁡(Y∣X)=v(X)\Var(Y \given X) = v(X) with v(x)=Var⁡(Y∣X=x)v(x) = \Var(Y \given X = x).

Proof

With Z=E[Y∣G]Z = \E[Y \given \mathcal{G}], write Y−E[Y]=(Y−Z)+(Z−E[Y])Y - \E[Y] = (Y - Z) + (Z - \E[Y]). The second summand lies in L2(G)L^2(\mathcal{G}) and the first is orthogonal to all of L2(G)L^2(\mathcal{G}), so Pythagoras gives Var⁡(Y)=E[(Y−Z)2]+E[(Z−E[Y])2]\Var(Y) = \E[(Y - Z)^2] + \E[(Z - \E[Y])^2]. The first term is E[E[(Y−Z)2∣G]]=E[Var⁡(Y∣G)]\E\big[\E[(Y - Z)^2 \given \mathcal{G}]\big] = \E[\Var(Y \given \mathcal{G})] by total expectation, and the second is Var⁡(Z)\Var(Z) because E[Z]=E[Y]\E[Z] = \E[Y].

∎

The geometric interpretation is the projection theorem: centered vector Y−E[Y]Y - \E[Y] decomposes into a part inside the subspace of what G\mathcal{G} knows and a perpendicular part. The first is variability between groups (how prediction changes with information), the second variability within each group (what information does not resolve). This is statistical ANOVA, and the same idea recurs in bias-variance decomposition.

InteractiveExplained and unexplained variance
−6−3036X = 1 (p = 0.25)X = 2 (p = 0.25)X = 3 (p = 0.25)X = 4 (p = 0.25)
  • group mean E[Y∣X=k]\E[Y \given X = k]
  • overall mean E[Y]\E[Y]
  • explained component
  • unexplained component
Var⁡(Y)=E[Var⁡(Y∣X)]+Var⁡(E[Y∣X])\Var(Y) = \E[\Var(Y \given X)] + \Var(\E[Y \given X])
unexplained17 %explained83 %
0.60
1.50
Var⁡(Y)\Var(Y)2.160
E[Var⁡(Y∣X)]\E[\Var(Y \given X)], unexplained0.360
Var⁡(E[Y∣X])\Var(\E[Y \given X]), explained1.800
η2=Var⁡(E[Y∣X])/Var⁡(Y)\eta^2 = \Var(\E[Y \given X]) / \Var(Y)0.833
Four groups X=1,…,4X = 1, \dots, 4 with probabilities pkp_k; in group kk, YY has mean s cks\,c_k and standard deviation σ\sigma. Magenta segments are E[Y∣X=k]\E[Y \given X = k] and the dashed line E[Y]\E[Y]. The stacked bar divides Var⁡(Y)\Var(Y) into what XX does not explain (aqua, mean within-group variance) and what it explains (orange, variance of group means). Set ss to zero, then σ\sigma to zero. Select a point: its deviation from E[Y]\E[Y] splits into a part in the subspace of functions of XX and a perpendicular part. With different noise per group, Var⁡(Y∣X)\Var(Y \given X) ceases to be constant.

Ratio η2=Var⁡(E[Y∣X])/Var⁡(Y)\eta^2 = \Var(\E[Y \given X])/\Var(Y) is the correlation ratio, the fraction of variance XX explains with the best possible function. It is 00 if E[Y∣X]\E[Y \given X] is constant and 11 if YY is a function of XX. At the end we see η2≥ρ2\eta^2 \ge \rho^2, squared correlation, with equality if and only if regression is linear.

The same law organizes two later ideas. Aleatoric and epistemic uncertainty: in a Bayesian model with parameter θ\theta, Var⁡(Y)=E[Var⁡(Y∣θ)]+Var⁡(E[Y∣θ])\Var(Y) = \E[\Var(Y \given \theta)] + \Var(\E[Y \given \theta]); the first term is noise remaining even if θ\theta were known, the second uncertainty about θ\theta, measured by disagreements between ensemble members. Rao-Blackwell: if TT estimates something and you condition on statistic SS, T∗=E[T∣S]T^* = \E[T \given S] has the same mean and variance Var⁡(T)−E[Var⁡(T∣S)]≤Var⁡(T)\Var(T) - \E[\Var(T \given S)] \le \Var(T). Sufficiency of SS is needed only so T∗T^* does not depend on the unknown parameter (the Rao-Blackwell theorem).

Conditioning on probability-zero events

Regular conditional distributions

For each event BB, P(B∣G)=E[1B∣G]\Pr(B \given \mathcal{G}) = \E[\ind_B \given \mathcal{G}] is an almost-surely defined random variable. One might naturally think that, for each fixed ω\omega, B↦P(B∣G)(ω)B \mapsto \Pr(B \given \mathcal{G})(\omega) is a probability measure. But σ-additivity P(⋃nBn∣G)=∑nP(Bn∣G)\Pr(\bigcup_n B_n \given \mathcal{G}) = \sum_n \Pr(B_n \given \mathcal{G}) holds outside a null set different for each sequence (Bn)(B_n), and there are uncountably many sequences. In general there is no way to choose versions that are simultaneously measures. When there is, the object has a name.

The proof idea for d=1d = 1 is Jensen’s: reduce the uncountable to the countable. For each rational qq, take a version of F(q,x)=P(Y≤q∣X=x)F(q, x) = \Pr(Y \le q \given X = x). Monotonicity of F(⋅,x)F(\cdot, x) on rationals, limits 00 and 11 and right-continuity on rationals are countably many conditions, each holding outside a null set, so all hold outside one null set NN. Outside NN, F(⋅,x)F(\cdot, x) extends to a distribution function on R\R and defines a measure κ(x,⋅)\kappa(x, \cdot); on NN use any fixed law. The π-λ theorem extends condition 3 from half-lines (−∞,q](-\infty, q] to all Borel sets. Details are in Durrett, section 4.1.3.

When densities exist, κ(x, ⁣dy)=p(y∣x) ⁣dy\kappa(x, \dd y) = p(y \given x)\dd y with the previous lesson’s conditional density, justifying the continuous-case formula. But uniqueness is only PX\Pr_X-almost sure. If P(X=x0)=0\Pr(X = x_0) = 0, you can replace κ(x0,⋅)\kappa(x_0, \cdot) with any other law and still have a valid regular conditional distribution. P\Pr does not determine the value at an isolated probability-zero point. Something else does, as the next paradox shows.

The Borel-Kolmogorov paradox

Choose a uniform point on the unit sphere and describe it by latitude ϕ∈[−π/2,π/2]\phi \in [-\pi/2, \pi/2] and longitude λ∈(−π,π]\lambda \in (-\pi, \pi]. The area element is cos⁡ϕ ⁣dϕ ⁣dλ\cos\phi\dd\phi\dd\lambda, so joint density is cos⁡ϕ/(4π)\cos\phi/(4\pi): λ\lambda is uniform, ϕ\phi has density cos⁡ϕ/2\cos\phi/2, and they are independent. Now condition on the point lying on a great circle.

  • The equator, {ϕ=0}\{\phi = 0\}. By independence, the conditional law of λ\lambda given ϕ\phi is uniform for every ϕ\phi. In particular the point is distributed uniformly over the equator.
  • A complete meridian, {λ∈{0,π}}\{\lambda \in \{0, \pi\}\}. The law of ϕ\phi given λ\lambda is cos⁡ϕ/2\cos\phi/2 for every λ\lambda. On the meridian, the point concentrates near the equator and scarcely appears near the poles.

But equator and meridian are the same kind of object: two great circles, and a sphere rotation preserving the uniform law maps one to the other. What is “the” law of a uniform point conditioned to lie on a great circle? The figure estimates it both ways.

InteractiveThe Borel-Kolmogorov paradox
  • great circle CC
  • points in the band
  • equator (z=0z = 0)
Conditional law of position ψ\psi along CC (density per radian)
−180°−90°0°90°180°|cos ψ| / 41 / (2π)
ψ=0°\psi = 0° and ±180°\pm 180°: equator; ±90°\pm 90°: poles.
Neighborhood of CC
8.0°
Neighborhood probability0.1380
Theoretical0.1395
Points inside20696 of 150000
P(∣latitude∣<30°∣neighborhood)\Pr(\abs{\text{latitude}} < 30° \given \text{neighborhood})0.336
Limit: band / wedge0.333 / 0.500
The band has the same width throughout CC: each arc of CC receives mass proportional to its length, and the conditional law is uniform, 1/(2π)1/(2\pi).
Uniform points on the sphere and a great circle CC (magenta), a complete meridian relative to the vertical axis. The event 'the point is in CC' has probability zero, so approximate it by a neighborhood of width ε\varepsilon and condition on that. The band has constant width (a latitude band relative to a pole on the equator); the wedge lies between two meridians, wide at the equator and narrow at the poles. Below is a histogram of position ψ\psi along CC. Lower ε\varepsilon as much as you like: the band always gives the uniform law and the wedge density ∣cos⁡ψ∣/4\abs{\cos\psi}/4. Compare probability of landing within 30°30° of the equator: 1/31/3 versus 1/21/2.

Kolmogorov’s resolution, presented in his 1933 Foundations, is that conditioning on an isolated probability-zero event is undefined. What is defined is conditioning on a σ-algebra or random variable, and the two answers condition on different variables:

  • The uniform law is Pλ∣ϕ=0\Pr_{\lambda \given \phi = 0}, the regular conditional distribution of longitude given latitude, evaluated at ϕ=0\phi = 0. It corresponds to bands {∣ϕ∣<ε}\{\abs{\phi} < \eps\}, constant-width neighborhoods.
  • Law cos⁡ϕ/2\cos\phi/2 is Pϕ∣λ=0\Pr_{\phi \given \lambda = 0}, latitude given longitude, evaluated at λ=0\lambda = 0. It corresponds to wedges {∣λ∣<ε}\{\abs{\lambda} < \eps\}.

Both are correct for their respective variables. Since regular conditional distributions are determined only almost surely, their values at the single point ϕ=0\phi = 0 or λ=0\lambda = 0 are fixed by continuity of the family containing that point, namely the variable being observed. The circle as a set is insufficient.

This is not merely an exam curiosity. In probabilistic programming, “observing” an exact value of a continuous function of latent variables conditions on a null event, and the result depends on which function is observed: observing X−Y=0X - Y = 0 or X/Y=1X/Y = 1 describes the same line and gives different posteriors, as seen above. In diffusion, conditioning on xt=x\vb{x}_t = \vb{x} presents no such problem because the observed variable is fixed (xt\vb{x}_t itself) and has a continuous positive density, and the optimal denoiser is the mean of its regular conditional distribution. Chang and Pollard (1997) develop this view of conditional distributions as disintegrations of measure along a map.

Best predictor versus best linear predictor

The best linear (affine) predictor of YY from XX, both in L2L^2 with Var⁡(X)>0\Var(X) > 0, is the projection of YY onto the plane span⁡{1,X}\spn\{1, X\}:

L^[Y∣X]=E[Y]+Cov⁡(X,Y)Var⁡(X)(X−E[X]),E[(Y−L^[Y∣X])2]=Var⁡(Y) (1−ρ2).\hat{L}[Y \given X] = \E[Y] + \frac{\Cov(X, Y)}{\Var(X)}\big(X - \E[X]\big), \qquad \E\big[(Y - \hat{L}[Y \given X])^2\big] = \Var(Y)\,(1 - \rho^2).

The two orthogonality conditions, E[Y−L^]=0\E[Y - \hat{L}] = 0 and E[(Y−L^)X]=0\E[(Y - \hat{L})X] = 0, are the least-squares normal equations with one regressor. Since span⁡{1,X}⊂L2(σ(X))\spn\{1, X\} \subset L^2(\sigma(X)), the geometric tower says projecting YY onto the plane equals projecting E[Y∣X]\E[Y \given X] onto the plane, and Pythagoras gives

E[(Y−L^)2]⏟Var⁡(Y)(1−ρ2)=E[(Y−E[Y∣X])2]⏟Var⁡(Y)(1−η2)+E[(E[Y∣X]−L^)2].\underbrace{\E\big[(Y - \hat{L})^2\big]}_{\Var(Y)(1 - \rho^2)} = \underbrace{\E\big[(Y - \E[Y \given X])^2\big]}_{\Var(Y)(1 - \eta^2)} + \E\big[(\E[Y \given X] - \hat{L})^2\big].

Thus η2≥ρ2\eta^2 \ge \rho^2, with equality if and only if E[Y∣X]\E[Y \given X] is affine in XX. The best linear predictor is the best linear approximation of the regression function, and its excess error is exactly the distance between them.

  • When they differ. With X∼N(0,1)X \sim \Normal(0, 1) and Y=X2+0.5 εY = X^2 + 0.5\,\eps, Cov⁡(X,Y)=E[X3]=0\Cov(X, Y) = \E[X^3] = 0: ρ=0\rho = 0 and the best linear predictor is constant E[Y]=1\E[Y] = 1, with error Var⁡(Y)=2.25\Var(Y) = 2.25. Conditional expectation is X2X^2, with error 0.250.25: η2=2/2.25≈0.89\eta^2 = 2/2.25 \approx 0.89. Zero correlation does not mean XX cannot predict YY.
  • When they coincide: the Gaussian case. If (X,Y)(X, Y) is jointly normal, residual Y−L^[Y∣X]Y - \hat{L}[Y \given X] is uncorrelated with XX and jointly normal with it, hence independent. By property 7, E[Y−L^∣X]=E[Y−L^]=0\E[Y - \hat{L} \given X] = \E[Y - \hat{L}] = 0, so E[Y∣X]=L^[Y∣X]\E[Y \given X] = \hat{L}[Y \given X]: in the Gaussian world the best prediction is linear and conditional variance constant. This previews Gaussian conditioning, the basis of the Kalman filter and Gaussian processes.
  • The denoiser. If X0=±1X_0 = \pm 1 with probability 1/21/2 and Xt=X0+σεX_t = X_0 + \sigma\eps, Bayes’ formula gives E[X0∣Xt]=tanh⁡(Xt/σ2)\E[X_0 \given X_t] = \tanh(X_t/\sigma^2), a highly nonlinear function, while the best linear predictor is Xt/(1+σ2)X_t/(1 + \sigma^2). With σ=0.5\sigma = 0.5, linear error is σ2/(1+σ2)=0.2\sigma^2/(1 + \sigma^2) = 0.2 and optimal error about three times smaller. You can check tanh⁡(x/σ2)=x+σ2  ⁣d ⁣dxlog⁡pt(x)\tanh(x/\sigma^2) = x + \sigma^2\,\frac{\dd}{\dd x}\log p_t(x) with ptp_t the density of XtX_t: this is Tweedie’s formula in one dimension and why a trained denoiser gives the score function for free.

Implementation from scratch

Empirical conditional expectation given a partition is a group average, calculated in linear time with np.bincount. It illustrates the preceding ideas: convergence as the partition is refined, estimator bias and variance, residual orthogonality and total variance.

[ ]Conditional expectation by partitionsBrowser
import numpy as np

def cond_exp_bins(Y, X, edges):
    """E[Y | G] empírica, con G generada por los intervalos [e_k, e_{k+1}) de X."""
    k = len(edges) - 1
    idx = np.clip(np.searchsorted(edges, X, side="right") - 1, 0, k - 1)
    sumas = np.bincount(idx, weights=Y, minlength=k)
    cuentas = np.bincount(idx, minlength=k)
    medias = sumas / np.maximum(cuentas, 1)
    return medias[idx], idx, medias

rng = np.random.default_rng(0)
n = 200_000
m = lambda x: np.sin(2 * np.pi * x) + 0.5 * x        # la verdadera E[Y | X = x]
X = rng.uniform(0, 1, n)
Y = m(X) + 0.3 * rng.standard_normal(n)               # ruido de varianza 0.09
Xn = rng.uniform(0, 1, n)                             # datos nuevos para medir el error honesto
Yn = m(Xn) + 0.3 * rng.standard_normal(n)

print(" piezas   error en los datos   error en datos nuevos   E[(Z - m(X))^2]")
for k in [1, 4, 16, 64, 256, 1024, 8192]:
    edges = np.linspace(0, 1, k + 1)
    Z, _, medias = cond_exp_bins(Y, X, edges)
    jn = np.clip(np.searchsorted(edges, Xn, side="right") - 1, 0, k - 1)
    print(f"{k:7d}   {np.mean((Y - Z)**2):18.5f}   {np.mean((Yn - medias[jn])**2):21.5f}   {np.mean((Z - m(X))**2):15.6f}")

# ortogonalidad del residuo con 16 piezas
Z, idx, _ = cond_exp_bins(Y, X, np.linspace(0, 1, 17))
R = Y - Z
print("\nresiduo frente a funciones G-medibles (funciones del índice de pieza):")
for nombre, W in [("1[pieza 3]", (idx == 3) * 1.0), ("pieza**2", idx**2.0), ("cos(pieza)", np.cos(idx))]:
    print(f"  E[R * {nombre:12s}] = {np.mean(R * W): .1e}")
print("residuo frente a funciones de X que no son G-medibles:")
for nombre, W in [("X", X), ("sin(2 pi X)", np.sin(2 * np.pi * X))]:
    print(f"  E[R * {nombre:12s}] = {np.mean(R * W): .1e}")

print(f"\nVar(Y) = {Y.var():.6f}")
print(f"E[Var(Y|G)] + Var(E[Y|G]) = {np.mean(R**2):.6f} + {Z.var():.6f} = {np.mean(R**2) + Z.var():.6f}")

The table tells three stories. Error on the data themselves always falls with refinement, even below irreducible noise 0.090.09: with 81928192 pieces of about 2424 points each, averages start chasing noise. Error on new data instead is U-shaped, with minimum near 256256 pieces, as is distance to true mm: few pieces give bias (the function is not constant within each) and many give variance (each average uses little data). This is the dilemma of any nonparametric E[Y∣X]\E[Y \given X] estimator. The last two parts check what theory says is exact, orthogonality and total variance, up to rounding, because under the empirical law the partition truly generates a finite σ-algebra.

[ ]The tower with nested and non-nested partitionsBrowser
gruesa = np.linspace(0, 1, 5)        # 4 piezas: sus cortes están entre los de la fina
fina = np.linspace(0, 1, 17)         # 16 piezas
otra = np.linspace(0, 1, 6)          # 5 piezas: cortes en 0.2, 0.4, ... que no son de la fina

ZG, _, _ = cond_exp_bins(Y, X, fina)
for nombre, H in [("H anidada en G (4 piezas)", gruesa), ("H no anidada (5 piezas)", otra)]:
    torre, _, _ = cond_exp_bins(ZG, X, H)       # E[E[Y|G] | H]
    directa, _, _ = cond_exp_bins(Y, X, H)      # E[Y | H]
    print(f"{nombre:26s}  max |E[E[Y|G]|H] - E[Y|H]| = {np.max(np.abs(torre - directa)):.1e}")

With the nested partition the difference is of order 10−1310^{-13}, pure rounding; without nesting it is order 10−210^{-2}, a real error. The tower is not an approximation: it is an exact identity requiring H⊂G\mathcal{H} \subset \mathcal{G}.

[ ]Best predictor versus best linear predictorBrowser
def mejor_lineal(Y, X):
    b = np.mean((X - X.mean()) * (Y - Y.mean())) / X.var()
    return Y.mean() + b * (X - X.mean())

def cond_exp_cuantiles(Y, X, k=200):
    """Esperanza condicional empírica con k piezas de igual número de puntos."""
    return cond_exp_bins(Y, X, np.quantile(X, np.linspace(0, 1, k + 1)))[0]

X1 = rng.standard_normal(n); Y1 = X1**2 + 0.5 * rng.standard_normal(n)
X2 = rng.standard_normal(n); Y2 = 0.8 * X2 + 0.6 * rng.standard_normal(n)
s = 0.5
X0 = rng.choice([-1.0, 1.0], n); Xt = X0 + s * rng.standard_normal(n)

print(f"{'caso':24s} {'MSE lineal':>10s} {'MSE E[Y|X]':>11s} {'rho^2':>7s} {'eta^2':>7s}")
for nombre, Yc, Xc in [("Y = X^2 + ruido", Y1, X1), ("gaussiana, rho = 0.8", Y2, X2), ("denoiser E[X0 | Xt]", X0, Xt)]:
    L, C = mejor_lineal(Yc, Xc), cond_exp_cuantiles(Yc, Xc)
    rho2 = np.corrcoef(Xc, Yc)[0, 1] ** 2
    print(f"{nombre:24s} {np.mean((Yc - L)**2):10.4f} {np.mean((Yc - C)**2):11.4f} {rho2:7.4f} {C.var() / Yc.var():7.4f}")

print(f"\ndenoiser exacto tanh(x/s^2): MSE = {np.mean((X0 - np.tanh(Xt / s**2))**2):.4f}   lineal teórico s^2/(1+s^2) = {s**2 / (1 + s**2):.4f}")

# residuo ortogonal a las funciones de X pero no independiente de X
Xh = rng.standard_normal(n); Rh = np.abs(Xh) * rng.standard_normal(n)   # Y = X + R, E[Y|X] = X
print(f"heterocedástico: E[R X] = {np.mean(Rh * Xh):.3f}, E[R X^2] = {np.mean(Rh * Xh**2):.3f}, corr(R^2, X^2) = {np.corrcoef(Rh**2, Xh**2)[0, 1]:.3f}")

In the Gaussian case both error columns agree (apart from estimation noise), and ρ2≈η2≈0.64\rho^2 \approx \eta^2 \approx 0.64. In the other two, conditional expectation wins by a wide margin. Quantile estimation of E[Y∣X]\E[Y \given X] in the first case gives error slightly above theoretical 0.250.25 and η2\eta^2 slightly below 0.890.89: tail pieces are wide and X2X^2 varies greatly within them (bias). The last line expresses the earlier warning numerically: the residual is orthogonal to XX and X2X^2, but R2R^2 and X2X^2 have correlation 0.50.5.

[ ]Borel and Kolmogorov by Monte CarloBrowser
N = 400_000
z = rng.uniform(-1, 1, N); lon = rng.uniform(-np.pi, np.pi, N)   # uniforme en la esfera (Arquímedes)
r = np.sqrt(1 - z**2); x, y = r * np.cos(lon), r * np.sin(lon)

print("círculo C: el meridiano del plano y = 0.  P(|latitud| < 30° | entorno de C)")
for eps in [0.2, 0.05, 0.01]:
    banda = np.abs(y) < np.sin(eps)                          # anchura constante alrededor de C
    cuna = np.arctan2(np.abs(y), np.abs(x)) < eps            # entre meridianos: |longitud| < eps o |longitud - pi| < eps
    lat_banda = np.arctan2(z[banda], np.abs(x[banda]))       # proyección ortogonal sobre el plano de C
    lat_cuna = np.arcsin(z[cuna])                            # giro alrededor del eje z hasta C
    print(f"  eps = {eps:4.2f}:  banda {np.mean(np.abs(lat_banda) < np.pi / 6):.3f} ({banda.sum():6d} puntos)"
          f"   cuña {np.mean(np.abs(lat_cuna) < np.pi / 6):.3f} ({cuna.sum():6d} puntos)")
print(f"  límites: uniforme 1/3 = {1/3:.3f},  cos/2: sin(30°) = {np.sin(np.pi / 6):.3f}")

A, B = rng.standard_normal(N), rng.standard_normal(N)
for d in [0.1, 0.02]:
    dif, coc = np.abs(A - B) < d, np.abs(A / B - 1) < d
    print(f"d = {d}:  E[X^2 | |X - Y| < d] = {np.mean(A[dif]**2):.3f}   E[X^2 | |X/Y - 1| < d] = {np.mean(A[coc]**2):.3f}")

As neighborhoods narrow, estimates do not approach one another: each converges to its own limit, 1/31/3 and 1/21/2 on the sphere, 1/21/2 and 11 with two normals. The figure’s histogram is this same simulation.

The library version

There is no conditional_expectation function in a library for the general object, because it depends on the σ-algebra. There are estimators of E[Y∣X]\E[Y \given X], and all are, in one way or another, averages over information:

ToolWhich σ-algebra it usesWhen
df.groupby(x)[y].transform("mean")that of a discrete variablecategorical XX: exact conditional expectation of the empirical law
pd.cut or pd.qcut then groupbyfixed interval partitionquick exploration, as in the earlier cells
sklearn.tree.DecisionTreeRegressorlearned partition (leaves)interpretable nonlinear regression; average per leaf
KNeighborsRegressor, kernelsneighborhoods of each pointlocal smoothing; bias and variance depend on neighborhood size
a network with MSE lossnone explicithigh dimension; approximates E[Y∣X]\E[Y \given X] within its function class
[ ]With pandas and scikit-learnBrowser
import pandas as pd
from sklearn.tree import DecisionTreeRegressor

rng = np.random.default_rng(0)
n = 20_000
df = pd.DataFrame({"dado": rng.integers(1, 7, n)})
df["y"] = df["dado"] + rng.standard_normal(n)

df["e_y_x"] = df.groupby("dado")["y"].transform("mean")      # E[Y | X] fila a fila
var_dentro = df.groupby("dado")["y"].var(ddof=0)              # Var(Y | X = x)
p = df["dado"].value_counts(normalize=True).sort_index()
print(df.groupby("dado")["y"].agg(["mean", "var", "size"]).round(3))
print(f"\nVar(Y) = {df['y'].var(ddof=0):.4f} = E[Var(Y|X)] + Var(E[Y|X]) = "
      f"{(p * var_dentro).sum():.4f} + {df['e_y_x'].var(ddof=0):.4f}")

# un árbol de regresión es una esperanza condicional respecto de la partición de sus hojas
X = rng.uniform(0, 1, n)
Y = np.sin(2 * np.pi * X) + 0.5 * X + 0.3 * rng.standard_normal(n)
arbol = DecisionTreeRegressor(max_leaf_nodes=16, random_state=0).fit(X[:, None], Y)
Z, hoja = arbol.predict(X[:, None]), arbol.apply(X[:, None])
medias = pd.Series(Y).groupby(hoja).transform("mean").to_numpy()
R = Y - Z
print(f"\nhojas: {len(np.unique(hoja))}   max |predicción - promedio de su hoja| = {np.max(np.abs(Z - medias)):.1e}")
print(f"max sobre hojas |E[R 1_hoja]| = {max(abs(np.mean(R * (hoja == h))) for h in np.unique(hoja)):.1e}")
print(f"E[R X] = {np.mean(R * X):.1e}   E[R sin(2 pi X)] = {np.mean(R * np.sin(2 * np.pi * X)):.1e}")

The groupby reproduces total variance under the empirical law, and the numerical exercise below asks for the population value. The tree confirms the table: its predictions are exactly means of YY in each leaf, and the residual is orthogonal to leaf indicators as in the first figure, but not to a function of XX varying within each leaf, such as sin⁡(2πX)\sin(2\pi X). With XX itself the product is almost zero (order 10−610^{-6} versus 10−310^{-3} with sine) because leaf contributions of opposite signs cancel; with sin⁡(2πX)\sin(2\pi X), varying within each leaf like regression itself, they add. A tree is conditional expectation given a finite σ-algebra chosen by the algorithm to reduce error; a random forest averages many such trees.

Common mistakes

Exercises

NumericTotal variance of a noisy die
Let XX be uniform on {1,…,6}\{1, \dots, 6\} and Y=X+εY = X + \varepsilon with ε∼N(0,1)\varepsilon \sim \Normal(0, 1) independent of XX. Calculate Var⁡(Y)\Var(Y) using total variance.
NumericA sum with a random number of terms
A server receives N∼Poisson⁡(4)N \sim \operatorname{Poisson}(4) requests per minute and each takes ξi∼Exp⁡\xi_i \sim \operatorname{Exp} with mean 22 seconds, iid and independent of NN. Calculate Var⁡(S)\Var(S) for total time S=ξ1+⋯+ξNS = \xi_1 + \cdots + \xi_N.
QuizFour identities and one error
Let X,Y,ZX, Y, Z be variables with Y∈L1Y \in L^1 (and XY∈L1XY \in L^1 where needed). Which statement is false in general?
QuizAn orthogonal but dependent residual
Let X∼N(0,1)X \sim \Normal(0, 1), independent ε∼N(0,1)\varepsilon \sim \Normal(0, 1) and Y=X+∣X∣εY = X + \abs{X}\varepsilon. Which statements are true?

More than one answer may be correct.

NumericThe wedge on the meridian
A uniform point on the sphere is conditioned on meridian {λ=0}\{\lambda = 0\} as the limit of wedges {∣λ∣<ε}\{\abs{\lambda} < \varepsilon\}, that is, using the regular conditional distribution of latitude given longitude. What is the probability its latitude satisfies ∣ϕ∣<30°\abs{\phi} < 30°?
NumericCondition on a line via a ratio
Let X,YX, Y be independent N(0,1)\Normal(0, 1) and R=X/YR = X/Y. Calculate E[X2∣R=1]\E[X^2 \given R = 1] using the regular conditional distribution of XX given RR.
ProofConditional expectation minimizes squared error
Prove: Let Y∈L2Y \in L^2 and Z=E[Y∣G]Z = \E[Y \given \mathcal{G}]. Then Z∈L2Z \in L^2 and for every G\mathcal{G}-measurable W∈L2W \in L^2, E[(Y−W)2]≥E[(Y−Z)2]\E[(Y - W)^2] \ge \E[(Y - Z)^2], with equality if and only if W=ZW = Z almost surely.
0
Use only the definition and properties of conditional expectation (not the projection theorem).

Step 1 of 4. First, why is Z∈L2Z \in L^2?

ProofFrom the tower to total variance
Prove: If H⊂G\mathcal{H} \subset \mathcal{G} and Y∈L1Y \in L^1, then E[E[Y∣G]∣H]=E[Y∣H]\E[\E[Y \given \mathcal{G}] \given \mathcal{H}] = \E[Y \given \mathcal{H}]. If Y∈L2Y \in L^2, Var⁡(Y)=E[Var⁡(Y∣G)]+Var⁡(E[Y∣G])\Var(Y) = \E[\Var(Y \given \mathcal{G})] + \Var(\E[Y \given \mathcal{G}]).
0
Let Z=E[Y∣G]Z = \E[Y \given \mathcal{G}]. For the first part it suffices to show E[Y∣H]\E[Y \given \mathcal{H}] satisfies the definition of conditional expectation of ZZ given H\mathcal{H}.

Step 1 of 4. What exactly must be checked?

CodeConditional expectation by partitions and the tower
Implement cond_expectation_partition(Y, X, bins), returning an array Z with the same shape as Y and empirical conditional expectation of Y given the partition of X into intervals [bins[k], bins[k+1]) (last one closed on the right): at each point, the mean of Y over points whose X lies in the same interval. Assume all X lie in [bins[0], bins[-1]] and bins is strictly increasing. Vectorize it (no Python loops over points). Tests check the definition (zero residual sum in each piece), total variance and the tower property for nested partitions.
import numpy as np

def cond_expectation_partition(Y, X, bins):
  """E[Y | G] empírica para la partición de X en [bins[k], bins[k+1])."""
  Y = np.asarray(Y, dtype=float)
  X = np.asarray(X, dtype=float)
  bins = np.asarray(bins, dtype=float)
  # tu código: índice de pieza de cada punto, suma y recuento por pieza, promedio
  return np.zeros_like(Y)
Shift+Enter to run

Summary

Key idea
Conditional expectation E[Y∣G]\E[Y \given \mathcal{G}] is the best prediction of YY with information G\mathcal{G}: the unique variable (up to null sets) using only what G\mathcal{G} knows and correct on average over each G\mathcal{G} event. It exists by Radon-Nikodym and, in L2L^2, is the orthogonal projection of YY onto G\mathcal{G}-measurable variables; hence it minimizes squared error, its residual is orthogonal to everything known, and variance splits into explained and unexplained parts.
  • E[Y∣X]\E[Y \given X] is a random variable g(X)g(X), with regression function g(x)=E[Y∣X=x]g(x) = \E[Y \given X = x] determined only PX\Pr_X-almost surely. In the discrete case it is a group average; with densities, ∫y p(y∣x) ⁣dy\int y\,p(y \given x)\dd y.
  • Definition: G\mathcal{G}-measurable, integrable and E[Z1A]=E[Y1A]\E[Z\ind_A] = \E[Y\ind_A] for A∈GA \in \mathcal{G}. It exists and is unique almost surely; it is the Radon-Nikodym derivative of Y ⁣dPY\dd\Pr restricted to G\mathcal{G}.
  • Properties: linearity, monotonicity, tower (H⊂G\mathcal{H} \subset \mathcal{G}: coarser information prevails), taking out what is known, independence, conditional Jensen and dominated convergence. These yield Bellman, Doob martingales and risk-neutral prices.
  • Var⁡(Y)=E[Var⁡(Y∣X)]+Var⁡(E[Y∣X])\Var(Y) = \E[\Var(Y \given X)] + \Var(\E[Y \given X]); η2≥ρ2\eta^2 \ge \rho^2, with equality if and only if regression is linear, as in the Gaussian case.
  • Conditioning on a probability-zero event makes sense only through a variable or σ-algebra: regular conditional distributions exist on Rd\R^d but are unique almost surely, and the Borel-Kolmogorov paradox shows two correct answers for the same circle.
  • Estimating E[Y∣X]\E[Y \given X] is regression: piecewise averages, trees, neighbors or networks, all with a tradeoff between bias (large pieces) and variance (few data per piece).