Environment
Python 3.14.6, NumPy 2.4.6, SciPy 1.18.1, Polars 2.1.0, statsmodels 0.14.6, Matplotlib 3.11.2.
Overview
Chapter 4, “Estimating What Drives Choice,” of Marketing Science in Theory and Practice examines how price, performance, and brand relate to product choice. This article follows the chapter from the business problem through logit choice models, estimation in Python, and comparisons of possible actions. Using simulated smartphone choices, we compare a ¥10,000 price cut with three additional hours of battery life.
Setup code (imports and display settings)
from importlib.metadata import version
from pathlib import Path
from pprint import pprint
import platform
import numpy as np
import polars as pl
import matplotlib.pyplot as plt
import matplotlib_fontja # 日本語の軸ラベルを表示する。
from matplotlib.ticker import FuncFormatter, ScalarFormatter
from scipy.special import expit, softmax
from scipy.stats import gumbel_r, norm
from statsmodels.discrete.conditional_models import ConditionalLogit
from IPython.display import Latex, SVG, display
# ノートブックのフォルダーとリポジトリ直下のどちらからも実行できる。
base_dir = Path.cwd()
if (base_dir / "blog/04/04_nb.ipynb").exists():
base_dir = base_dir / "blog/04"
figure_dir = base_dir / "04_nb_files"
figure_dir.mkdir(exist_ok=True)
def sig3(value):
"""末尾のゼロを残し、有効数字3桁にそろえる。"""
return format(float(value), "#.3g").removesuffix(".")
def show_math(tex):
"""重要式の原稿の区切りを、出力用の $$ に変換する。"""
tex = tex.strip()
if tex.startswith(r"\(") and tex.endswith(r"\)"):
tex = tex[2:-2].strip()
display(Latex("$$\n" + tex + "\n$$"))
def save_svg(fig, filename):
"""SVGを保存し、同じ画像を出力欄にも埋め込む。"""
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 value, _: str(int(value))
if float(value).is_integer() else sig3(value)
))
path = figure_dir / filename
fig.savefig(path, format="svg", bbox_inches="tight")
plt.close(fig)
display(SVG(filename=str(path)))
np.set_printoptions(formatter={"float_kind": sig3})
plt.rcParams.update({"font.size": 11, "axes.spines.top": False,
"axes.spines.right": False, "svg.fonttype": "path"})
colors = ["#326B9C", "#B56836", "#45806B"]
print("実行環境: wa-src(3.14.6)")
print(f"Python: {platform.python_version()}")
for package in ["numpy", "scipy", "polars", "statsmodels", "matplotlib",
"matplotlib-fontja", "ipython"]:
print(f"{package}: {version(package)}")
実行環境: wa-src(3.14.6)
Python: 3.14.6
numpy: 2.4.6
scipy: 1.18.1
polars: 2.1.0
statsmodels: 0.14.6
matplotlib: 3.11.2
matplotlib-fontja: 1.1.0
ipython: 9.18.1
1. Compare reasons for choice numerically
The chapter opens with an online service losing market share. Suggested explanations include high prices, poor usability, and low awareness. To choose what to improve first, we need to examine how each condition relates to choice.
Reasons reported in a post-purchase survey may differ from actual choices. A choice experiment instead asks people to select one option from alternatives with different attributes, allowing us to estimate attribute weights. Showing choice probabilities after a price or performance change, as well as coefficients, makes the actions easier to compare.
2. Derive choice probabilities from utility
2.1 Separate observed attributes from unobserved factors
Let $U_{ij}$ be the utility consumer $i$ receives from product $j$. We split it into $V_{ij}$, calculated from observed attributes, and an unobserved term $\varepsilon_{ij}$. We omit the choice-task index for now.
show_math(r"""\(
U_{ij}=V_{ij}+\varepsilon_{ij},\qquad
V_{ij}=\alpha_j+\sum_{k=1}^{K}\beta_k x_{ijk}
\)""")
$$ U_{ij}=V_{ij}+\varepsilon_{ij},\qquad V_{ij}=\alpha_j+\sum_{k=1}^{K}\beta_k x_{ijk} $$
Here $\alpha_j$ is a product-specific constant and $\beta_k$ is the weight per unit of attribute $k$. We assume the consumer chooses the product with the highest utility. Because the errors are unobserved, we express choice as a probability. The basic model uses common coefficients for all respondents.
2.2 From Gumbel errors to multinomial logit
Assume the errors are independent standard Gumbel variables. Their cumulative distribution function $F$ and its derivative, the density $f$, are as follows.
show_math(r"""\(
F(s)=e^{-e^{-s}},\qquad
f(s)=\frac{dF(s)}{ds}=e^{-s}e^{-e^{-s}}
\)""")
$$ F(s)=e^{-e^{-s}},\qquad f(s)=\frac{dF(s)}{ds}=e^{-s}e^{-e^{-s}} $$
s = np.linspace(-3, 6, 400)
fig, axes = plt.subplots(1, 2, figsize=(10, 3.2), layout="constrained")
for ax, values, title, label in zip(
axes, [gumbel_r.pdf(s), gumbel_r.cdf(s)],
["標準ガンベル分布の密度", "標準ガンベル分布の累積確率"],
["密度", "累積確率"],
):
ax.plot(s, values, color=colors[0])
ax.set(xlabel="誤差 s", ylabel=label, title=title)
ax.grid(alpha=0.200)
save_svg(fig, "01_gumbel.svg")
Fix $\varepsilon_{ij}=s$. For every other product $k$, we can multiply the probabilities that $\varepsilon_{ik}<s+V_{ij}-V_{ik}$, then integrate over $s$.
show_math(r"""\(
\begin{aligned}
P_{ij}
&=P(U_{ij}>U_{ik},\ \forall k\ne j)\\
&=\int_{-\infty}^{\infty}f(s)
\prod_{k\ne j}F(s+V_{ij}-V_{ik})\,ds\\
&=\int_{-\infty}^{\infty}e^{-s}
\exp\!\left[-e^{-s}\left(1+\sum_{k\ne j}e^{V_{ik}-V_{ij}}\right)\right]ds.
\end{aligned}
\)""")
$$ \begin{aligned} P_{ij} &=P(U_{ij}>U_{ik},\ \forall k\ne j)\\ &=\int_{-\infty}^{\infty}f(s) \prod_{k\ne j}F(s+V_{ij}-V_{ik})\,ds\\ &=\int_{-\infty}^{\infty}e^{-s} \exp\!\left[-e^{-s}\left(1+\sum_{k\ne j}e^{V_{ik}-V_{ij}}\right)\right]ds. \end{aligned} $$
Set $C=1+\sum_{k\ne j}e^{V_{ik}-V_{ij}}$. With $u=e^{-s}$, we have $ds=-du/u$, and the integration limits change from $s:-\infty\to\infty$ to $u:\infty\to0$.
show_math(r"""\(
\begin{aligned}
P_{ij}
&=\int_{\infty}^{0}u e^{-Cu}\left(-\frac{du}{u}\right)
=\int_{0}^{\infty}e^{-Cu}\,du\\
&=\left[-\frac{e^{-Cu}}{C}\right]_{0}^{\infty}
=\frac{1}{C}\\
&=\frac{1}{\sum_{k=1}^{J}e^{V_{ik}-V_{ij}}}
=\frac{e^{V_{ij}}}{\sum_{k=1}^{J}e^{V_{ik}}}.
\end{aligned}
\)""")
$$ \begin{aligned} P_{ij} &=\int_{\infty}^{0}u e^{-Cu}\left(-\frac{du}{u}\right) =\int_{0}^{\infty}e^{-Cu}\,du\\ &=\left[-\frac{e^{-Cu}}{C}\right]_{0}^{\infty} =\frac{1}{C}\\ &=\frac{1}{\sum_{k=1}^{J}e^{V_{ik}-V_{ij}}} =\frac{e^{V_{ij}}}{\sum_{k=1}^{J}e^{V_{ik}}}. \end{aligned} $$
This is the multinomial logit (MNL) probability formula. The common denominator makes the probabilities sum to 1. However, the ratio of two products’ probabilities does not depend on the other alternatives. This property is called independence of irrelevant alternatives (IIA).
show_math(r"""\(
\frac{P_{iA}}{P_{iB}}
=\frac{e^{V_{iA}}/\sum_k e^{V_{ik}}}{e^{V_{iB}}/\sum_k e^{V_{ik}}}
=e^{V_{iA}-V_{iB}}
\)""")
$$ \frac{P_{iA}}{P_{iB}} =\frac{e^{V_{iA}}/\sum_k e^{V_{ik}}}{e^{V_{iB}}/\sum_k e^{V_{ik}}} =e^{V_{iA}-V_{iB}} $$
The figure starts with equal utilities for a car and a red bus. Adding a blue bus with the same utility gives each alternative probability one-third under MNL. The basic model does not represent the special similarity between the two buses.
fig, axes = plt.subplots(1, 2, figsize=(10, 3.2), layout="constrained")
for ax, labels, title in zip(
axes, [["自家用車", "赤バス"], ["自家用車", "赤バス", "青バス"]],
["追加前:効用は同じ", "青バスを追加:効用は同じ"],
):
probabilities = softmax(np.zeros(len(labels)))
bars = ax.bar(labels, 100 * probabilities, color=colors[:len(labels)])
ax.bar_label(bars, labels=[f"{sig3(100 * p)}%" for p in probabilities])
ax.set(ylabel="選択確率(%)", ylim=(0, 65), title=title)
save_svg(fig, "02_iia.svg")
2.3 Coefficient units and willingness to pay
We measure price in units of ¥10,000 and battery life in hours. Brand A is the reference, with indicator variables for brands B and C. Because each brand corresponds to one product, these coefficients also include product-specific differences.
show_math(r"""\(
V_{ij}=\beta_p p_{ij}+\beta_h h_{ij}
+\beta_B d_{ijB}+\beta_C d_{ijC}
\)""")
$$ V_{ij}=\beta_p p_{ij}+\beta_h h_{ij} +\beta_B d_{ijB}+\beta_C d_{ijC} $$
Absolute coefficients with different units cannot be compared directly as measures of importance. We obtain willingness to pay (WTP) from the condition that a performance improvement and a price increase offset each other.
show_math(r"""\(
\begin{aligned}
\Delta V&=\beta_p\Delta p+\beta_h\Delta h=0\\
\beta_p\Delta p&=-\beta_h\Delta h\\
\mathrm{WTP}_h=\frac{\Delta p}{\Delta h}
&=-\frac{\beta_h}{\beta_p}.
\end{aligned}
\)""")
$$ \begin{aligned} \Delta V&=\beta_p\Delta p+\beta_h\Delta h=0\\ \beta_p\Delta p&=-\beta_h\Delta h\\ \mathrm{WTP}_h=\frac{\Delta p}{\Delta h} &=-\frac{\beta_h}{\beta_p}. \end{aligned} $$
The unit is ¥10,000 per hour. WTP is not an observed payment; it is the price difference that balances utility under the model.
2.4 Binary logit and probit
With two options, probabilities depend only on the utility difference $z=V_1-V_0$. Dividing the numerator and denominator by $e^{V_1}$ gives the sigmoid function.
show_math(r"""\(
\begin{aligned}
p&=\frac{e^{V_1}}{e^{V_1}+e^{V_0}}
=\frac{1}{1+e^{V_0-V_1}}
=\frac{1}{1+e^{-z}}\\
1-p&=\frac{e^{-z}}{1+e^{-z}},\qquad
\frac{p}{1-p}=e^z,\qquad \log\frac{p}{1-p}=z.
\end{aligned}
\)""")
$$ \begin{aligned} p&=\frac{e^{V_1}}{e^{V_1}+e^{V_0}} =\frac{1}{1+e^{V_0-V_1}} =\frac{1}{1+e^{-z}}\\ 1-p&=\frac{e^{-z}}{1+e^{-z}},\qquad \frac{p}{1-p}=e^z,\qquad \log\frac{p}{1-p}=z. \end{aligned} $$
Equal utilities give $p=0.500$. Probit instead uses normal errors. If the two errors are independent with variance $\sigma^2$, their difference has variance $2\sigma^2$.
show_math(r"""\(
P_1=\Phi\!\left(\frac{V_1-V_0}{\sqrt{2}\sigma}\right),\qquad
\Phi(z)=\int_{-\infty}^{z}\frac{e^{-s^2/2}}{\sqrt{2\pi}}\,ds
\)""")
$$ P_1=\Phi\!\left(\frac{V_1-V_0}{\sqrt{2}\sigma}\right),\qquad \Phi(z)=\int_{-\infty}^{z}\frac{e^{-s^2/2}}{\sqrt{2\pi}}\,ds $$
The right panel uses the logistic standard deviation $\pi/\sqrt{3}$ to rescale both distributions to variance 1. The curves are close but not identical. Multinomial probit can represent correlations between errors, but generally requires numerical integration to calculate probabilities.
z = np.linspace(-4, 4, 400)
fig, axes = plt.subplots(1, 2, figsize=(10, 3.4), layout="constrained")
axes[0].plot(z, expit(z), color=colors[0])
axes[0].scatter([0], [0.500], color=colors[1], zorder=3)
axes[0].set(xlabel="効用差 z", ylabel="選択確率", title="二項ロジット")
# 分散1に標準化したロジスティック分布のCDFと標準正規CDFを比較する。
axes[1].plot(z, expit(np.pi * z / np.sqrt(3)), label="ロジット(分散1)")
axes[1].plot(z, norm.cdf(z), "--", label="プロビット(分散1)")
axes[1].set(xlabel="標準化した値", ylabel="累積確率", title="分布の幅をそろえた比較")
axes[1].legend()
for ax in axes:
ax.grid(alpha=0.200)
save_svg(fig, "03_logit_probit.svg")
3. Estimate the model and interpret the results in Python
3.1 Create choice data
As in the chapter, we simulate 500 people, eight tasks each, and three products per task. Each row represents one product in one task; only the selected product has chosen=1. The random seed and generation procedure follow the source notebook. The price coefficient is $-0.0000280$ per yen, and the battery-life coefficient is $0.120$.
rng = np.random.default_rng(42)
n_respondents, n_tasks = 500, 8
products = ["A", "B", "C"]
price_levels = {"A": [69800, 79800, 89800], "B": [59800, 69800, 79800],
"C": [79800, 89800, 99800]}
hours_levels = {"A": [9, 12, 15], "B": [9, 12], "C": [12, 15, 18]}
brand_premium = {"A": 0, "B": -0.300, "C": 0.500}
records = []
for respondent in range(n_respondents):
for task in range(n_tasks):
attributes, utilities = {}, {}
for product in products:
price = int(rng.choice(price_levels[product]))
hours = int(rng.choice(hours_levels[product]))
v = -0.0000280 * price + 0.120 * hours + brand_premium[product]
utilities[product] = v + rng.gumbel()
attributes[product] = (price, hours)
chosen = max(utilities, key=utilities.get)
for product in products:
price, hours = attributes[product]
records.append((respondent, task, product, int(product == chosen),
price, hours))
df = pl.DataFrame(records, orient="row", schema=[
"respondent_id", "choice_set_id", "brand", "chosen", "price_yen", "battery_hours"
])
# 各課題に3製品、選択1件があることと、欠損・重複がないことを確認する。
check = df.group_by("respondent_id", "choice_set_id").agg(
pl.len().alias("rows"), pl.col("brand").n_unique().alias("brands"),
pl.col("chosen").sum().alias("selected"),
)
assert df.null_count().to_numpy().sum() == 0
assert check.filter((pl.col("rows") != 3) | (pl.col("brands") != 3)
| (pl.col("selected") != 1)).is_empty()
print(f"{n_respondents}人 × {n_tasks}課題 × 3製品 = {df.height:,}行")
print(df.head(6))
observed_share = np.array([
df.filter(pl.col("brand") == product)["chosen"].mean() for product in products
])
fig, ax = plt.subplots(figsize=(6.5, 3.3), layout="constrained")
bars = ax.bar(products, observed_share * 100, color=colors)
ax.bar_label(bars, labels=[f"{sig3(p * 100)}%" for p in observed_share])
ax.set(xlabel="製品", ylabel="選ばれた割合(%)", ylim=(0, 65), title="模擬データの選択割合")
save_svg(fig, "04_observed_choices.svg")
500人 × 8課題 × 3製品 = 12,000行
shape: (6, 6)
┌───────────────┬───────────────┬───────┬────────┬───────────┬───────────────┐
│ respondent_id ┆ choice_set_id ┆ brand ┆ chosen ┆ price_yen ┆ battery_hours │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str ┆ i64 ┆ i64 ┆ i64 │
╞═══════════════╪═══════════════╪═══════╪════════╪═══════════╪═══════════════╡
│ 0 ┆ 0 ┆ A ┆ 1 ┆ 69800 ┆ 15 │
│ 0 ┆ 0 ┆ B ┆ 0 ┆ 69800 ┆ 12 │
│ 0 ┆ 0 ┆ C ┆ 0 ┆ 79800 ┆ 12 │
│ 0 ┆ 1 ┆ A ┆ 0 ┆ 89800 ┆ 15 │
│ 0 ┆ 1 ┆ B ┆ 1 ┆ 69800 ┆ 9 │
│ 0 ┆ 1 ┆ C ┆ 0 ┆ 89800 ┆ 15 │
└───────────────┴───────────────┴───────┴────────┴───────────┴───────────────┘
The observed shares reflect differences in price and performance as well as brand. They should not be read as brand effects alone.
3.2 Estimate coefficients by maximum likelihood
Task numbers repeat across respondents, so we combine them with respondent IDs to create unique task identifiers. Price is converted to units of ¥10,000. A common intercept would not change the probabilities, so we do not include one.
Let $y_{ijt}$ indicate the choice. We maximize the likelihood $L$, the product of the chosen alternatives’ probabilities. Taking logarithms turns the product into the sum used for optimization.
show_math(r"""\(
\begin{aligned}
L&=\prod_{i,t,j}P_{ijt}^{y_{ijt}},\qquad
\ell=\log L=\sum_{i,t,j}y_{ijt}\log P_{ijt}\\
\log P_{ijt}&=V_{ijt}-\log\sum_k e^{V_{ikt}}\\
\widehat{\mathbf{b}}&=\underset{\mathbf{b}}{\operatorname{argmax}}\;
\sum_{i,t,j}y_{ijt}\left(V_{ijt}-\log\sum_k e^{V_{ikt}}\right),\qquad
V_{ijt}=\mathbf{x}_{ijt}^{\mathsf T}\mathbf{b}.
\end{aligned}
\)""")
$$ \begin{aligned} L&=\prod_{i,t,j}P_{ijt}^{y_{ijt}},\qquad \ell=\log L=\sum_{i,t,j}y_{ijt}\log P_{ijt}\\ \log P_{ijt}&=V_{ijt}-\log\sum_k e^{V_{ikt}}\\ \widehat{\mathbf{b}}&=\underset{\mathbf{b}}{\operatorname{argmax}}\; \sum_{i,t,j}y_{ijt}\left(V_{ijt}-\log\sum_k e^{V_{ikt}}\right),\qquad V_{ijt}=\mathbf{x}_{ijt}^{\mathsf T}\mathbf{b}. \end{aligned} $$
Here $\mathbf{x}_{ijt}$ is the four-attribute vector and $\mathbf{b}$ the coefficient vector. Passing task IDs to ConditionalLogit fits an MNL model in which one alternative is chosen per task.
df_model = df.with_columns(
(pl.col("respondent_id") * n_tasks + pl.col("choice_set_id")).alias("task_id"),
(pl.col("price_yen") / 10000).alias("price_man"),
(pl.col("brand") == "B").cast(pl.Int8).alias("brand_B"),
(pl.col("brand") == "C").cast(pl.Int8).alias("brand_C"),
).sort("task_id", "brand")
features = ["price_man", "battery_hours", "brand_B", "brand_C"]
X = df_model.select(features).to_numpy()
y = df_model["chosen"].to_numpy()
groups = df_model["task_id"].to_numpy()
model = ConditionalLogit(y, X, groups=groups)
result = model.fit(disp=False, maxiter=200)
beta = np.asarray(result.params)
ci = np.asarray(result.conf_int())
true_beta = np.array([-0.280, 0.120, -0.300, 0.500])
print("属性、設定した係数、推定係数、95%信頼区間")
pprint([(name, sig3(truth), sig3(value), tuple(sig3(v) for v in interval))
for name, truth, value, interval in zip(features, true_beta, beta, ci)],
width=100)
属性、設定した係数、推定係数、95%信頼区間
[('price_man', '-0.280', '-0.312', ('-0.362', '-0.262')),
('battery_hours', '0.120', '0.138', ('0.120', '0.157')),
('brand_B', '-0.300', '-0.374', ('-0.481', '-0.268')),
('brand_C', '0.500', '0.459', ('0.356', '0.563'))]
3.3 Check odds ratios and uncertainty
The estimated price coefficient is $-0.312$, and the battery-life coefficient is $0.138$. Increasing one attribute of one product by one unit changes its odds relative to a comparison product by the following factor.
show_math(r"""\(
\mathrm{OR}_k
=\frac{P'_j/P'_m}{P_j/P_m}
=\frac{e^{V_j+\beta_k-V_m}}{e^{V_j-V_m}}
=e^{\beta_k}
\)""")
$$ \mathrm{OR}_k =\frac{P’_j/P’_m}{P_j/P_m} =\frac{e^{V_j+\beta_k-V_m}}{e^{V_j-V_m}} =e^{\beta_k} $$
odds = np.exp(beta)
odds_ci = np.exp(ci)
labels = ["価格 +1万円", "駆動時間 +1時間", "ブランドB(対A)", "ブランドC(対A)"]
print("属性、オッズ比、95%信頼区間、p値")
pprint([(name, sig3(value), tuple(sig3(v) for v in interval), sig3(p))
for name, value, interval, p in zip(features, odds, odds_ci, result.pvalues)],
width=100)
fig, ax = plt.subplots(figsize=(8, 3.5), layout="constrained")
ax.errorbar(odds, np.arange(4),
xerr=np.vstack([odds - odds_ci[:, 0], odds_ci[:, 1] - odds]),
fmt="o", capsize=4, color=colors[0], label="推定値と95%信頼区間")
ax.axvline(1, linestyle="--", color="gray")
ax.set(yticks=np.arange(4), yticklabels=labels, xlabel="相対オッズの倍率",
title="オッズ比の推定結果")
ax.invert_yaxis()
ax.legend(loc="lower right")
save_svg(fig, "05_odds_ratios.svg")
属性、オッズ比、95%信頼区間、p値
[('price_man', '0.732', ('0.696', '0.770'), '3.87e-34'),
('battery_hours', '1.15', ('1.13', '1.17'), '2.72e-49'),
('brand_B', '0.688', ('0.618', '0.765'), '6.11e-12'),
('brand_C', '1.58', ('1.43', '1.76'), '2.95e-18')]
The battery-life odds ratio is $1.15$. This does not mean that the probability itself rises by 15%. The confidence intervals assume independent tasks in the simulated data. For repeated responses in real data, assess uncertainty with methods such as respondent-level bootstrap resampling.
3.4 Calculate WTP
Battery-life WTP is about $0.444$ units of ¥10,000 per hour. To obtain an interval, we apply the delta method using the coefficient covariance matrix $\mathbf{S}$. Differentiate the coefficient ratio with respect to each coefficient and collect the derivatives in vector $\mathbf{g}$.
show_math(r"""\(
\begin{aligned}
w_k&=-\frac{\beta_k}{\beta_p},\qquad
\frac{\partial w_k}{\partial\beta_p}=\frac{\beta_k}{\beta_p^2},\qquad
\frac{\partial w_k}{\partial\beta_k}=-\frac{1}{\beta_p}\\
\mathrm{SE}(\hat w_k)&\approx\sqrt{\mathbf{g}^{\mathsf T}\mathbf{S}\mathbf{g}},\qquad
\mathrm{CI}_{95\%}\approx\hat w_k\pm1.96\,\mathrm{SE}(\hat w_k).
\end{aligned}
\)""")
$$ \begin{aligned} w_k&=-\frac{\beta_k}{\beta_p},\qquad \frac{\partial w_k}{\partial\beta_p}=\frac{\beta_k}{\beta_p^2},\qquad \frac{\partial w_k}{\partial\beta_k}=-\frac{1}{\beta_p}\\ \mathrm{SE}(\hat w_k)&\approx\sqrt{\mathbf{g}^{\mathsf T}\mathbf{S}\mathbf{g}},\qquad \mathrm{CI}_{95\%}\approx\hat w_k\pm1.96\,\mathrm{SE}(\hat w_k). \end{aligned} $$
# 価格係数の区間が0を含む場合、単純な係数比の解釈は控える。
assert ci[0, 1] < 0, "価格係数を確認してからWTPを解釈する"
covariance = np.asarray(result.cov_params())
wtp, wtp_lower, wtp_upper = [], [], []
for k in [1, 2, 3]:
value = -beta[k] / beta[0]
gradient = np.zeros(4)
gradient[0] = beta[k] / beta[0] ** 2
gradient[k] = -1 / beta[0]
se = np.sqrt(gradient @ covariance @ gradient)
wtp.append(value)
wtp_lower.append(value - 1.96 * se)
wtp_upper.append(value + 1.96 * se)
wtp, wtp_lower, wtp_upper = map(np.asarray, [wtp, wtp_lower, wtp_upper])
print("属性、WTP、95%信頼区間(万円:駆動時間は1時間当たり)")
pprint([(name, sig3(value), (sig3(lo), sig3(hi)))
for name, value, lo, hi in zip(features[1:], wtp, wtp_lower, wtp_upper)])
show_math(r"\(\widehat{\mathrm{WTP}}_h=-\frac{\hat\beta_h}{\hat\beta_p}\approx "
+ sig3(wtp[0]) + r"\;\text{万円/時間}\)")
fig, ax = plt.subplots(figsize=(8, 3.5), layout="constrained")
ax.errorbar(wtp, np.arange(3), xerr=np.vstack([wtp - wtp_lower, wtp_upper - wtp]),
fmt="o", capsize=4, color=colors[2])
ax.axvline(0, color="gray", linestyle="--")
ax.set(yticks=np.arange(3), yticklabels=labels[1:], xlabel="WTP(万円)",
title="属性の価値を価格差へ換算:推定値と95%信頼区間")
ax.invert_yaxis()
save_svg(fig, "06_wtp.svg")
属性、WTP、95%信頼区間(万円:駆動時間は1時間当たり)
[('battery_hours', '0.444', ('0.354', '0.534')),
('brand_B', '-1.20', ('-1.50', '-0.898')),
('brand_C', '1.47', ('1.18', '1.77'))]
$$ \widehat{\mathrm{WTP}}_h=-\frac{\hat\beta_h}{\hat\beta_p}\approx 0.444\;\text{万円/時間} $$
This ratio becomes unstable when the price coefficient is close to zero. Brand WTP in this example also includes product-specific differences.
3.5 Compare a price cut with longer battery life
Fix B at ¥69,800 and 12 hours, and C at ¥89,800 and 15 hours. Starting from A at ¥79,800 and 12 hours, change only its price or only its battery life and recalculate the probabilities.
def choice_prob(profiles):
# softmaxは最大効用を引いて計算し、指数関数の桁あふれを防ぐ。
return softmax(np.asarray(profiles) @ beta)
base = np.array([[7.98, 12, 0, 0], [6.98, 12, 1, 0], [8.98, 15, 0, 1]])
price_down, battery_up = base.copy(), base.copy()
price_down[0, 0] = 6.98
battery_up[0, 1] = 15
scenario_names = ["変更前", "1万円の値下げ", "3時間の延長"]
probabilities = np.vstack([choice_prob(p) for p in [base, price_down, battery_up]])
assert np.allclose(probabilities.sum(axis=1), 1)
print("条件、Aの選択確率(%)、変更前との差(ポイント)")
pprint([(name, sig3(100 * p[0]), sig3(100 * (p[0] - probabilities[0, 0])))
for name, p in zip(scenario_names, probabilities)])
fig, ax = plt.subplots(figsize=(8, 3.6), layout="constrained")
positions = np.arange(3)
for j, product in enumerate(products):
bars = ax.bar(positions + (j - 1) * 0.250, probabilities[:, j] * 100,
width=0.230, label=product, color=colors[j])
ax.bar_label(bars, labels=[sig3(100 * p) for p in probabilities[:, j]], fontsize=9)
ax.set(xticks=positions, xticklabels=scenario_names, ylabel="選択確率(%)",
ylim=(0, 60), title="Aの条件だけを変えたときの3製品の選択確率")
ax.legend(title="製品", ncol=3)
save_svg(fig, "07_scenarios.svg")
# 候補範囲内で、価格と駆動時間をそれぞれ連続的に変える。
fig, axes = plt.subplots(1, 2, figsize=(10, 3.6), layout="constrained")
for ax, column, values, xlabel in zip(
axes, [0, 1], [np.linspace(6.98, 8.98, 100), np.linspace(9, 15, 100)],
["Aの価格(万円):駆動時間12時間", "Aの駆動時間(時間):価格7.98万円"],
):
curve = []
for value in values:
profiles = base.copy()
profiles[0, column] = value
curve.append(choice_prob(profiles)[0])
ax.plot(values, 100 * np.asarray(curve), color=colors[0])
ax.scatter([base[0, column]], [100 * probabilities[0, 0]],
color=colors[1], label="変更前", zorder=3)
ax.set(xlabel=xlabel, ylabel="Aの選択確率(%)", ylim=(15, 45))
ax.legend()
ax.grid(alpha=0.200)
fig.suptitle("他の条件を固定したときのAの選ばれやすさ")
save_svg(fig, "08_sensitivity.svg")
条件、Aの選択確率(%)、変更前との差(ポイント)
[('変更前', '27.1', '0.00'),
('1万円の値下げ', '33.6', '6.57'),
('3時間の延長', '36.0', '8.91')]
A’s choice probability rises from 27.1% to 33.6% with the price cut and to 36.0% with longer battery life. Under these conditions, the three-hour improvement gives the larger increase. However, these are calculations conditional on choosing one of A, B, and C, not market-wide purchase probabilities or sales volumes. Development costs, lost margin from the price cut, and implementation time also matter.
Conclusion
This article introduced a procedure for estimating attribute weights with a logit choice model and comparing actions using WTP and choice probabilities.
The model provides comparisons under its assumptions and the presented alternatives. After narrowing down the actions, use a small sales test to check purchases and profit.
Chapter 4 of Marketing Science in Theory and Practice also covers choice-experiment design, coefficient interpretation, and model limitations. The detailed implementation is available on the book’s support page .