状態・行動・結果・損失関数による意思決定問題の定式化

実行環境

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

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

概要

発注量の選択を、状態、行動、結果、損失の4要素に分ける。利益表を作り、期待損失の最小化と期待利益の最大化がどのようにつながるかを計算する。

書籍『意思決定の理論と実践』/第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("102_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. 何を選び、何が分からないのか

意思決定者が選ぶ量を行動$a$、選べないが結果に影響する量を状態$\theta$とする。結果は$y=g(a,\theta)$、その望ましくなさは損失$L(a,\theta)=\ell(g(a,\theta))$で表す。結果は売上、残在庫、欠品数のようなベクトルでもよい。

ここでは1日分の商品を発注する。発注量$q$と需要$d$の候補は、いずれも40、80、120個である。

要素この例での定義
状態(需要)当日の需要。発注時には未観測
行動(発注量)当日の発注量
結果販売数、売れ残り数、欠品数
損失利益の符号を反転した値、または機会損失

状態は行動と無関係に生じると仮定する。価格変更で需要そのものが変わる場合は、同じ需要分布を全行動に使えるとは限らない。何を固定して比較しているかを先に決める必要がある。

2. 結果から利益を作る

販売価格を5、仕入価格を3、売れ残りの回収価格を1とする。金額は1個当たりの共通単位である。欠品の追加罰金は置かず、失った販売機会を利益の差として扱う。

$$ \mathbf{y}(q,d)=\bigl(\min(q,d),\ (q-d)_+,\ (d-q)_+\bigr), \qquad x_+=\max(x,0). $$

$$ \pi(q,d)=5\min(q,d)+(q-d)_+-3q. $$

例えば$q=80,d=40$なら、40個売れ、40個残る。したがって、

$$ \pi(80,40)=5\times40+1\times40-3\times80=0. $$

$q=80,d=120$では売上が$5\times80$、残在庫は0なので、利益は160である。列を需要、行を発注量にすると利益行列は次になる。

$$ \mathbf{\Pi}=\begin{pmatrix}80&80&80\\0&160&160\\-80&80&240\end{pmatrix}. $$

quantity = np.array([40, 80, 120])
demand = np.array([40, 80, 120])
q = quantity[:, None]
d = demand[None, :]
profit = 5 * np.minimum(q, d) + np.maximum(q - d, 0) - 3 * q
probability = np.array([0.250, 0.500, 0.250])
loss = -profit
expected_loss = loss @ probability
pprint({"利益": profit, "期待損失": expected_loss})
assert np.array_equal(profit, [[80, 80, 80], [0, 160, 160], [-80, 80, 240]])
assert quantity[np.argmin(expected_loss)] == 80

fig, ax = plt.subplots()
im = ax.imshow(profit, cmap="RdYlGn", vmin=-80, vmax=240)
ax.set(xticks=range(3), xticklabels=demand, yticks=range(3), yticklabels=quantity,
       xlabel="Demand", ylabel="Order quantity")
for i in range(3):
    for j in range(3):
        ax.text(j, i, str(profit[i, j]), ha="center", va="center", color="black")
fig.colorbar(im, ax=ax, label="Profit")
save_fig(fig, "01_profit_matrix")
{'利益': array([[ 80,  80,  80],
       [  0, 160, 160],
       [-80,  80, 240]]),
 '期待損失': array([-80.0, -120, -80.0])}

3. 損失と確率を組み合わせる

損失を$L(q,d)=-\pi(q,d)$と定める。損失が負でも問題はなく、小さいほど望ましいという順序が重要である。需要確率を$\mathbf{p}=(0.250,0.500,0.250)^{\mathsf T}$とすると、期待損失は行列積$\mathbf{L}\mathbf{p}$になる。

$$ \begin{aligned} \mathbb E[L(40,D)]&=-80,\\ \mathbb E[L(80,D)]&=0\times0.250-160\times0.500-160\times0.250=-120,\\ \mathbb E[L(120,D)]&=80\times0.250-80\times0.500-240\times0.250=-80. \end{aligned} $$

よって発注量80を選ぶ。結果の金額に対する効用が線形でない場合は、金銭利益の期待値だけでは選択を表現できない。

4. 損失の基準点は変更できる

需要を事前に知っていた場合の最大利益を$b(d)=\max_q\pi(q,d)$とする。機会損失は$R(q,d)=b(d)-\pi(q,d)$であり、全要素が非負になる。

$$ \mathbb E[R(q,D)]=\mathbb E[b(D)]-\mathbb E[\pi(q,D)]. $$

$\mathbb E[b(D)]$は$q$に依存しないため、この変更で最適発注量は変わらない。本例では$b(40)=80,b(80)=160,b(120)=240$であり、その期待値は160である。期待機会損失は$(80,40,80)$となる。

より一般に、$L^{\prime}(a,\theta)=cL(a,\theta)+h(\theta)$、$c>0$なら、全行動に共通の状態分布の下で期待損失の最小化解は変わらない。行動依存の項を加えると、この性質は保証されない。

$$ \displaystyle q^*\in\arg\min_q\mathbb{E}[L(q,D)]=\{80\} $$

benchmark = profit.max(axis=0)
regret = benchmark[None, :] - profit
expected_profit = profit @ probability
expected_regret = regret @ probability
pprint({"機会損失行列": regret, "期待機会損失": expected_regret})
assert np.allclose(expected_regret, benchmark @ probability - expected_profit)

fig, axes = plt.subplots(1, 2, figsize=(9, 3.60))
axes[0].bar(quantity, expected_profit, width=20)
axes[0].set(xlabel="Order quantity", ylabel="Expected profit", xticks=quantity)
axes[1].bar(quantity, expected_regret, width=20, color="tab:orange")
axes[1].set(xlabel="Order quantity", ylabel="Expected regret", xticks=quantity)
save_fig(fig, "02_expected_values")
{'期待機会損失': array([80.0, 40.0, 80.0]),
 '機会損失行列': array([[  0,  80, 160],
       [ 80,   0,  80],
       [160,  80,   0]])}

最小化と最大化を混ぜると、実装は動いていても逆の行動を選ぶ。表の列名には、値が大きいほどよいのか、小さいほどよいのかを明記する。今回は売れ残りの回収が可能であることも前提であり、廃棄費用がかかる商品なら利益式を変更する。

結論

この記事では、状態・行動・結果・損失を区別し、発注問題を期待損失の最小化として定式化した。

この例では80個の発注が最適である。利益を機会損失に変換しても、行動に共通の基準を引くだけなら最適解は変わらない。