Implementing and Visualizing Decision Tables and Trees in Python
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
We represent three business sizes and three demand states using both a decision table and a decision tree. We implement probability-weighted averaging at chance nodes and maximization at decision nodes, and check that both representations agree.
This article corresponds to Chapter 1, “Foundations of Decision Science”, 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("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. Put actions and states in a table
Business size is S, M, or L, and demand is low, medium, or high. Profit is measured in units of 10,000 JPY, with a common demand distribution for all actions.
| Size | Low demand | Medium demand | High demand |
|---|---|---|---|
| S | 20 | 20 | 20 |
| M | -10 | 40 | 70 |
| L | -50 | 20 | 120 |
| Probability | 0.200 | 0.500 | 0.300 |
Rows represent actions and columns represent states. Expected profits are the product of the profit matrix $\mathbf{G}$ and probability vector $\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}. $$
For M, for example, $-10\times0.200+40\times0.500+70\times0.300=-2+20+21=39$. Maximizing expected profit selects M. Check that probabilities sum to 1 and use the same state order as the matrix columns.
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. A decision tree has different kinds of nodes
Squares mark choices made by the decision maker, circles mark chance events, and terminal nodes give outcomes. This is a decision-analysis diagram, not a classification tree used in machine learning.
Work backward from terminal nodes toward the root. At each chance node, sum child values weighted by conditional probabilities. At each decision node, take the largest child value. This procedure is called backward induction or rollback.
$$ V(n)=\begin{cases} g(n), & n\text{ is terminal},\\ \sum_{c}P(c\mid n)V(c), & n\text{ is a chance node},\\ \max_{c}V(c), & n\text{ is a decision node}. \end{cases} $$
Starting with terminal profits gives values of 20, 39, and 36 at the chance nodes for S, M, and L. The root value is $\max(20,39,36)=39$. If actions tie, retain all optimal actions as well as the maximum value.
$$ \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. Changing the information order changes the problem
In this tree, size is chosen before demand is known. If size can be chosen after observing demand, first maximize within each state, then average.
$$ \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} $$
The difference is 21. Placing a decision node after a chance node assumes that the information is available before choosing. Even with the same profit table, a different decision time can give a different answer.
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'}
Tables are useful for listing alternatives compared at one time. Trees are useful when research, observations, and actions occur in several stages. A tree that allows an action to vary freely with an unobserved state uses information that is not actually available. At each square, check what information the decision maker has at that point.
Conclusion
We confirmed that matrix multiplication for the table and backward induction for the tree both give an expected profit of 39.
Take a probability-weighted average at chance nodes and a maximum at decision nodes. Changing when demand is observed changes the problem itself, so the order of nodes is part of the model.