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.
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], the expected future discounted reward from s. It is not a fixed number: it is a function of state and, evaluated at random state St, 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) receiving noisy image xt=x0+σε and minimizing E∥D(xt)−x0∥2. Whatever the architecture, the best it can learn is E[x0∣xt], and Tweedie’s formula relates it to the gradient of logpt.
A derivative price. At interest rate r, the time-t price of a contract paying H at T is e−r(T−t)EQ[H∣Ft], an expectation under the risk-neutral measure depending on the entire market history to t, not one value.
Any squared-loss regression. A network minimizing E[(Y−f(X))2] estimates E[Y∣X] (the functional that loss elicits).
In all four cases the question is the same: what is the best prediction of a variable Y 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 Y over everything unknown, holding what you know fixed.
The plan:
The discrete case, averaging within groups, and the density case.
The general definition given a σ-algebra, with Radon-Nikodym existence and almost-sure uniqueness.
Geometry: in L2, conditional expectation is an orthogonal projection and therefore the best predictor.
Properties used throughout derivations: tower, taking out what is known, independence and Jensen.
The laws of total expectation and total variance.
Conditioning on probability-zero events: regular conditional distributions and the Borel-Kolmogorov paradox.
The best predictor versus the best linear predictor, and when they agree.
The discrete case: an average within each group
Roll two dice. Let X be the first and Y their sum. If you know X=4, the sum is 4 plus an unseen die, and your best prediction is 4+3.5=7.5. In general, using elementary conditional probability,
This is a number for each x: a function g(x)=x+3.5. But what happens when you do not fix x beforehand and evaluate g at the random variable itself?
E[Y∣X]:=g(X)=X+3.5.
E[Y∣X] is a random variable: it takes value 4.5 if a 1 is rolled, 5.5 for a 2, and so on up to 9.5. It is the prediction of Y you would make after seeing X, viewed before seeing it. Two facts characterize it and seed the general definition:
It depends only on X. It is constant on each event {X=x}.
It is correct on average within each event determined by X. For each x, E[g(X)1{X=x}]=g(x)P(X=x)=E[Y1{X=x}], and summing gives E[g(X)1{X∈B}]=E[Y1{X∈B}] for every set B.
Geometrically, X partitions Ω into six pieces {X=1},…,{X=6}, and E[Y∣X] replaces Y by its mean on each piece. What X 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]=x∑E[Y∣X=x]P(X=x)=E[E[Y∣X]].
With densities
If (X,Y) has joint density p(x,y) and marginal pX(x)>0, conditional densityp(y∣x)=p(x,y)/pX(x) gives
E[Y∣X=x]=∫yp(y∣x)dy=:g(x),E[Y∣X]=g(X).
For example, if (X,Y) is uniform on triangle 0<y<x<1, the joint density is 2 there, pX(x)=2x and p(y∣x)=1/x on (0,x): given X=x, Y is uniform on (0,x) and E[Y∣X]=X/2. The second property still holds, now with integrals: for Borel B,
But there is a problem absent in the discrete case: each event {X=x} has probability zero, so E[Y∣X=x] cannot be defined as a ratio. The density formula works, but what is it calculating? Changing p on a null set (another version of the same density) changes 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) is the collection of events determined by knowing X. More generally a σ-algebra G⊂F is a state of information: events A∈G are those whose occurrence you know. The figure makes this concrete with Ω=[0,1], uniform probability and G generated by a partition into intervals.
InteractiveAverage with available information
Y(ω)
Z=E[Y∣G], piecewise mean
Variable Y(ω)
Partition
Tower property
Pieces of G4
E[(Y−E[Y∣G])2]0.1354
Explained variance Var(Z)/Var(Y)67.4 %
E[Z] versus E[Y]0.0293 = 0.0293
maxA∣E[(Y−Z)1A]∣, A∈G0.000000
E[(Y−Z)ω]−0.0043
The blue curve is a variable Y(ω) on Ω=[0,1] with uniform probability. Cuts divide Ω into pieces and generate a finite σ-algebra G; knowing G means knowing which piece contains ω. Magenta shows E[Y∣G]: the average of Y on each piece. Add or remove cuts, or increase the dyadic level, and watch squared error fall. The final two readings compare residual Y−Z with piece indicators (always zero) and with ω, which is not G-measurable (almost never zero). Enable the tower: if H cuts are among G cuts, averaging twice equals averaging once; otherwise it fails. With the stepped shape, choose cuts at jumps.
Three observations the definition will capture:
E[Y∣G] is G-measurable: constant on each piece because G information cannot distinguish points in that piece.
It is correct on average on each G event: reading maxA∣E[(Y−Z)1A]∣ is zero for every union of pieces.
More information, better prediction: refining the partition lowers error, and in the dyadic limit E[Y∣Gk]→Y. Without cuts, G={∅,Ω} and prediction is the mean E[Y], the best guess without information. Sequence E[Y∣G0],E[Y∣G1],… with increasingly fine dyadic partitions is a first example of a martingale, and its convergence to Y 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 Y satisfies 2 and 3, but generally not 1: the problem is precisely to find the G-measurable variable behaving like Y on G events.
If G=σ(X), the Doob-Dynkin lemma from lesson 4 says every σ(X)-measurable variable has form g(X) with Borel g. Thus E[Y∣X]=g(X), and define E[Y∣X=x]:=g(x). This g is the regression function of Y on X and, as we will see, is determined only PX-almost surely: at an isolated x with P(X=x)=0 its value has no intrinsic meaning.
Proof
Uniqueness.Z−Z′ is G-measurable, so Aε={Z−Z′>ε}∈G for each ε>0. By condition 3 applied to both,
0=E[Y1Aε]−E[Y1Aε]=E[(Z−Z′)1Aε]≥εP(Aε),
thus P(Aε)=0. Since {Z>Z′}=⋃nA1/n is a countable union of null sets, P(Z>Z′)=0, and symmetrically P(Z<Z′)=0.
Existence. First suppose Y≥0. Define two finite measures on measurable space (Ω,G), not on (Ω,F): restriction PG=P∣G and
ν(A)=E[Y1A],A∈G.
ν is a measure by monotone convergence, finite because ν(Ω)=E[Y]<∞, and absolutely continuous with respect to PG: if P(A)=0, then Y1A=0 almost surely and ν(A)=0. By the Radon-Nikodym theorem applied on (Ω,G), there exists Z=dν/dPG≥0, G-measurable, with ν(A)=∫AZdPG for every A∈G. For a G-measurable function, integration with respect to PG or P agrees (true for G event indicators, by linearity for simple functions and by monotone convergence in general), so E[Z1A]=E[Y1A]. Taking A=Ω, E[Z]=E[Y]<∞. For general Y, Y=Y+−Y− and E[Y+∣G]−E[Y−∣G] satisfies all three conditions.
∎
Consider why the proof works. Applying Radon-Nikodym on (Ω,F) would give dν/dP=Y, adding nothing. Restricting both measures to G forces the density to be G-measurable: conditional expectation is the Radon-Nikodym derivative of YdP viewed at G‘s resolution. That is exactly what the figure did: distribute each piece’s mass ν(A) uniformly (according to P) within it.
Three extreme cases clarify the idea:
No information, G={∅,Ω}: the only G-measurable variables are constants, and condition 3 with A=Ω forces the constant to be E[Y].
Complete information, G=F (or Y already G-measurable): E[Y∣G]=Y.
Countable partition{B1,B2,…} of Ω generating G: E[Y∣G]=∑kP(Bk)E[Y1Bk]1Bk, summing pieces with P(Bk)>0 (any value works on null pieces). This is the elementary formula and the figure.
Geometry: an orthogonal projection in L2
For Y∈L2 there is a second construction, independent of Radon-Nikodym, that also explains why conditional expectation is the best prediction. Lesson 5 showed that L2, with ⟨U,V⟩=E[UV], is a Hilbert space (Lp spaces are complete). Within it, G-measurable variables form
L2(G)={W∈L2:W has a G-measurable version},
a vector subspace. It is closed: L2(Ω,G,P∣G) is complete by the same Riesz-Fischer theorem applied to that probability space, and its norm is the L2 norm; a complete subspace of a metric space is closed.
Proof
The projection exists. Let d=infW∈L2(G)∥Y−W∥2 and Wn be a minimizing sequence. By the parallelogram identity, ∥Wn−Wm∥2=2∥Y−Wn∥2+2∥Y−Wm∥2−4Y−2Wn+Wm2, and since 2Wn+Wm∈L2(G), the final term is at least 4d2. Thus ∥Wn−Wm∥2≤2∥Y−Wn∥2+2∥Y−Wm∥2−4d2, and this bound tends to 2d2+2d2−4d2=0: the sequence is Cauchy, converges in L2 to ΠY, and ΠY∈L2(G) because the subspace is closed. By norm continuity, ∥Y−ΠY∥=d. For any W∈L2(G), function t↦∥Y−ΠY−tW∥2=d2−2t⟨Y−ΠY,W⟩+t2∥W∥2 has its minimum at t=0, so ⟨Y−ΠY,W⟩=0: this is the orthogonal projection, as in finite-dimensional orthogonal projection.
The projection is conditional expectation. For A∈G, W=1A∈L2(G) and orthogonality says E[(Y−ΠY)1A]=0. ΠY is G-measurable and integrable (L2⊂L1 on a probability space), so it meets all three conditions and uniqueness gives ΠY=Z. This proves both Z∈L2(G) and point 1. Points 2 and 3 follow from Pythagoras: for W∈L2(G), Z−W∈L2(G) is orthogonal to Y−Z, so E[(Y−W)2]=E[(Y−Z)2]+E[(Z−W)2]; W=0 gives point 3.
∎
This gives a second existence proof, used by Williams in Probability with Martingales: construct E[Y∣G] in L2 as a projection, and for Y∈L1, Y≥0, approximate by Yn=min(Y,n)∈L2; projections E[Yn∣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, then L2(H)⊂L2(G) and the minimum over a larger set is lower: E[(Y−E[Y∣G])2]≤E[(Y−E[Y∣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
Y
E[Y∣X]
residual Y−Z
G-measurable variables
Information G
Probabilities
p3=0.30
Variable Y
Z(0.97, 0.97, 0.90)
E[(Y−Z)1B] per block0.0000, 0.0000
E[Y2]1.595
E[Z2]+E[(Y−Z)2]0.904 + 0.691
E[Z] and E[Y]0.950 and 0.950
With Ω={ω1,ω2,ω3}, a random variable is a vector (Y(ω1),Y(ω2),Y(ω3)) in R3 and the L2 inner product is ⟨U,V⟩=∑ipiUiVi. Each axis is scaled by 3pi, transforming that product to the screen's Euclidean product up to constant factor 3, preserving angles and perpendiculars. The σ(X)-measurable variables, constant in each X block, form the yellow plane, and E[Y∣X] (magenta) is the foot of the perpendicular from Y. Move Y and probabilities: the residual remains perpendicular and E[(Y−Z)1B] readings remain zero. Disable L2 geometry with nonuniform p: 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: L2 geometry depends on P. In original coordinates, “perpendicular” means with weighted product ∑ipiUiVi, not the Euclidean one. For block {ω1,ω2} and p=(0.5,0.2,0.3), conditional expectation on the block is (0.5Y1+0.2Y2)/0.7, the weighted average; simple average (Y1+Y2)/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.
Proof
(1) The right side is G-measurable and integrable, and condition 3 is linear. (2) Let Z=E[Y∣G] and A={Z<0}∈G. Then 0≥E[Z1A]=E[Y1A]≥0, so Z1A=0 almost surely and P(A)=0. The absolute-value bound follows from applying (1) and (2) to ∣Y∣−Y≥0 and ∣Y∣+Y≥0. (3) This is condition 3 with A=Ω. (4)Y itself satisfies the definition.
(5)E[Y∣H] is H-measurable and hence G-measurable, so the second equality is (4). For the first, E[Y∣H] is H-measurable and integrable, and for A∈H, since also A∈G,
E[E[Y∣H]1A]=E[Y1A]=E[E[Y∣G]1A],
which is the definition of E[E[Y∣G]∣H]. The only place H⊂G is used is applying condition 3 for E[Y∣G] to A∈H.
(6) For X=1B with B∈G and any A∈G: E[1BE[Y∣G]1A]=E[E[Y∣G]1A∩B]=E[Y1A∩B]=E[1BY1A], because A∩B∈G. By linearity this holds for simple X. If X,Y≥0, take simple G-measurable Xn with Xn↑X; since E[Y∣G]≥0, monotone convergence on both sides of E[XnE[Y∣G]1A]=E[XnY1A] gives the result. The general case follows by splitting X and Y into positive and negative parts.
(7) Constant E[Y] is G-measurable and, for A∈G, independence of Y and 1A gives E[Y1A]=E[Y]P(A)=E[E[Y]1A].
(8) A convex function on R is the supremum of a countable family of affine functions ℓn(x)=anx+bn (supporting lines at rational points). For each n, by (1), (2) and (4), E[φ(Y)∣G]≥E[ℓn(Y)∣G]=ℓn(E[Y∣G]) outside a null set Nn. Outside ⋃nNn, still null, all hold simultaneously, and taking the supremum over n yields the inequality. With φ(x)=∣x∣p and taking expectations, E∣E[Y∣G]∣p≤E[E[∣Y∣p∣G]]=E∣Y∣p.
(9) Let Vn=supk≥n∣Yk−Y∣, decreasing to 0 and bounded by 2V. By (2), ∣E[Yn∣G]−E[Y∣G]∣≤E[Vn∣G], which decreases almost surely to a limit L≥0. By unconditional dominated convergence, E[L]≤E[E[Vn∣G]]=E[Vn]→0, hence L=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 Z is independent of pair (X,Y), then E[Y∣X,Z]=E[Y∣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), E[h(X)(Y−E[Y∣X])]=0. The best predictor’s residual is orthogonal to every function of X. This is property 1 of the projection theorem, now for Y∈L1.
Laws of total expectation and total variance
Property 3 is the law of total expectation: E[Y]=E[E[Y∣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∈L2 as
Var(Y∣G)=E[(Y−E[Y∣G])2∣G]=E[Y2∣G]−E[Y∣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) with v(x)=Var(Y∣X=x).
Proof
With Z=E[Y∣G], write Y−E[Y]=(Y−Z)+(Z−E[Y]). The second summand lies in L2(G) and the first is orthogonal to all of L2(G), so Pythagoras gives 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)] by total expectation, and the second is Var(Z) because E[Z]=E[Y].
∎
The geometric interpretation is the projection theorem: centered vector Y−E[Y] decomposes into a part inside the subspace of what 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
group mean E[Y∣X=k]
overall mean E[Y]
explained component
unexplained component
Var(Y)=E[Var(Y∣X)]+Var(E[Y∣X])
unexplained17 %explained83 %
Var(Y)2.160
E[Var(Y∣X)], unexplained0.360
Var(E[Y∣X]), explained1.800
η2=Var(E[Y∣X])/Var(Y)0.833
Four groups X=1,…,4 with probabilities pk; in group k, Y has mean sck and standard deviation σ. Magenta segments are E[Y∣X=k] and the dashed line E[Y]. The stacked bar divides Var(Y) into what X does not explain (aqua, mean within-group variance) and what it explains (orange, variance of group means). Set s to zero, then σ to zero. Select a point: its deviation from E[Y] splits into a part in the subspace of functions of X and a perpendicular part. With different noise per group, Var(Y∣X) ceases to be constant.
Ratio η2=Var(E[Y∣X])/Var(Y) is the correlation ratio, the fraction of variance X explains with the best possible function. It is 0 if E[Y∣X] is constant and 1 if Y is a function of X. At the end we see η2≥ρ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 θ, Var(Y)=E[Var(Y∣θ)]+Var(E[Y∣θ]); the first term is noise remaining even if θ were known, the second uncertainty about θ, measured by disagreements between ensemble members. Rao-Blackwell: if T estimates something and you condition on statistic S, T∗=E[T∣S] has the same mean and variance Var(T)−E[Var(T∣S)]≤Var(T). Sufficiency of S is needed only so T∗ does not depend on the unknown parameter (the Rao-Blackwell theorem).
Conditioning on probability-zero events
Regular conditional distributions
For each event B, P(B∣G)=E[1B∣G] is an almost-surely defined random variable. One might naturally think that, for each fixed ω, B↦P(B∣G)(ω) is a probability measure. But σ-additivity P(⋃nBn∣G)=∑nP(Bn∣G) holds outside a null set different for each sequence(Bn), 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=1 is Jensen’s: reduce the uncountable to the countable. For each rational q, take a version of F(q,x)=P(Y≤q∣X=x). Monotonicity of F(⋅,x) on rationals, limits 0 and 1 and right-continuity on rationals are countably many conditions, each holding outside a null set, so all hold outside one null set N. Outside N, F(⋅,x) extends to a distribution function on R and defines a measure κ(x,⋅); on N use any fixed law. The π-λ theorem extends condition 3 from half-lines (−∞,q] to all Borel sets. Details are in Durrett, section 4.1.3.
When densities exist, κ(x,dy)=p(y∣x)dy with the previous lesson’s conditional density, justifying the continuous-case formula. But uniqueness is only PX-almost sure. If P(X=x0)=0, you can replace κ(x0,⋅) with any other law and still have a valid regular conditional distribution. P 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] and longitude λ∈(−π,π]. The area element is cosϕdϕdλ, so joint density is cosϕ/(4π): λ is uniform, ϕ has density cosϕ/2, and they are independent. Now condition on the point lying on a great circle.
The equator, {ϕ=0}. By independence, the conditional law of λ given ϕ is uniform for every ϕ. In particular the point is distributed uniformly over the equator.
A complete meridian, {λ∈{0,π}}. The law of ϕ given λ is cosϕ/2 for every λ. 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 C
points in the band
equator (z=0)
Conditional law of position ψ along C (density per radian)
ψ=0° and ±180°: equator; ±90°: poles.
Neighborhood of C
Neighborhood probability0.1380
Theoretical0.1395
Points inside20696 of 150000
P(∣latitude∣<30°∣neighborhood)0.336
Limit: band / wedge0.333 / 0.500
The band has the same width throughout C: each arc of C receives mass proportional to its length, and the conditional law is uniform, 1/(2π).
Uniform points on the sphere and a great circle C (magenta), a complete meridian relative to the vertical axis. The event 'the point is in C' has probability zero, so approximate it by a neighborhood of width ε 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 ψ along C. Lower ε as much as you like: the band always gives the uniform law and the wedge density ∣cosψ∣/4. Compare probability of landing within 30° of the equator: 1/3 versus 1/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, the regular conditional distribution of longitude given latitude, evaluated at ϕ=0. It corresponds to bands {∣ϕ∣<ε}, constant-width neighborhoods.
Law cosϕ/2 is Pϕ∣λ=0, latitude given longitude, evaluated at λ=0. It corresponds to wedges {∣λ∣<ε}.
Both are correct for their respective variables. Since regular conditional distributions are determined only almost surely, their values at the single point ϕ=0 or λ=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=0 or X/Y=1 describes the same line and gives different posteriors, as seen above. In diffusion, conditioning on xt=x presents no such problem because the observed variable is fixed (xt 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 Y from X, both in L2 with Var(X)>0, is the projection of Y onto the plane span{1,X}:
The two orthogonality conditions, E[Y−L^]=0 and E[(Y−L^)X]=0, are the least-squares normal equations with one regressor. Since span{1,X}⊂L2(σ(X)), the geometric tower says projecting Y onto the plane equals projecting E[Y∣X] onto the plane, and Pythagoras gives
Thus η2≥ρ2, with equality if and only if E[Y∣X] is affine in X. 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) and Y=X2+0.5ε, Cov(X,Y)=E[X3]=0: ρ=0 and the best linear predictor is constant E[Y]=1, with error Var(Y)=2.25. Conditional expectation is X2, with error 0.25: η2=2/2.25≈0.89. Zero correlation does not mean X cannot predict Y.
When they coincide: the Gaussian case. If (X,Y) is jointly normal, residual Y−L^[Y∣X] is uncorrelated with X and jointly normal with it, hence independent. By property 7, E[Y−L^∣X]=E[Y−L^]=0, so E[Y∣X]=L^[Y∣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=±1 with probability 1/2 and Xt=X0+σε, Bayes’ formula gives E[X0∣Xt]=tanh(Xt/σ2), a highly nonlinear function, while the best linear predictor is Xt/(1+σ2). With σ=0.5, linear error is σ2/(1+σ2)=0.2 and optimal error about three times smaller. You can check tanh(x/σ2)=x+σ2dxdlogpt(x) with pt the density of Xt: 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.09: with 8192 pieces of about 24 points each, averages start chasing noise. Error on new data instead is U-shaped, with minimum near 256 pieces, as is distance to true m: 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] 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−13, pure rounding; without nesting it is order 10−2, a real error. The tower is not an approximation: it is an exact identity requiring H⊂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. In the other two, conditional expectation wins by a wide margin. Quantile estimation of E[Y∣X] in the first case gives error slightly above theoretical 0.25 and η2 slightly below 0.89: tail pieces are wide and X2 varies greatly within them (bias). The last line expresses the earlier warning numerically: the residual is orthogonal to X and X2, but R2 and X2 have correlation 0.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/3 and 1/2 on the sphere, 1/2 and 1 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], and all are, in one way or another, averages over information:
Tool
Which σ-algebra it uses
When
df.groupby(x)[y].transform("mean")
that of a discrete variable
categorical X: exact conditional expectation of the empirical law
pd.cut or pd.qcut then groupby
fixed interval partition
quick exploration, as in the earlier cells
sklearn.tree.DecisionTreeRegressor
learned partition (leaves)
interpretable nonlinear regression; average per leaf
KNeighborsRegressor, kernels
neighborhoods of each point
local smoothing; bias and variance depend on neighborhood size
a network with MSE loss
none explicit
high dimension; approximates E[Y∣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 Y in each leaf, and the residual is orthogonal to leaf indicators as in the first figure, but not to a function of X varying within each leaf, such as sin(2πX). With X itself the product is almost zero (order 10−6 versus 10−3 with sine) because leaf contributions of opposite signs cancel; with sin(2π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 X be uniform on {1,…,6} and Y=X+ε with ε∼N(0,1) independent of X. Calculate Var(Y) using total variance.
NumericA sum with a random number of terms
A server receives N∼Poisson(4) requests per minute and each takes ξi∼Exp with mean 2 seconds, iid and independent of N. Calculate Var(S) for total time S=ξ1+⋯+ξN.
QuizFour identities and one error
Let X,Y,Z be variables with Y∈L1 (and XY∈L1 where needed). Which statement is false in general?
QuizAn orthogonal but dependent residual
Let X∼N(0,1), independent ε∼N(0,1) and Y=X+∣X∣ε. 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} as the limit of wedges {∣λ∣<ε}, that is, using the regular conditional distribution of latitude given longitude. What is the probability its latitude satisfies ∣ϕ∣<30°?
NumericCondition on a line via a ratio
Let X,Y be independent N(0,1) and R=X/Y. Calculate E[X2∣R=1] using the regular conditional distribution of X given R.
Prove: Let Y∈L2 and Z=E[Y∣G]. Then Z∈L2 and for every G-measurable W∈L2, E[(Y−W)2]≥E[(Y−Z)2], with equality if and only if W=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∈L2?
ProofFrom the tower to total variance
Prove: If H⊂G and Y∈L1, then E[E[Y∣G]∣H]=E[Y∣H]. If Y∈L2, Var(Y)=E[Var(Y∣G)]+Var(E[Y∣G]).
0
Let Z=E[Y∣G]. For the first part it suffices to show E[Y∣H] satisfies the definition of conditional expectation of Z given 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] is the best prediction of Y with information G: the unique variable (up to null sets) using only what G knows and correct on average over each G event. It exists by Radon-Nikodym and, in L2, is the orthogonal projection of Y onto 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] is a random variable g(X), with regression function g(x)=E[Y∣X=x] determined only PX-almost surely. In the discrete case it is a group average; with densities, ∫yp(y∣x)dy.
Definition: G-measurable, integrable and E[Z1A]=E[Y1A] for A∈G. It exists and is unique almost surely; it is the Radon-Nikodym derivative of YdP restricted to G.
Properties: linearity, monotonicity, tower (H⊂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]); η2≥ρ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 but are unique almost surely, and the Borel-Kolmogorov paradox shows two correct answers for the same circle.
Estimating E[Y∣X] is regression: piecewise averages, trees, neighbors or networks, all with a tradeoff between bias (large pieces) and variance (few data per piece).