条件付き期待値とフィルトレーション

実行環境

Python 3.14.6、NumPy 2.4.6、SciPy 1.18.1、Matplotlib 3.11.2(Jupyter Notebook)。

本記事は2021年頃の記事をリライトし、上記の環境で計算したものである。

書籍:『確率過程の理論と実践』
章:第2章 確率過程の数学的性質

概要

条件付き期待値を「現在の情報で区別できる場合ごとの平均」として計算する。有限標本空間で定義を確認し、情報が増えるフィルトレーション、塔則、二乗誤差を最小にする性質を導く。最後に、将来の値を先に知ると条件付き期待値が変わる例を扱う。

計算の準備

コードは上から順に実行する。数値は表示時だけ有効数字3桁に整える。

実行環境の確認・ライブラリの読み込み・描画設定
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. 条件付き期待値は確率変数である

$\mathbb{P}(A)>0$ の事象 $A$ で条件付けると、$\mathbb{E}[X\mid A]=\mathbb{E}[X\mathbf{1}_A]/\mathbb{P}(A)$ は1個の数になる。一方、観測値 $Z$ がまだ確定していない段階の $\mathbb{E}[X\mid Z]$ は、$Z$ に応じて値が変わる確率変数である。

確率空間 $(\Omega,\mathcal{F},\mathbb{P})$ 上で、$\mathbb{E}[|X|]<\infty$ とする。情報を表す $\sigma$ 加法族 $\mathcal{G}\subseteq\mathcal{F}$ は、全体集合、補集合、可算和について閉じた事象の集まりである。$Y=\mathbb{E}[X\mid\mathcal{G}]$ は、次の2条件を満たす可積分な確率変数として定義される。

  1. $Y$ は $\mathcal{G}$ 可測である。つまり、$\mathcal{G}$ の情報だけで $Y$ の値を決められる。
  2. すべての $A\in\mathcal{G}$ について、以下の積分が一致する。

$$ \mathbb{E}[Y\mathbf{1}_A]=\mathbb{E}[X\mathbf{1}_A]. $$

この定義による $Y$ は確率1で一意である。確率0の集合での値は特定されない。定義の詳細はMITの条件付き期待値の講義資料 に沿っている。

有限個のグループで計算する

$\mathcal{G}$ が正の確率を持つ分割 $A_1,\ldots,A_m$ から生成されるとする。可測な $Y$ は各 $A_j$ 上で一定値 $c_j$ を取る。定義の第2条件に代入すると、

$$ \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} $$

有限標本空間では、各グループ内で確率を重みにした平均を計算すればよい。標本点の確率が異なる場合、単純平均にはならない。

2. 3回の観測で情報が増える例

独立な $B_1,B_2,B_3\sim\operatorname{Bernoulli}(p)$ を考え、$p=0.600$ とする。標本点は $\omega=(b_1,b_2,b_3)\in\{0,1\}^3$ であり、

$$ \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 $$

と定める。時刻 $n$ で最初の $n$ 個を観測するなら、情報の集まりは

$$ \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 $$

となる。このように時刻とともに増加する $\sigma$ 加法族の列がフィルトレーションである。一般の過程 $X_n$ について $\sigma(X_0,\ldots,X_n)$ を自然なフィルトレーションという。$Y_n$ が各時刻で $\mathcal{F}_n$ 可測なら、過程 $Y_n$ はこのフィルトレーションに適合している。

独立な未観測の変数の平均は $p$ のままである。$M_n=\mathbb{E}[X\mid\mathcal{F}_n]$ とすると、

$$ \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} $$

例えば $B_1=0$ と分かれば予測は $2.40$、$B_1=1$ なら $4.40$ になる。図1では、同じ枠の中の標本点は、その時刻の情報では区別できない。

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. 塔則を定義から確かめる

$\mathcal{G}\subseteq\mathcal{H}$ とし、$Z=\mathbb{E}[\mathbb{E}[X\mid\mathcal{H}]\mid\mathcal{G}]$ とおく。$Z$ は $\mathcal{G}$ 可測である。また、任意の $A\in\mathcal{G}$ は $\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} $$

したがって $Z$ は $\mathbb{E}[X\mid\mathcal{G}]$ の定義を満たし、一意性から塔則を得る。

$$ \boxed{\mathbb{E}[\mathbb{E}[X\mid\mathcal{H}]\mid\mathcal{G}] =\mathbb{E}[X\mid\mathcal{G}]\quad\text{a.s.}} $$

この例では $\mathbb{E}[M_{n+1}\mid\mathcal{F}_n]=M_n$ となる。可積分性と適合性も満たすので、$M_n$ はマルチンゲールである。これは経路が一定という意味ではなく、現在の情報で平均した次の予測値が現在の予測値に等しいという意味である。一般に $X_n$ が適合しているだけでは、マルチンゲールとは限らない。

# 定義の積分条件を、各分割のすべてのグループで照合する。
# 有限空間の事象はこれらのグループの和なので、これで十分である。
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. 二乗誤差を最小にする予測

ここからは $\mathbb{E}[X^2]<\infty$ を仮定する。$Y=\mathbb{E}[X\mid\mathcal{G}]$ とし、$Z$ を任意の二乗可積分な $\mathcal{G}$ 可測変数とする。条件付きJensen不等式より $\mathbb{E}[Y^2]\le\mathbb{E}[X^2]$ なので、$Y$ も二乗可積分である。$Y-Z$ は現在の情報で分かるので、

$$ \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} $$

この条件付き期待値の性質は、有界な可測変数を外へ出す公式を二乗可積分な変数へ拡張したものであり、積の可積分性はCauchy–Schwarz不等式で保証される。$X-Z=(X-Y)+(Y-Z)$ を二乗して平均すると、

$$ \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} $$

よって条件付き期待値は、同じ情報から作れる予測の中で平均二乗誤差を最小にする。情報が増えると選べる予測が増えるため、この最小誤差は増加しない。ただし、個々の標本点で誤差が必ず減るという主張ではない。

今回、未観測の $B_j-p$ は独立で分散が $p(1-p)=0.240$ である。係数の二乗を足すと、各時刻の最小誤差は順に

$$ (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 $$

となる。観測回数が同じだけ増えても、誤差の減り方は一様ではない。係数が大きい $B_3$ を知ると、残っていた誤差が大きく減る。

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. フィルトレーションを変えると性質も変わる

公平で独立な $\xi_1,\ldots,\xi_T\in\{-1,1\}$ から $S_n=\sum_{j=1}^n\xi_j$ を作る。自然な情報 $\mathcal{F}_n=\sigma(\xi_1,\ldots,\xi_n)$ では、未来の増分は独立なので

$$ \mathbb{E}[S_{n+1}\mid\mathcal{F}_n] =S_n+\mathbb{E}[\xi_{n+1}\mid\mathcal{F}_n]=S_n. $$

ところが、最初から終点 $S_T$ も知っている情報 $\mathcal{G}_n=\sigma(\mathcal{F}_n,S_T)$ を使うと話が変わる。残り $T-n$ 個の増分は、和が $S_T-S_n$ という条件の下で交換可能である。各増分の条件付き平均を $a$ とすれば、

$$ (T-n)a=\mathbb{E}\!\left[\sum_{j=n+1}^T\xi_j\mid\mathcal{G}_n\right] =S_T-S_n. $$

したがって $n<T$ で

$$ \mathbb{E}[S_{n+1}\mid\mathcal{G}_n] =S_n+\frac{S_T-S_n}{T-n}. $$

となり、一般には $S_n$ と一致しない。過程の式だけでマルチンゲール性を判断せず、何を知っているかまで指定する必要がある。予測に将来の値が混ざっていないかを確認する際にも、この区別が役立つ。

# 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])}

結論

この記事では、条件付き期待値を情報に応じた確率変数として定義し、フィルトレーションの下での予測の更新を計算した。

有限標本空間では、観測で区別できないグループごとに重み付き平均を取る。塔則は、詳しい情報で求めた予測を粗い情報で平均し直す性質である。二乗可積分な場合、条件付き期待値は現在の情報から作る予測の平均二乗誤差を最小にする。

マルチンゲール性は情報の選び方にも依存する。将来の終点をあらかじめ知る例では、同じランダムウォークでも条件付き平均が変わった。

参考文献