Formulating Decisions with States, Actions, Outcomes, and Loss Functions

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 separate an ordering decision into four elements: states, actions, outcomes, and losses. We build a profit table and calculate the connection between minimizing expected loss and maximizing expected profit.

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("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. What is chosen, and what is unknown?

Let $a$ be an action chosen by the decision maker and $\theta$ a state that affects the outcome but cannot be chosen. Write the outcome as $y=g(a,\theta)$ and its undesirability as the loss $L(a,\theta)=\ell(g(a,\theta))$. An outcome may be a vector containing sales, leftover inventory, and unmet demand.

We order products for one day. Both the order quantity $q$ and demand $d$ can take the values 40, 80, or 120.

ElementDefinition in this example
State: demandDemand during the day, unobserved when ordering
Action: order quantityNumber of items ordered for the day
OutcomeSales, leftover stock, and unmet demand
LossNegative profit or opportunity loss

We assume the state arises independently of the action. If changing the price also changes demand, a common demand distribution may no longer apply to every action. Decide what is held fixed before comparing actions.

2. Calculate profit from outcomes

The sale price is 5, the purchase cost is 3, and the salvage value of an unsold item is 1, all in the same currency unit per item. We add no separate stockout penalty; missed sales are reflected in differences in profit.

$$ \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. $$

For example, if $q=80,d=40$, then 40 items sell and 40 remain. Thus,

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

When $q=80,d=120$, revenue is $5\times80$ and no stock remains, giving a profit of 160. With demand in columns and order quantities in rows, the profit matrix is as follows.

$$ \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. Combine losses with probabilities

Define loss as $L(q,d)=-\pi(q,d)$. Negative losses are valid: the ordering, with smaller values preferred, is what matters. For demand probabilities $\mathbf{p}=(0.250,0.500,0.250)^{\mathsf T}$, expected loss is the matrix product $\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} $$

We therefore order 80 items. If utility is not linear in money, expected monetary profit alone cannot represent the preference.

4. Change the baseline for loss

Let $b(d)=\max_q\pi(q,d)$ be the highest profit possible if demand were known in advance. Opportunity loss is $R(q,d)=b(d)-\pi(q,d)$, which is nonnegative in every case.

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

Because $\mathbb E[b(D)]$ does not depend on $q$, this change leaves the optimal order unchanged. Here $b(40)=80,b(80)=160,b(120)=240$, with expectation 160. Expected opportunity losses are $(80,40,80)$.

More generally, if $L^{\prime}(a,\theta)=cL(a,\theta)+h(\theta)$ with $c>0$, the minimizers of expected loss are unchanged under a state distribution shared by all actions. Adding an action-dependent term does not guarantee this property.

$$ \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]])}

Confusing minimization with maximization can reverse the selected action even when the code runs. Label table columns to show whether higher or lower values are preferred. This example also assumes that unsold items have salvage value; products with disposal costs require a different profit formula.

Conclusion

We distinguished states, actions, outcomes, and losses, and formulated the ordering problem as expected-loss minimization.

Ordering 80 items is optimal in this example. Replacing profit with opportunity loss also preserves the optimum when the baseline is common to all actions.