意思決定表と決定木をPythonで実装・可視化する
実行環境
Python 3.14.6、NumPy 2.5.4、SciPy 1.18.1、Matplotlib 3.11.2(Jupyter Notebook)。
本記事は2021年頃の記事をリライトし、上記の環境で計算したものである。
概要
3つの事業規模と3つの需要状態を、意思決定表と決定木の両方で表す。確率節点では確率による加重平均、決定節点では最大値を取る手順を実装し、同じ結果になることを確認する。
書籍『意思決定の理論と実践』/第1章 意思決定科学の基礎。数値例は説明用に設定したものであり、実測データではない。
計算の準備
コードは上から順に実行する。数値は表示時だけ有効数字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("103_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、需要は低・中・高の3状態である。利益の単位は万円とし、需要確率は各行動で共通とする。
| 規模 | 低需要 | 中需要 | 高需要 |
|---|---|---|---|
| S | 20 | 20 | 20 |
| M | -10 | 40 | 70 |
| L | -50 | 20 | 120 |
| 確率 | 0.200 | 0.500 | 0.300 |
行を行動、列を状態に対応させる。期待利益は、利益行列$\mathbf{G}$と確率ベクトル$\mathbf{p}$の積である。
$$ \mathbf{v}=\mathbf{G}\mathbf{p} =\begin{pmatrix}20&20&20\\-10&40&70\\-50&20&120\end{pmatrix} \begin{pmatrix}0.200\\0.500\\0.300\end{pmatrix} =\begin{pmatrix}20\\39\\36\end{pmatrix}. $$
例えばMは$-10\times0.200+40\times0.500+70\times0.300=-2+20+21=39$である。期待利益最大化ではMを選ぶ。確率の合計が1か、行列の列順と確率の順番が同じかを確認する必要がある。
actions = ["S", "M", "L"]
states = ["Low", "Middle", "High"]
profit = np.array([[20, 20, 20], [-10, 40, 70], [-50, 20, 120]], dtype=float)
probability = np.array([0.200, 0.500, 0.300])
assert profit.shape == (len(actions), len(states))
assert np.all(probability >= 0) and np.isclose(probability.sum(), 1)
expected = profit @ probability
pprint(dict(zip(actions, map(s3, expected))))
fig, ax = plt.subplots()
im = ax.imshow(profit, cmap="RdYlGn", vmin=-50, vmax=120)
ax.set(xticks=range(3), xticklabels=states, yticks=range(3), yticklabels=actions,
xlabel="State", ylabel="Action")
for i, j in np.ndindex(profit.shape):
ax.text(j, i, s3(profit[i, j]), ha="center", va="center")
fig.colorbar(im, ax=ax, label="Profit (10,000 JPY)")
save_fig(fig, "01_decision_table")
{'L': '36.0', 'M': '39.0', 'S': '20.0'}
2. 決定木の節点には種類がある
決定木の四角は自分で選ぶ節点、丸は確率で分岐する節点、末端は結果である。ここでの決定木は意思決定分析の図であり、機械学習の分類木ではない。
末端から根へ戻り、確率節点では条件付き確率を掛けた和を取る。決定節点では子の評価値の最大を取る。この処理を後ろ向き計算、または折り畳みと呼ぶ。
$$ V(n)=\begin{cases} g(n), & n\text{が末端},\\ \sum_{c}P(c\mid n)V(c), & n\text{が確率節点},\\ \max_{c}V(c), & n\text{が決定節点}. \end{cases} $$
末端の利益から順に計算すると、S、M、Lの確率節点は20、39、36になる。根では$\max(20,39,36)=39$となる。同点の場合、最適行動は複数あるので、最大値だけでなく同点の行動も残す。
$$ \displaystyle V(\mathrm{root})=\max(20,39,36)=39 $$
# 各行動の下に、需要による確率分岐を置く。
tree = {
"kind": "decision",
"children": [
{"kind": "chance", "name": action,
"probability": probability,
"children": [{"kind": "terminal", "value": float(v)} for v in row]}
for action, row in zip(actions, profit)
],
}
def evaluate(node):
if node["kind"] == "terminal":
return node["value"]
child_values = np.array([evaluate(child) for child in node["children"]])
if node["kind"] == "chance":
p = np.asarray(node["probability"])
assert np.all(p >= 0) and np.isclose(p.sum(), 1)
return float(p @ child_values)
if node["kind"] == "decision":
return float(child_values.max())
raise ValueError("未定義の節点である")
value = evaluate(tree)
selected = [actions[i] for i in np.flatnonzero(np.isclose(expected, value))]
pprint({"木の評価値": s3(value), "最適行動": selected})
assert np.isclose(value, expected.max()) and selected == ["M"]
{'最適行動': ['M'], '木の評価値': '39.0'}
# 木の位置を固定し、枝と注釈が重ならないように描く。
fig, ax = plt.subplots(figsize=(10, 7))
root = (0, 5)
ax.scatter(*root, marker="s", s=650, color="tab:blue", zorder=3)
ax.text(-0.180, 5, "Choose\n39", ha="right", va="center")
for i, action in enumerate(actions):
y = 9 - 4 * i
ax.plot([0, 1.40], [5, y], color="gray")
ax.text(0.700, (5 + y) / 2 + 0.250, action, ha="center")
ax.scatter(1.40, y, s=700, color="tab:orange", zorder=3)
ax.text(1.40, y, s3(expected[i]), ha="center", va="center", zorder=4)
for j, state in enumerate(states):
leaf_y = y + (1 - j) * 1.10
ax.plot([1.40, 3.50], [y, leaf_y], color="gray")
ax.text(2.50, (y + leaf_y) / 2 + 0.160,
f"{state}: {s3(probability[j])}", ha="center", fontsize=9)
ax.text(3.60, leaf_y, s3(profit[i, j]), va="center")
ax.set(xlim=(-0.700, 4.20), ylim=(-0.700, 10.7))
ax.axis("off")
save_fig(fig, "02_decision_tree")
3. 情報の順序を変えると別の問題になる
この木では、需要を知る前に規模を選ぶ。需要を見てから規模を選べるなら、状態ごとの最大値を先に取り、その後で平均する。
$$ \begin{aligned} \max_a\mathbb E[G(a,\theta)]&=39,\\ \mathbb E[\max_aG(a,\theta)]&=0.200\times20+0.500\times40+0.300\times120\\ &=4+20+36=60. \end{aligned} $$
両者の差は21である。決定節点を確率節点の後ろに移すことは、情報を先に得られるという仮定を追加することになる。同じ利益表でも、意思決定の時点が違えば答えが変わる。
perfect_information = float(probability @ profit.max(axis=0))
fig, ax = plt.subplots()
ax.bar(["Choose first", "Observe first"], [value, perfect_information],
color=["tab:blue", "tab:green"])
ax.set_ylabel("Expected profit (10,000 JPY)")
ax.yaxis.set_major_formatter(FuncFormatter(lambda y, pos: s3(y)))
save_fig(fig, "03_information_order")
pprint({"需要観測後の期待利益": s3(perfect_information),
"差": s3(perfect_information - value)})
{'差': '21.0', '需要観測後の期待利益': '60.0'}
表は同じ時点で比較する候補を一覧にするのに向く。木は調査、観測、行動が複数回現れる場合に向く。ただし、観測できない状態ごとに自由に行動を変える木を描くと、実際には利用できない情報を使った計算になる。各四角の時点で、意思決定者がどの情報を利用できるかを確認する。
結論
この記事では、意思決定表の行列積と、決定木の後ろ向き計算が同じ期待利益39を与えることを確認した。
確率節点では確率による加重平均、決定節点では最大値を取る。需要を観測する時点を変えると問題自体が変わるため、木の順序もモデルの前提として扱う。