シナリオ分析と感度分析で意思決定の頑健性を可視化する

実行環境

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

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

概要

複数の需要シナリオで推奨が変わるかを調べる。確率を1つずつ動かす分析から2次元の領域図へ進み、最適案が切り替わる境界と、固定した案の最大後悔を計算する。

書籍『意思決定の理論と実践』/第3章 不確実性と意思決定基準。数値例は説明用に設定したものであり、実測データではない。

計算の準備

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

実行環境の確認・ライブラリの読み込み・描画設定
import sys
from pathlib import Path
from pprint import pprint

import numpy as np
import scipy
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter, ScalarFormatter
from matplotlib_inline.backend_inline import set_matplotlib_formats
from IPython.display import Math, display

# 表示だけを丸め、計算には丸める前の値を使う。
def s3(value):
    return format(float(value), "#.3g").rstrip(".")


np.set_printoptions(formatter={"float_kind": s3})
set_matplotlib_formats("svg")
plt.rcParams.update({
    "figure.figsize": (7, 4),
    "font.size": 11,
    "axes.spines.top": False,
    "axes.spines.right": False,
    "axes.grid": True,
    "grid.alpha": 0.200,
    "svg.fonttype": "path",
})
OUT_DIR = Path("109_nb_files")
OUT_DIR.mkdir(exist_ok=True)


def save_fig(fig, name):
    # 数値の目盛りだけを整形し、候補名などのラベルは保つ。
    for ax in fig.axes:
        for axis in (ax.xaxis, ax.yaxis):
            if isinstance(axis.get_major_formatter(), ScalarFormatter):
                axis.set_major_formatter(FuncFormatter(lambda x, pos: s3(x)))
    # SVGをファイルとセル出力の両方に残す。
    fig.tight_layout()
    fig.savefig(OUT_DIR / f"{name}.svg", format="svg", bbox_inches="tight")
    display(fig)
    plt.close(fig)


assert sys.version_info[:3] == (3, 14, 6), "Python 3.14.6のカーネルを選択すること"
print("実行環境: wa-src(3.14.6)")
print("Python:", sys.version.split()[0])
print("NumPy:", np.__version__, "SciPy:", scipy.__version__)
print("Matplotlib:", matplotlib.__version__)
実行環境: wa-src(3.14.6)
Python: 3.14.6
NumPy: 2.5.4 SciPy: 1.18.1
Matplotlib: 3.11.2

1. シナリオ分析と感度分析

シナリオ分析は、低成長・基準・高成長など、意味のある前提の組を比較する。感度分析は、前提を連続的に変えて評価値や推奨の変化を調べる。どちらも、前提の現実性を保証する方法ではない。

利益表はS、M、Lの順に次とする。列は低・中・高需要である。

$$ \mathbf{G}=\begin{pmatrix}20&20&20\\-10&40&70\\-50&20&120\end{pmatrix}. $$

低需要確率を$\ell$、高需要確率を$h$とすると、中需要確率は$1-\ell-h$である。許される範囲は$\ell\geq0,h\geq0,\ell+h\leq1$となる。確率を変更したとき、合計が1になるように残りの確率も変える必要がある。

$$ \begin{aligned} V_S&=20,\\ V_M&=-10\ell+40(1-\ell-h)+70h=40-50\ell+30h,\\ V_L&=-50\ell+20(1-\ell-h)+120h=20-70\ell+100h. \end{aligned} $$

2. 前提の組ごとに比較する

低成長、基準、高成長の確率ベクトルを、それぞれ$(0.500,0.400,0.100)$、$(0.200,0.500,0.300)$、$(0.100,0.300,0.600)$とする。これらは需要状態の分布であり、シナリオ自体の発生確率ではない。

actions = ["S", "M", "L"]
profit = np.array([[20, 20, 20], [-10, 40, 70], [-50, 20, 120]], dtype=float)
scenarios = np.array([[0.500, 0.400, 0.100], [0.200, 0.500, 0.300], [0.100, 0.300, 0.600]])
scenario_names = ["Low growth", "Baseline", "High growth"]
assert np.allclose(scenarios.sum(axis=1), 1)
values = profit @ scenarios.T
pprint({name: {action: s3(values[i, j]) for i, action in enumerate(actions)}
        for j, name in enumerate(scenario_names)})
assert np.array_equal(np.argmax(values, axis=0), [0, 1, 2])

fig, ax = plt.subplots()
for i, action in enumerate(actions):
    ax.plot(range(3), values[i], "o-", label=action)
ax.set(xticks=range(3), xticklabels=scenario_names, ylabel="Expected profit")
ax.yaxis.set_major_formatter(FuncFormatter(lambda y, pos: s3(y)))
ax.legend()
save_fig(fig, "01_scenarios")
{'Baseline': {'L': '36.0', 'M': '39.0', 'S': '20.0'},
 'High growth': {'L': '73.0', 'M': '53.0', 'S': '20.0'},
 'Low growth': {'L': '-5.00', 'M': '18.0', 'S': '20.0'}}

低成長ではS、基準ではM、高成長ではLを選ぶ。図の線は3つの計算結果を結んだもので、シナリオ間の時間的推移を表してはいない。

3. 1変数の感度と切り替え点

$\ell=0.200$を固定して$h$を動かす。中需要の確率がその分だけ増減するので、$0\leq h\leq0.800$である。

$$ V_M=30+30h,\qquad V_L=6+100h. $$

MとLの差は$V_M-V_L=24-70h$なので、同点は$h=12/35\approx0.343$になる。基準の$h=0.300$から約$0.0429$、すなわち4.29パーセントポイント増えると推奨が切り替わる。Mはこの範囲で常にSを上回るため、この交点は全体の最適案の切り替え点でもある。

$$ \displaystyle V_M-V_L=24-70h=0\ \Longrightarrow\ h=\frac{12}{35}\approx0.343 $$

h = np.linspace(0, 0.800, 401)
p_line = np.stack([np.full_like(h, 0.200), 0.800 - h, h])
line_values = profit @ p_line
threshold = 12 / 35
fig, ax = plt.subplots()
for i, action in enumerate(actions):
    ax.plot(h, line_values[i], label=action)
ax.axvline(threshold, color="gray", linestyle="--", label=f"Tie = {s3(threshold)}")
ax.set(xlabel="High-demand probability (Low fixed at 0.200)", ylabel="Expected profit")
ax.legend()
save_fig(fig, "02_one_way_sensitivity")

4. 2変数の領域図で見落としを減らす

低需要確率も動くなら、MとLの同点条件は$20+20\ell-70h=0$、すなわち$h=(2+2\ell)/7$である。MがS以上となる条件は$h\geq(5\ell-2)/3$、LがS以上となる条件は$h\geq0.700\ell$である。

各案が最適となる領域は、これらの不等式と確率の実行可能範囲の共通部分で決まる。格子による図では同点を1色で描くため、正確な境界は式で補う。色の領域の広さを、その案が最適になる確率と解釈してはいけない。確率平面上の前提に対する分布を別途指定していないからである。

from matplotlib.colors import ListedColormap

low, high = np.meshgrid(np.linspace(0, 1, 251), np.linspace(0, 1, 251))
valid = low + high <= 1
scores = np.stack([np.full_like(low, 20), 40 - 50 * low + 30 * high,
                   20 - 70 * low + 100 * high])
winner = np.ma.masked_where(~valid, np.argmax(scores, axis=0))
fig, ax = plt.subplots(figsize=(6, 5))
# 同じ最適案の領域をまとめ、SVGの継ぎ目とファイル容量を抑える。
im = ax.contourf(low, high, winner, levels=[-0.500, 0.500, 1.50, 2.50],
                 cmap=ListedColormap(["#8db5db", "#91c4a6", "#ecc286"]))
ax.grid(False)
ax.plot([0, 1], [1, 0], color="gray")
ax.scatter([0.200], [0.300], color="black", label="Baseline")
colorbar = fig.colorbar(im, ax=ax, ticks=[0, 1, 2])
colorbar.ax.set_yticklabels(actions)
ax.set(xlabel="Low-demand probability", ylabel="High-demand probability")
ax.legend()
save_fig(fig, "03_decision_regions")

5. 推奨が変わることと、損失が大きいことは別である

同点に近い場所では推奨が変わっても利益差は小さい。そこで基準で選んだMを固定し、前提ごとの後悔$\max_aV_a(\ell,h)-V_M(\ell,h)$を見る。

ここでは$\ell\in[0.100,0.300]$、$h\in[0.200,0.400]$という長方形を考える。範囲内はすべて実行可能である。各利益差は一次関数であり、それらの最大値である後悔は凸関数になる。長方形内の点は頂点の凸結合なので、凸性から後悔の最大値は頂点の最大値以下になる。したがって4頂点を調べれば十分である。

vertices = np.array([[low_p, 1 - low_p - high_p, high_p]
                     for low_p in [0.100, 0.300] for high_p in [0.200, 0.400]])
vertex_values = profit @ vertices.T
regret_of_m = vertex_values.max(axis=0) - vertex_values[1]
pprint({"4頂点の確率": vertices, "Mを固定した後悔": regret_of_m,
        "範囲内の最大後悔": s3(regret_of_m.max())})
assert np.isclose(regret_of_m.max(), 6)
{'4頂点の確率': array([[0.100, 0.700, 0.200],
       [0.100, 0.500, 0.400],
       [0.300, 0.500, 0.200],
       [0.300, 0.300, 0.400]]),
 'Mを固定した後悔': array([0.00, 6.00, 0.00, 2.00]),
 '範囲内の最大後悔': '6.00'}

この範囲でMを選び続けた場合の最大後悔は6である。範囲そのものに根拠がなければ、この値も説明用の数字にとどまる。追加調査の必要性を検討するときは、順位の変化と、判断を固定した場合の利益差を併記する。

結論

この記事では、シナリオ比較、1変数の切り替え点、2変数の最適領域、固定案の最大後悔を計算した。

低需要確率を0.200に固定した基準点ではMが最適だが、高需要確率が約0.343を超えるとLへ切り替わる。頑健性を報告するときは、調べた前提の範囲と、推奨が変わった場合の利益差も示す。