Conditional Expectation and Filtrations
Environment
Python 3.14.6, NumPy 2.4.6, SciPy 1.18.1, Matplotlib 3.11.2 (Jupyter Notebook).
This article is a rewrite of a post from around 2021, with calculations performed in the environment described above.
Book: Theory and Practice of Stochastic Processes
Chapter 2: Mathematical Properties of Stochastic Processes
Overview
We calculate conditional expectations as averages over cases that can be distinguished using current information. On a finite sample space, we examine the definition, filtrations that accumulate information, the tower property, and the minimum mean squared error property. Finally, we show how knowing a future value changes a conditional expectation.
Preparation
Run the code cells in order. Round numerical values to three significant figures only for display.
Check the environment, import libraries, and configure plots
import platform
import sys
from pathlib import Path
from pprint import pprint
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import font_manager
from matplotlib.ticker import FuncFormatter, MaxNLocator
import numpy as np
import scipy
from scipy import stats
from IPython.display import Math, SVG, display
from itertools import product
from matplotlib.patches import Rectangle
%matplotlib inline
def sig3(value):
"""数値を有効数字3桁の表示用文字列にする。"""
return format(float(value), '#.3g').removesuffix('.')
np.set_printoptions(formatter={'float_kind': sig3}, linewidth=100)
# 日本語フォントを選び、SVGに文字の輪郭を埋め込む。
font_names = {font.name for font in font_manager.fontManager.ttflist}
for candidate in ['Hiragino Sans', 'Noto Sans CJK JP', 'IPAexGothic', 'YuGothic']:
if candidate in font_names:
plt.rcParams['font.family'] = candidate
break
plt.rcParams.update({
'font.size': 11,
'axes.spines.top': False,
'axes.spines.right': False,
'axes.unicode_minus': False,
'svg.fonttype': 'path',
'svg.hashsalt': 'stochastic-104',
})
# Notebookのフォルダー、またはリポジトリ直下から実行する。
notebook_dir = Path.cwd()
if (notebook_dir / 'pyproject.toml').is_file():
notebook_dir /= 'series/stochastic-processes/104'
figure_dir = notebook_dir / '104_nb_files'
figure_dir.mkdir(parents=True, exist_ok=True)
def save_figure(fig, filename):
# 目盛りの小数も3桁にそろえる。文字列の目盛りはそのまま使う。
formatter = FuncFormatter(
lambda value, _: str(int(value)) if float(value).is_integer() else sig3(value)
)
for ax in fig.axes:
if ax.xaxis.get_converter() is None and ax.get_xscale() == 'linear':
ax.xaxis.set_major_formatter(formatter)
if ax.yaxis.get_converter() is None and ax.get_yscale() == 'linear':
ax.yaxis.set_major_formatter(formatter)
path = figure_dir / filename
fig.savefig(path, format='svg', bbox_inches='tight', metadata={'Date': None})
plt.close(fig)
display(SVG(filename=str(path)))
print('環境名: wa-src(3.14.6)')
print(f'Python: {platform.python_version()}')
print(f'OS: {platform.system()} / {platform.machine()}')
print(f'NumPy: {np.__version__}, SciPy: {scipy.__version__}')
print(f'Matplotlib: {matplotlib.__version__}')
print(f'画像ディレクトリ: {figure_dir.name}')
assert sys.version_info[:3] == (3, 14, 6), '指定のPython環境を選択すること'
環境名: wa-src(3.14.6)
Python: 3.14.6
OS: Darwin / arm64
NumPy: 2.4.6, SciPy: 1.18.1
Matplotlib: 3.11.2
画像ディレクトリ: 104_nb_files
1. Conditional Expectation Is a Random Variable
Conditioning on an event $A$ with $\mathbb{P}(A)>0$ gives a single number, $\mathbb{E}[X\mid A]=\mathbb{E}[X\mathbf{1}_A]/\mathbb{P}(A)$. In contrast, before the observation $Z$ is known, $\mathbb{E}[X\mid Z]$ is a random variable whose value depends on $Z$.
On the probability space $(\Omega,\mathcal{F},\mathbb{P})$, assume $\mathbb{E}[|X|]<\infty$. The $\sigma$-algebra $\mathcal{G}\subseteq\mathcal{F}$ represents information: it contains the whole space and is closed under complements and countable unions. The conditional expectation $Y=\mathbb{E}[X\mid\mathcal{G}]$ is an integrable random variable satisfying two conditions:
- $Y$ is $\mathcal{G}$-measurable: the information in $\mathcal{G}$ is enough to determine $Y$.
- For every $A\in\mathcal{G}$, the following integrals agree.
$$ \mathbb{E}[Y\mathbf{1}_A]=\mathbb{E}[X\mathbf{1}_A]. $$
This definition determines $Y$ uniquely almost surely. Values on probability-zero sets are not specified. We follow MIT’s lecture on conditional expectation .
Calculation over a Finite Partition
Suppose $\mathcal{G}$ is generated by a partition $A_1,\ldots,A_m$ whose members have positive probability. A measurable $Y$ takes a constant value $c_j$ on each $A_j$. Substituting into the second condition gives
$$ \begin{aligned} c_j\mathbb{P}(A_j)&=\mathbb{E}[X\mathbf{1}_{A_j}],\\ c_j&=\frac{\mathbb{E}[X\mathbf{1}_{A_j}]}{\mathbb{P}(A_j)},\\ \mathbb{E}[X\mid\mathcal{G}] &=\sum_{j=1}^m c_j\mathbf{1}_{A_j}. \end{aligned} $$
On a finite sample space, calculate a probability-weighted average within each group. If sample points have unequal probabilities, this is not a simple arithmetic average.
2. Information from Three Observations
Let $B_1,B_2,B_3\sim\operatorname{Bernoulli}(p)$ be independent and set $p=0.600$. A sample point is $\omega=(b_1,b_2,b_3)\in\{0,1\}^3$. Define
$$ \mathbb{P}(\{\omega\})=p^{b_1+b_2+b_3}(1-p)^{3-b_1-b_2-b_3}, \qquad X=2B_1+B_2+3B_3 $$
If the first $n$ variables are observed by time $n$, the available information is
$$ \mathcal{F}_0=\{\varnothing,\Omega\},\qquad \mathcal{F}_n=\sigma(B_1,\ldots,B_n),\qquad \mathcal{F}_0\subseteq\mathcal{F}_1\subseteq\mathcal{F}_2\subseteq\mathcal{F}_3 $$
Such an increasing sequence of $\sigma$-algebras is a filtration. For a general process $X_n$, $\sigma(X_0,\ldots,X_n)$ is its natural filtration. If $Y_n$ is $\mathcal{F}_n$-measurable at every time, the process $Y_n$ is adapted to the filtration.
The mean of each independent, unobserved variable remains $p$. Defining $M_n=\mathbb{E}[X\mid\mathcal{F}_n]$ gives
$$ \begin{aligned} M_0&=2p+p+3p=6p=3.60,\\ M_1&=2B_1+\mathbb{E}[B_2]+3\mathbb{E}[B_3]=2B_1+2.40,\\ M_2&=2B_1+B_2+3\mathbb{E}[B_3]=2B_1+B_2+1.80,\\ M_3&=2B_1+B_2+3B_3=X. \end{aligned} $$
For example, observing $B_1=0$ gives the prediction $2.40$, while $B_1=1$ gives $4.40$. In Figure 1, the sample points inside the same box cannot be distinguished using the information available at that time.
outcomes = np.array(list(product([0, 1], repeat=3)))
p = 0.600
probabilities = p**outcomes.sum(axis=1) * (1 - p)**(3 - outcomes.sum(axis=1))
target = outcomes @ np.array([2, 1, 3])
def conditional_mean(values, labels, weights):
"""同じ観測ラベルを持つ標本点の重み付き平均を返す。"""
result = np.empty(len(values), dtype=float)
for label in np.unique(labels):
selected = labels == label
result[selected] = np.sum(weights[selected] * values[selected]) / weights[selected].sum()
return result
# 先頭n個のビットを整数ラベルにし、観測が同じ標本点をまとめる。
groups = [np.zeros(8, dtype=int)]
groups += [outcomes[:, :n] @ (2**np.arange(n - 1, -1, -1)) for n in range(1, 4)]
predictions = np.column_stack([
conditional_mean(target, labels, probabilities) for labels in groups
])
expected = np.column_stack([
np.full(8, 6 * p),
2 * outcomes[:, 0] + 4 * p,
2 * outcomes[:, 0] + outcomes[:, 1] + 3 * p,
target,
])
np.testing.assert_allclose(predictions, expected, atol=1.00e-12)
pprint([{'標本点': ''.join(map(str, bits)), '確率': sig3(weight),
'X': int(value), 'M1': sig3(prediction)}
for bits, weight, value, prediction in
zip(outcomes, probabilities, target, predictions[:, 1])], sort_dicts=False)
fig, ax = plt.subplots(figsize=(11, 4), layout='constrained')
for n, labels in enumerate(groups):
for label in np.unique(labels):
indices = np.flatnonzero(labels == label)
left, width = indices[0], len(indices)
value = predictions[left, n]
ax.add_patch(Rectangle((left, n), width, 0.800,
facecolor=plt.cm.Blues(0.150 + 0.700 * value / 6),
edgecolor='white', linewidth=2))
ax.text(left + width / 2, n + 0.400, sig3(value),
ha='center', va='center', color='white' if value > 3 else 'black')
ax.set(xlim=(0, 8), ylim=(4, -0.200),
title='図1 観測による分割と各グループの条件付き期待値', xlabel='標本点 (B1, B2, B3)')
# 標本点のラベルと軸名が重ならないよう、間隔を取る。
ax.set_xlabel('標本点 (B1, B2, B3)', labelpad=28)
for x, bits in enumerate(outcomes):
ax.text(x + 0.500, 4.15, ''.join(map(str, bits)), ha='center')
ax.set_xticks([])
ax.set_yticks([])
ax.set_frame_on(False)
for n in range(4):
ax.text(-0.150, n + 0.400, f'F{n}', ha='right', va='center')
save_figure(fig, '01_information_partitions.svg')
[{'標本点': '000', '確率': '0.0640', 'X': 0, 'M1': '2.40'},
{'標本点': '001', '確率': '0.0960', 'X': 3, 'M1': '2.40'},
{'標本点': '010', '確率': '0.0960', 'X': 1, 'M1': '2.40'},
{'標本点': '011', '確率': '0.144', 'X': 4, 'M1': '2.40'},
{'標本点': '100', '確率': '0.0960', 'X': 2, 'M1': '4.40'},
{'標本点': '101', '確率': '0.144', 'X': 5, 'M1': '4.40'},
{'標本点': '110', '確率': '0.144', 'X': 3, 'M1': '4.40'},
{'標本点': '111', '確率': '0.216', 'X': 6, 'M1': '4.40'}]
$$ \displaystyle \mathbb{E}[X\mid\mathcal{F}_1]=2B_1+2.40 $$
3. Derive the Tower Property from the Definition
Let $\mathcal{G}\subseteq\mathcal{H}$ and set $Z=\mathbb{E}[\mathbb{E}[X\mid\mathcal{H}]\mid\mathcal{G}]$. Then $Z$ is $\mathcal{G}$-measurable. Since every $A\in\mathcal{G}$ also belongs to $\mathcal{H}$,
$$ \begin{aligned} \mathbb{E}[Z\mathbf{1}_A] &=\mathbb{E}[\mathbb{E}[X\mid\mathcal{H}]\mathbf{1}_A]\\ &=\mathbb{E}[X\mathbf{1}_A]. \end{aligned} $$
Thus $Z$ satisfies the definition of $\mathbb{E}[X\mid\mathcal{G}]$. Uniqueness gives the tower property.
$$ \boxed{\mathbb{E}[\mathbb{E}[X\mid\mathcal{H}]\mid\mathcal{G}] =\mathbb{E}[X\mid\mathcal{G}]\quad\text{a.s.}} $$
In this example, $\mathbb{E}[M_{n+1}\mid\mathcal{F}_n]=M_n$. Integrability and adaptedness also hold, so $M_n$ is a martingale. This does not mean each path is constant: the next prediction, averaged over current information, equals the current prediction. In general, adaptedness of $X_n$ alone does not make it a martingale.
# 定義の積分条件を、各分割のすべてのグループで照合する。
# 有限空間の事象はこれらのグループの和なので、これで十分である。
for n, labels in enumerate(groups):
for label in np.unique(labels):
mask = labels == label
lhs = probabilities[mask] @ predictions[mask, n]
rhs = probabilities[mask] @ target[mask]
np.testing.assert_allclose(lhs, rhs, atol=1.00e-12)
if n < 3:
averaged_next = conditional_mean(predictions[:, n + 1], labels, probabilities)
np.testing.assert_allclose(averaged_next, predictions[:, n], atol=1.00e-12)
pprint({'各時刻のE[M_n]': [sig3(v) for v in probabilities @ predictions],
'E[X]': sig3(probabilities @ target)}, sort_dicts=False)
print('条件付き期待値の定義と塔則を全標本点で確認した。')
fig, ax = plt.subplots(figsize=(9, 4), layout='constrained')
for bits, path in zip(outcomes, predictions):
ax.plot(range(4), path, 'o-', alpha=0.750, label=''.join(map(str, bits)))
ax.plot(range(4), probabilities @ predictions, 'k--', lw=2, label='確率で重み付けした平均')
ax.set(xlabel='観測した回数 n', ylabel='条件付き期待値 M_n',
title='図2 予測は経路ごとに変化し、平均は一定になる', xticks=range(4))
ax.legend(ncol=3, fontsize=9)
save_figure(fig, '02_conditional_predictions.svg')
{'各時刻のE[M_n]': ['3.60', '3.60', '3.60', '3.60'], 'E[X]': '3.60'}
条件付き期待値の定義と塔則を全標本点で確認した。
4. The Prediction that Minimizes Squared Error
Now assume $\mathbb{E}[X^2]<\infty$. Let $Y=\mathbb{E}[X\mid\mathcal{G}]$, and let $Z$ be any square-integrable, $\mathcal{G}$-measurable variable. Conditional Jensen’s inequality gives $\mathbb{E}[Y^2]\le\mathbb{E}[X^2]$, so $Y$ is square-integrable too. Since $Y-Z$ is known from the current information,
$$ \begin{aligned} \mathbb{E}[(X-Y)(Y-Z)] &=\mathbb{E}[(Y-Z)\mathbb{E}[X-Y\mid\mathcal{G}]]\\ &=\mathbb{E}[(Y-Z)\cdot0]=0. \end{aligned} $$
This extends the rule for taking a bounded measurable factor outside a conditional expectation to square-integrable variables. The Cauchy–Schwarz inequality guarantees integrability of the product. Squaring $X-Z=(X-Y)+(Y-Z)$ and taking expectations gives
$$ \begin{aligned} \mathbb{E}[(X-Z)^2] &=\mathbb{E}[(X-Y)^2]+2\mathbb{E}[(X-Y)(Y-Z)]+\mathbb{E}[(Y-Z)^2]\\ &=\mathbb{E}[(X-Y)^2]+\mathbb{E}[(Y-Z)^2]\\ &\ge\mathbb{E}[(X-Y)^2]. \end{aligned} $$
Conditional expectation therefore minimizes mean squared error among predictions based on the same information. More information allows a larger class of predictions, so the minimum error cannot increase. This does not claim that the error decreases at every individual sample point.
Here the unobserved variables $B_j-p$ are independent with variance $p(1-p)=0.240$. Summing squared coefficients gives the successive minimum errors:
$$ (2^2+1^2+3^2)\,0.240=3.36,\quad (1^2+3^2)\,0.240=2.40,\quad 3^2\,0.240=2.16,\quad 0 $$
The reduction is not uniform across observations. Learning $B_3$, whose coefficient is largest, removes a larger portion of the remaining error.
errors = target[:, None] - predictions
mse = probabilities @ errors**2
mse_theory = p * (1 - p) * np.array([14, 10, 9, 0])
np.testing.assert_allclose(mse, mse_theory, atol=1.00e-12)
# F1に基づく最適予測を一定量ずらすと、誤差がずれの二乗だけ増える。
offsets = np.linspace(-2, 2, 81)
shifted_mse = np.array([
probabilities @ (target - predictions[:, 1] - offset)**2 for offset in offsets
])
np.testing.assert_allclose(shifted_mse, mse[1] + offsets**2, atol=1.00e-12)
pprint({'最小平均二乗誤差': [sig3(v) for v in mse]}, sort_dicts=False)
fig, axes = plt.subplots(1, 2, figsize=(11, 4), layout='constrained')
axes[0].bar(range(4), mse, color='#3979a5')
for n, value in enumerate(mse):
axes[0].text(n, value + 0.0800, sig3(value), ha='center')
axes[0].set(xticks=range(4), xlabel='観測した回数 n', ylabel='平均二乗誤差',
title='図3a 情報が増えると最小誤差は減る', ylim=(0, 4))
axes[1].plot(offsets, shifted_mse)
axes[1].scatter([0], [mse[1]], color='#c24a36', zorder=3)
axes[1].set(xlabel='M1に加える定数', ylabel='平均二乗誤差',
title='図3b 条件付き期待値からのずれの影響')
save_figure(fig, '03_prediction_error.svg')
{'最小平均二乗誤差': ['3.36', '2.40', '2.16', '0.00']}
5. Changing the Filtration Changes the Property
Construct $S_n=\sum_{j=1}^n\xi_j$ from independent, fair $\xi_1,\ldots,\xi_T\in\{-1,1\}$. Under the natural information $\mathcal{F}_n=\sigma(\xi_1,\ldots,\xi_n)$, future increments are independent, so
$$ \mathbb{E}[S_{n+1}\mid\mathcal{F}_n] =S_n+\mathbb{E}[\xi_{n+1}\mid\mathcal{F}_n]=S_n. $$
Now enlarge the information to $\mathcal{G}_n=\sigma(\mathcal{F}_n,S_T)$, so the endpoint $S_T$ is known from the start. Conditional on their sum being $S_T-S_n$, the remaining $T-n$ increments are exchangeable. If each increment has conditional mean $a$,
$$ (T-n)a=\mathbb{E}\!\left[\sum_{j=n+1}^T\xi_j\mid\mathcal{G}_n\right] =S_T-S_n. $$
Thus, for $n<T$,
$$ \mathbb{E}[S_{n+1}\mid\mathcal{G}_n] =S_n+\frac{S_T-S_n}{T-n}. $$
This generally differs from $S_n$. To assess the martingale property, specify what is known, not only the formula for the process. This distinction also helps check whether predictions contain future information.
# 6回のランダムウォークの全64経路を列挙する。
T, n = 6, 2
all_increments = np.array(list(product([-1, 1], repeat=T)))
all_walks = np.column_stack([np.zeros(2**T, dtype=int), all_increments.cumsum(axis=1)])
uniform_weights = np.full(2**T, 1 / 2**T)
prefix_labels = ((all_increments[:, :n] + 1) // 2) @ (2**np.arange(n - 1, -1, -1))
terminal_labels = (all_walks[:, -1] + T) // 2
enlarged_labels = prefix_labels * (T + 1) + terminal_labels
natural_prediction = conditional_mean(all_walks[:, n + 1], prefix_labels, uniform_weights)
enlarged_prediction = conditional_mean(all_walks[:, n + 1], enlarged_labels, uniform_weights)
bridge_prediction = all_walks[:, n] + (all_walks[:, -1] - all_walks[:, n]) / (T - n)
np.testing.assert_allclose(natural_prediction, all_walks[:, n], atol=1.00e-12)
np.testing.assert_allclose(enlarged_prediction, bridge_prediction, atol=1.00e-12)
# 最初の2増分が(+1,-1)、つまり現在位置が0の履歴に絞る。
selected = np.all(all_increments[:, :n] == [1, -1], axis=1)
possible_ends = np.unique(all_walks[selected, -1])
fig, ax = plt.subplots(figsize=(8, 4), layout='constrained')
ax.plot(possible_ends, possible_ends / (T - n), 'o-', label='終点も知る場合')
ax.axhline(0, color='black', linestyle='--', label='過去だけを知る場合')
ax.set(xlabel='既知の終点 S6', ylabel='次の位置 S3 の条件付き期待値',
title='図4 同じ現在位置 S2=0 でも、知っている情報で予測が変わる')
ax.legend()
save_figure(fig, '04_enlarged_information.svg')
pprint({'可能な終点': possible_ends,
'終点が既知のときの予測': possible_ends / (T - n)}, sort_dicts=False)
{'可能な終点': array([-4, -2, 0, 2, 4]),
'終点が既知のときの予測': array([-1.00, -0.500, 0.00, 0.500, 1.00])}
Conclusion
This article defined conditional expectation as a random variable determined by information and calculated how predictions update under a filtration.
On a finite sample space, use weighted averages within groups that the observations cannot distinguish. The tower property averages a prediction based on finer information back to coarser information. Under square integrability, conditional expectation minimizes mean squared prediction error among predictions using the available information.
The martingale property also depends on the information chosen. Knowing the future endpoint changed the conditional mean even for the same random walk.