Visualizing Decision Robustness with Scenario and Sensitivity Analysis
Environment
Python 3.14.6, NumPy 2.5.4, 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.
Overview
Check whether recommendations change across demand scenarios. Move from changing one probability to a two-dimensional map, deriving the switching boundaries and the maximum regret of a fixed action.
This article corresponds to Chapter 3, “Decision Making under Uncertainty”, of The Theory and Practice of Decision Making. The numerical examples are illustrative, not observed data.
Setup
Run the cells in order. Round to three significant figures only when displaying results.
Check versions, import libraries, and configure plots
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. Scenario analysis and sensitivity analysis
Scenario analysis compares meaningful combinations of assumptions, such as low, baseline, and high growth. Sensitivity analysis varies assumptions continuously to examine changes in values and recommendations. Neither method guarantees realistic assumptions.
The profit rows correspond to S, M, and L; columns correspond to low, medium, and high demand.
$$ \mathbf{G}=\begin{pmatrix}20&20&20\\-10&40&70\\-50&20&120\end{pmatrix}. $$
If low-demand probability is $\ell$ and high-demand probability is $h$, medium-demand probability is $1-\ell-h$. Feasibility requires $\ell\geq0,h\geq0,\ell+h\leq1$. When changing a probability, adjust the others so that they still sum to 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. Compare combinations of assumptions
Use probability vectors $(0.500,0.400,0.100)$, $(0.200,0.500,0.300)$, and $(0.100,0.300,0.600)$ for low, baseline, and high growth. These are demand distributions, not probabilities that the scenarios themselves occur.
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'}}
Low growth selects S, baseline growth M, and high growth L. Lines in the figure connect three calculated results; they do not represent changes over time.
3. One-variable sensitivity and a switching point
Fix $\ell=0.200$ and vary $h$. Medium-demand probability changes accordingly, so $0\leq h\leq0.800$.
$$ V_M=30+30h,\qquad V_L=6+100h. $$
The difference is $V_M-V_L=24-70h$, with a tie at $h=12/35\approx0.343$. Increasing $h$ from its baseline 0.300 by about $0.0429$, or 4.29 percentage points, changes the recommendation. M always exceeds S on this interval, so this intersection also changes the overall optimum.
$$ \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. Use a two-variable map to check a wider range
If low-demand probability also varies, M and L tie at $20+20\ell-70h=0$, or $h=(2+2\ell)/7$. M is at least as good as S when $h\geq(5\ell-2)/3$, and L is at least as good as S when $h\geq0.700\ell$.
Intersect these inequalities with the feasible probability region to find where each action is optimal. A grid plot assigns ties one color, so use the equations for exact boundaries. A colored area is not the probability that its action is optimal: no distribution over points in this probability plane has been specified.
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. A changed recommendation need not mean a large loss
Near a tie, a recommendation can change while the profit difference remains small. Fix the baseline action M and evaluate regret $\max_aV_a(\ell,h)-V_M(\ell,h)$ under each assumption.
Consider the rectangle $\ell\in[0.100,0.300]$, $h\in[0.200,0.400]$, which is entirely feasible. Each profit difference is affine, so their maximum, regret, is convex. Every point in the rectangle is a convex combination of its vertices; convexity bounds its regret by the largest vertex regret. Checking the four vertices is therefore sufficient.
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'}
The maximum regret from continuing to select M in this range is 6. Without a basis for the range, this remains an illustrative number. To assess the need for further research, report profit differences from a fixed action alongside ranking changes.
Conclusion
We calculated scenario comparisons, a one-variable switching point, two-variable optimal regions, and worst regret for a fixed action.
M is optimal at the baseline, but L becomes optimal when high-demand probability exceeds about 0.343 with low-demand probability fixed at 0.200. Report the assumption range and the profit differences when discussing robustness.