Environment

Python 3.14.6, NumPy 2.4.6, pandas 2.3.3, PyMC 6.2.0, ArviZ 1.3.0, Matplotlib 3.11.2.

Overview

The same discount may encourage one customer to buy while having little effect on another. Common coefficients alone cannot reflect this difference in marketing actions. This article introduces Chapter 6, “Capturing Consumer Heterogeneity,” of Marketing Science in Theory and Practice . We cover limited individual data, hierarchical structures and shrinkage, and implementation with PyMC.

Setup code (imports and display settings)
import platform
from importlib.metadata import version
from pathlib import Path
from pprint import pprint

import arviz as az
import matplotlib.pyplot as plt
import matplotlib_fontja  # 日本語フォントを設定する
import numpy as np
import pandas as pd
import pymc as pm
from IPython.display import Math, SVG, display
from matplotlib.ticker import FuncFormatter, MaxNLocator
from scipy.special import expit

print(f"Python {platform.python_version()} / {platform.system()}")
for package in ["numpy", "scipy", "pandas", "matplotlib", "matplotlib-fontja", "pymc", "arviz"]:
    print(f"{package}: {version(package)}")

# 数値は有効数字3桁で表示する。整数表示の末尾の小数点は除く。
def fmt3(value):
    return f"{value:#.3g}".removesuffix(".")


np.set_printoptions(formatter={"float_kind": fmt3})
pd.options.display.float_format = fmt3
plt.rcParams.update({"font.size": 11, "axes.spines.top": False, "axes.spines.right": False})
OUT = Path("06_nb_files")
OUT.mkdir(exist_ok=True)
BLUE, ORANGE = "#28658a", "#b85a2b"


def save_svg(fig, name):
    """軸の表示を整え、SVGを保存してノートブック内にも表示する。"""
    def tick(value, position):
        return str(int(value)) if value == int(value) else f"{value:#.3g}"

    for ax in fig.axes:
        if ax.get_xscale() == "linear":
            ax.xaxis.set_major_formatter(FuncFormatter(tick))
        if ax.get_yscale() == "linear":
            ax.yaxis.set_major_formatter(FuncFormatter(tick))
        ax.grid(alpha=0.200)
    fig.tight_layout()
    path = OUT / f"{name}.svg"
    fig.savefig(path, format="svg", bbox_inches="tight")
    plt.close(fig)
    display(SVG(filename=str(path)))
Python 3.14.6 / Darwin
numpy: 2.4.6
scipy: 1.18.1
pandas: 2.3.3
matplotlib: 3.11.2
matplotlib-fontja: 1.1.0
pymc: 6.2.0
arviz: 1.3.0

1. What do common coefficients miss?

The book begins with a uniform discount whose results fell below predictions from a common-coefficient model. Customers with strong and weak price responses were mixed together. A fully pooled model with price as its only explanatory variable expresses purchase probability as follows.

$$ q_{it}=\sigma(\beta_0+\beta x_{it}),\qquad \sigma(z)=\frac{1}{1+e^{-z}}. $$

Here $i$ denotes a consumer and $t$ a purchase opportunity. The coefficient describes a change in log-odds, not in probability. In the book’s example with price measured in yen, a coefficient of $-0.0310$ and an initial purchase probability of $0.500$ give the following probability after a ¥10 discount.

$$ \begin{aligned} \log\frac{0.500}{1-0.500}&=0,\\ \Delta z&=(-0.0310)(-10)=0.310,\\ q_{\mathrm{after}}&=\frac{1}{1+e^{-0.310}}\approx0.577. \end{aligned} $$

Differences in responses between consumers are called heterogeneity. They may arise from observed attributes or unobserved preferences. However, estimating everyone separately makes coefficients unstable for people with little history. Check individual coefficients and their uncertainty intervals as well as the average response.

2. Hierarchical structure and shrinkage

A hierarchical Bayesian model performs partial pooling: it estimates individual coefficients while sharing a population distribution across consumers. Let $a_i$ be the intercept and $b_i$ the price coefficient. The book’s three-level structure is summarized below.

$$ \begin{aligned} \mu_a,\mu_b&\sim\mathcal N(0,1),& \tau_a,\tau_b&\sim\mathrm{HalfNormal}(1),\\ a_i&\sim\mathcal N(\mu_a,\tau_a^2),& b_i&\sim\mathcal N(\mu_b,\tau_b^2),\\ y_{it}&\sim\mathrm{Bernoulli}(q_{it}),& q_{it}&=\sigma(a_i+b_i x_{it}). \end{aligned} $$

Other consumers’ observations also update the population distribution, and that information affects each person’s coefficient. We do not model a correlation between intercept and price coefficient here. The second argument of the normal distributions above is a variance, whereas PyMC’s sigma is a standard deviation. Because a standard deviation cannot be negative, we use a half-normal prior for it.

Follow the shrinkage calculation

To see the mechanism, use a simpler continuous-outcome model. Here $y_{it}$ is not a binary purchase indicator; it is an observation on the same scale as $b_i$. Assume $\mu,\sigma^2,\tau^2$ are known.

$$ y_{it}\mid b_i\sim\mathcal N(b_i,\sigma^2),\quad b_i\sim\mathcal N(\mu,\tau^2),\quad \bar y_i=\frac{1}{n_i}\sum_t y_{it}. $$

Multiply the likelihood by the prior and collect terms unrelated to $b_i$ into a constant. Use $\sum_t(y_{it}-\bar y_i)=0$ to decompose the sum of squares, then complete the square.

$$ \begin{aligned} \sum_t(y_{it}-b_i)^2 &=\sum_t(y_{it}-\bar y_i)^2+n_i(b_i-\bar y_i)^2,\\ p(b_i\mid\mathbf{y}_i) &\propto\exp\left[-\frac12\left\{ \frac{n_i}{\sigma^2}(b_i-\bar y_i)^2+ \frac{1}{\tau^2}(b_i-\mu)^2\right\}\right],\\ A&=\frac{n_i}{\sigma^2}+\frac{1}{\tau^2},\qquad B=\frac{n_i\bar y_i}{\sigma^2}+\frac{\mu}{\tau^2},\\ Ab_i^2-2Bb_i+C&=A\left(b_i-\frac BA\right)^2+C-\frac{B^2}{A}. \end{aligned} $$

The term $C=n_i\bar y_i^2/\sigma^2+\mu^2/\tau^2$ does not depend on $b_i$. The posterior is therefore normal with mean $B/A$ and variance $1/A$.

$$ \begin{aligned} E[b_i\mid\mathbf{y}_i] &=\frac{n_i\bar y_i/\sigma^2+\mu/\tau^2}{n_i/\sigma^2+1/\tau^2}\\ &=w_i\bar y_i+(1-w_i)\mu,\qquad w_i=\frac{n_i}{n_i+\sigma^2/\tau^2}. \end{aligned} $$

Fewer observations give more weight to the population mean. As in the book, set $\sigma^2/\tau^2=20$ and substitute five observations, an individual estimate of $-0.300$, and a population mean of $-0.0500$. The next figure illustrates this auxiliary model; it is not an exact solution for logistic regression.

# 本文の補助モデル:重みと縮小後の値を数値で確認する。
mu, individual = -0.0500, -0.300
n_grid = np.arange(1, 201)
weight = n_grid / (n_grid + 20)
shrunk = weight * individual + (1 - weight) * mu
display(Math(r"w=\frac{5}{5+20}=0.200,\qquad "
             r"E[b\mid\mathbf{y}]=0.200(-0.300)+0.800(-0.0500)=-0.100"))

fig, axes = plt.subplots(1, 2, figsize=(10, 3.6))
axes[0].plot(n_grid, weight, color=BLUE)
axes[0].set(xlabel="観測数", ylabel="本人のデータへの重み", ylim=(0, 1))
axes[1].plot(n_grid, shrunk, color=BLUE, label="縮小後")
axes[1].axhline(individual, color=ORANGE, ls="--", label="個別推定値")
axes[1].axhline(mu, color="gray", ls=":", label="母集団平均")
axes[1].scatter([5], [-0.100], color=BLUE)
axes[1].set(xlabel="観測数", ylabel="係数")
axes[1].legend(fontsize=9)
save_svg(fig, "01_shrinkage")

$\displaystyle w=\frac{5}{5+20}=0.200,\qquad E[b\mid\mathbf{y}]=0.200(-0.300)+0.800(-0.0500)=-0.100$

MCMC and posterior prediction

For hierarchical logistic regression, the posterior is difficult to obtain analytically, so we use MCMC. The book starts with the Metropolis–Hastings method, which probabilistically accepts or rejects proposals, while the implementation uses NUTS.

From the samples, we calculate posterior means and 94% highest density intervals (HDIs). An HDI contains 94% probability while favoring regions of higher density. A central 94% interval instead removes 3% from each tail. The methods differ, but the intervals coincide for symmetric, unimodal distributions such as a normal distribution. Calculating purchase probabilities for each parameter sample and then generating binary outcomes gives posterior predictive samples. These reflect both parameter uncertainty and variability in purchases.

$$ q_{it}^{(s)}=\sigma(a_i^{(s)}+b_i^{(s)}x_{it}),\qquad y_{it}^{\mathrm{rep},(s)}\sim\mathrm{Bernoulli}(q_{it}^{(s)}). $$

Here $s$ is the sample index. Use the intercept and slope from the same sample.

3. Estimate individual price coefficients in Python

Prepare the data

Using the book’s random settings, we generate 100 people with 3–29 purchase opportunities each. The population price coefficient has mean $-0.800$ and standard deviation $0.300$. Each row is one opportunity, including occasions without a purchase. These are simulated data, not observed point-of-sale records.

We transform price to $x=(\mathrm{price\_yen}-200)/50$. The coefficient represents a change in log-odds for a ¥50 increase, unlike the per-yen coefficient in the opening example. We retain string IDs and map them to consecutive integers for computation.

rng = np.random.default_rng(42)
n_customer = 100
n_obs = rng.integers(3, 30, size=n_customer)
b_true = rng.normal(-0.800, 0.300, n_customer)
a_true = rng.normal(0, 0.500, n_customer)

# 計算中は丸めず、購入と非購入の両方を記録する。
records = []
for i, n in enumerate(n_obs):
    price = rng.uniform(100, 300, n)
    scaled = (price - 200) / 50
    bought = rng.binomial(1, expit(a_true[i] + b_true[i] * scaled))
    for yen, x_value, y_value in zip(price, scaled, bought):
        records.append({
            "occasion_id": f"O{len(records) + 1:05d}",
            "customer_id": f"C{i + 1:03d}",
            "price_yen": yen, "price_scaled": x_value, "purchased": int(y_value),
        })
df = pd.DataFrame(records)
labels, idx = np.unique(df["customer_id"], return_inverse=True)
idx = idx.astype("int32")
x = df["price_scaled"].to_numpy()
y = df["purchased"].to_numpy()
print(f"消費者数: {len(labels)}、購入機会: {len(df)}")
print(df.head().to_string(index=False))
pprint(dict(zip(labels[:3].tolist(), range(3))))

fig, axes = plt.subplots(1, 2, figsize=(10, 3.6))
axes[0].hist(n_obs, bins=np.arange(2.5, 30.5, 3), color=BLUE, edgecolor="white")
axes[0].set(xlabel="1人当たりの観測数", ylabel="人数")
axes[0].yaxis.set_major_locator(MaxNLocator(integer=True))
price_grid = np.linspace(100, 300, 160)
x_grid = (price_grid - 200) / 50
for i in [0, 24, 49, 74, 99]:
    axes[1].plot(price_grid, expit(a_true[i] + b_true[i] * x_grid), label=labels[i])
axes[1].set(xlabel="価格(円)", ylabel="生成時の購入確率", ylim=(0, 1))
axes[1].legend(fontsize=8)
save_svg(fig, "02_data")
消費者数: 100、購入機会: 1675
occasion_id customer_id  price_yen  price_scaled  purchased
     O00001        C001        121         -1.58          1
     O00002        C001        113         -1.73          1
     O00003        C001        219         0.378          0
     O00004        C001        129         -1.42          1
     O00005        C001        265          1.30          0
{'C001': 0, 'C002': 1, 'C003': 2}

Define fully pooled and hierarchical models

First create a model with common coefficients. For the hierarchical model, use a non-centered parameterization: draw $z_i\sim\mathcal N(0,1)$ and construct $b_i=\mu_b+\tau_b z_i$. Apply the same approach to the intercepts. The array idx selects the coefficient belonging to the consumer in each row.

coords = {"customer": labels.tolist(), "obs": np.arange(len(df))}
with pm.Model(coords={"obs": coords["obs"]}) as pooled_model:
    a = pm.Normal("a", mu=0, sigma=1)
    b = pm.Normal("b", mu=0, sigma=1)
    pm.Bernoulli("y_obs", logit_p=a + b * x, observed=y, dims="obs")

with pm.Model(coords=coords) as hierarchical_model:
    # 母集団 → 個人別係数 → 購入結果の順に定義する。
    mu_a = pm.Normal("mu_a", mu=0, sigma=1)
    tau_a = pm.HalfNormal("tau_a", sigma=1)
    mu_b = pm.Normal("mu_b", mu=0, sigma=1)
    tau_b = pm.HalfNormal("tau_b", sigma=1)
    z_a = pm.Normal("z_a", mu=0, sigma=1, dims="customer")
    z_b = pm.Normal("z_b", mu=0, sigma=1, dims="customer")
    a_i = pm.Deterministic("a_i", mu_a + tau_a * z_a, dims="customer")
    b_i = pm.Deterministic("b_i", mu_b + tau_b * z_b, dims="customer")
    q = pm.Deterministic("q", pm.math.sigmoid(a_i[idx] + b_i[idx] * x), dims="obs")
    pm.Bernoulli("y_obs", p=q, observed=y, dims="obs")

Check the purchase probabilities allowed by the priors

Before fitting, sample the population and individual coefficients from their priors. The band is a central 94% interval for purchase probability. The priors allow curves in which purchase probability increases with price. Check whether this is consistent with the business assumptions before fitting.

# 1人の消費者の係数を、母集団の事前分布も含めて繰り返し生成する。
prior_rng = np.random.default_rng(2026)
size = 500
prior_mu_a = prior_rng.normal(0, 1, size)
prior_tau_a = np.abs(prior_rng.normal(0, 1, size))
prior_mu_b = prior_rng.normal(0, 1, size)
prior_tau_b = np.abs(prior_rng.normal(0, 1, size))
prior_a = prior_rng.normal(prior_mu_a, prior_tau_a)
prior_b = prior_rng.normal(prior_mu_b, prior_tau_b)
prior_q = expit(prior_a[:, None] + prior_b[:, None] * x_grid)
low, high = np.quantile(prior_q, [0.0300, 0.970], axis=0)

fig, ax = plt.subplots(figsize=(7.5, 3.6))
ax.fill_between(price_grid, low, high, color=BLUE, alpha=0.150, label="中央94%区間")
ax.plot(price_grid, prior_q[:25].T, color=BLUE, alpha=0.200, lw=0.800)
ax.plot(price_grid, np.median(prior_q, axis=0), color=ORANGE, label="中央値")
ax.set(xlabel="価格(円)", ylabel="事前分布から生成した購入確率", ylim=(0, 1))
ax.legend(fontsize=9)
save_svg(fig, "03_prior")

Run MCMC and check fit to the training data

As in the book, run four chains with 1,000 tuning iterations and retain 2,000 samples per chain. Posterior prediction regenerates outcomes for the same purchase opportunities, allowing us to compare purchase rates by price band. This checks reproduction of the training data, not accuracy on an unseen period.

with hierarchical_model:
    trace = pm.sample(
        draws=2000, tune=1000, chains=4, cores=2,
        target_accept=0.950, random_seed=42, progressbar=False,
        return_inferencedata=True,
    )

with hierarchical_model:
    predictive = pm.sample_posterior_predictive(
        trace, var_names=["y_obs"], random_seed=42, progressbar=False,
    )
Initializing NUTS using jitter+adapt_diag...


Multiprocess sampling (4 chains in 2 jobs)


NUTS: [mu_a, tau_a, mu_b, tau_b, z_a, z_b]


Sampling 4 chains for 1_000 tune and 2_000 draw iterations (4_000 + 8_000 draws total) took 18 seconds.


Sampling: [y_obs]
def samples(result, variable, dimension, group="posterior"):
    """チェーンと反復をまとめ、行をサンプル、列を対象にそろえる。"""
    return (result[group][variable].stack(sample=("chain", "draw"))
            .transpose("sample", dimension).values)


def hdi_columns(values):
    return np.array([az.hdi(column, prob=0.940) for column in values.T])


q_draws = samples(trace, "q", "obs")
y_rep = samples(predictive, "y_obs", "obs", "posterior_predictive")
selected = [np.flatnonzero(idx == i)[0] for i in [0, 24, 49, 74, 99]]
prediction_table = df.iloc[selected][["customer_id", "price_yen", "purchased"]].copy()
prediction_table["購入確率の平均"] = q_draws[:, selected].mean(axis=0)
prediction_table["再生成した購入率"] = y_rep[:, selected].mean(axis=0)
print(prediction_table.to_string(index=False))

# 同じ価格帯の購入機会をまとめ、購入率の事後予測分布を作る。
edges = np.linspace(100, 300, 9)
bins = np.digitize(df["price_yen"], edges[1:-1])
centers = (edges[:-1] + edges[1:]) / 2
observed = np.array([y[bins == b].mean() for b in range(8)])
rep_rates = np.column_stack([y_rep[:, bins == b].mean(axis=1) for b in range(8)])
interval = hdi_columns(rep_rates)
fig, ax = plt.subplots(figsize=(7.5, 3.6))
ax.fill_between(centers, interval[:, 0], interval[:, 1], color=BLUE, alpha=0.200,
                label="生成した購入率の94% HDI")
ax.plot(centers, rep_rates.mean(axis=0), color=BLUE, label="予測平均")
ax.scatter(centers, observed, color=ORANGE, label="実測購入率", zorder=3)
ax.set(xlabel="価格帯の中心(円)", ylabel="購入率", ylim=(0, 1))
ax.legend(fontsize=9)
save_svg(fig, "04_posterior_predictive")
customer_id  price_yen  purchased  購入確率の平均  再生成した購入率
       C001        121          1    0.783     0.783
       C025        295          0    0.180     0.184
       C050        172          0    0.551     0.554
       C075        261          0    0.182     0.183
       C100        300          0    0.210     0.220

Check sampling stability

$\hat R$ measures agreement across chains, while effective sample size (ESS) describes how much information the correlated samples contain. Check auxiliary variables as well as primary parameters, and inspect divergences, the energy diagnostic BFMI, and trace plots. Traces of population means alone cannot establish stability for every variable.

diagnostic_vars = ["mu_a", "tau_a", "mu_b", "tau_b", "z_a", "z_b", "a_i", "b_i"]
diagnostics = az.summary(trace, var_names=diagnostic_vars, kind="diagnostics", round_to="none")
max_rhat = float(diagnostics["r_hat"].max())
min_bulk = float(diagnostics["ess_bulk"].min())
min_tail = float(diagnostics["ess_tail"].min())
divergences = int(trace.sample_stats["diverging"].sum().item())
energy = trace.sample_stats["energy"].values
bfmi = np.mean(np.diff(energy, axis=1) ** 2, axis=1) / np.var(energy, axis=1)
pprint({"最大R_hat": f"{max_rhat:#.3g}", "最小ESS_bulk": f"{min_bulk:#.3g}",
        "最小ESS_tail": f"{min_tail:#.3g}", "発散数": divergences})
pprint(bfmi)
# 判定には表示用に丸める前の値を使う。
stable = max_rhat < 1.01 and min_bulk > 400 and min_tail > 400 and divergences == 0 and bfmi.min() > 0.300
print(f"数値診断の目安を満たす: {stable}")
tau_draws = trace.posterior["tau_b"].values.ravel()
tau_low, tau_high = az.hdi(tau_draws, prob=0.940)
pprint({"価格係数の母集団標準偏差": fmt3(tau_draws.mean()),
        "94% HDI": [fmt3(tau_low), fmt3(tau_high)]})

fig, axes = plt.subplots(2, 2, figsize=(10, 5.6))
for row, variable in enumerate(["mu_b", "tau_b"]):
    chain_values = trace.posterior[variable].values
    for chain, values in enumerate(chain_values):
        axes[row, 0].hist(values, bins=30, density=True, histtype="step", label=f"chain {chain + 1}")
        axes[row, 1].plot(values, lw=0.500, alpha=0.650)
    axes[row, 0].set(xlabel=variable, ylabel="密度")
    axes[row, 1].set(xlabel="調整後の反復", ylabel=variable)
axes[0, 0].legend(fontsize=8)
save_svg(fig, "05_trace")
{'最大R_hat': '1.00',
 '最小ESS_bulk': '2.36e+03',
 '最小ESS_tail': '3.07e+03',
 '発散数': 0}
array([0.702, 0.704, 0.691, 0.733])
数値診断の目安を満たす: True
{'94% HDI': ['0.000392', '0.340'], '価格係数の母集団標準偏差': '0.190'}

Use individual estimates to consider possible actions

This run has no divergences and meets the numerical diagnostic guidelines. However, the population standard deviation still has a wide uncertainty interval. Stable sampling and precise estimation are different things.

We report posterior means and 94% HDIs. Comparison with true values is possible because the data are simulated. Even many observations may not narrow an interval if prices barely vary. Requiring an HDI upper bound below $-0.500$ is only an example for selecting test candidates. Actual criteria should account for profit and cost.

b_draws = samples(trace, "b_i", "customer")
b_mean = b_draws.mean(axis=0)
b_hdi = hdi_columns(b_draws)
candidate = b_hdi[:, 1] < -0.500
customer_table = pd.DataFrame({
    "消費者ID": labels, "観測数": n_obs, "事後平均": b_mean,
    "HDI下限": b_hdi[:, 0], "HDI上限": b_hdi[:, 1], "検証候補": candidate,
})
print(customer_table.sort_values("事後平均").head(8).to_string(index=False))
print(f"例示基準を満たす人数: {int(candidate.sum())} / {n_customer}")

fig, axes = plt.subplots(1, 2, figsize=(10, 3.8))
axes[0].vlines(b_true, b_hdi[:, 0], b_hdi[:, 1], color=BLUE, alpha=0.250)
axes[0].scatter(b_true, b_mean, color=BLUE, s=12)
limits = [min(b_true.min(), b_hdi.min()), max(b_true.max(), b_hdi.max())]
axes[0].plot(limits, limits, "--", color="gray", label="推定値=真値")
axes[0].set(xlabel="生成時の真の価格係数", ylabel="事後平均と94% HDI")
axes[0].legend(fontsize=8)
axes[1].scatter(n_obs, b_hdi[:, 1] - b_hdi[:, 0], color=BLUE, s=20)
axes[1].set(xlabel="観測数", ylabel="94% HDIの幅")
save_svg(fig, "06_individual")
消費者ID  観測数   事後平均  HDI下限  HDI上限  検証候補
 C017   16 -0.926  -1.40 -0.571  True
 C062   23 -0.905  -1.33 -0.527  True
 C015   22 -0.903  -1.33 -0.530  True
 C038   25 -0.899  -1.36 -0.569  True
 C059   23 -0.896  -1.34 -0.542  True
 C013   22 -0.894  -1.31 -0.551  True
 C028   25 -0.892  -1.31 -0.547  True
 C094   13 -0.888  -1.36 -0.538  True
例示基準を満たす人数: 19 / 100

Compare population estimates

Finally, compare the fully pooled common coefficient with the hierarchical population mean. They estimate different quantities; the common coefficient need not equal the arithmetic mean of individual coefficients. This figure alone does not establish which model predicts better.

with pooled_model:
    pooled_trace = pm.sample(
        draws=2000, tune=1000, chains=4, cores=2,
        target_accept=0.950, random_seed=42, progressbar=False,
        return_inferencedata=True,
    )

# 比較モデルについても数値診断を出力する。
pooled_diagnostics = az.summary(pooled_trace, var_names=["a", "b"], kind="diagnostics", round_to="none")
print(pooled_diagnostics.to_string())
print(f"完全プール型の発散数: {int(pooled_trace.sample_stats['diverging'].sum().item())}")
fig, ax = plt.subplots(figsize=(7.5, 3.6))
rows = []
for name, draws in [
    ("完全プール型の共通係数", pooled_trace.posterior["b"].values.ravel()),
    ("階層モデルの母集団平均", trace.posterior["mu_b"].values.ravel()),
]:
    low, high = az.hdi(draws, prob=0.940)
    rows.append({"推定対象": name, "平均": draws.mean(), "HDI下限": low, "HDI上限": high})
    ax.hist(draws, bins=40, density=True, histtype="step", lw=2, label=name)
ax.axvline(-0.800, color="gray", ls="--", label="母集団平均の設定値")
ax.set(xlabel="価格係数(50円当たり)", ylabel="事後密度")
ax.legend(fontsize=9)
print(pd.DataFrame(rows).to_string(index=False))
save_svg(fig, "07_comparison")
Initializing NUTS using jitter+adapt_diag...


Multiprocess sampling (4 chains in 2 jobs)


NUTS: [a, b]


Sampling 4 chains for 1_000 tune and 2_000 draw iterations (4_000 + 8_000 draws total) took 3 seconds.


   ess_bulk  ess_tail  r_hat  mcse_mean  mcse_sd
a  5.14e+03  4.49e+03   1.00   0.000732 0.000598
b  5.35e+03  4.65e+03   1.00   0.000677 0.000589
完全プール型の発散数: 0
       推定対象     平均  HDI下限  HDI上限
完全プール型の共通係数 -0.749 -0.840 -0.654
階層モデルの母集団平均 -0.793 -0.900 -0.683

Conclusion

This article introduced hierarchical Bayesian estimation of individual price coefficients and their uncertainty by sharing information across consumers.

The posterior means in this run are $-0.749$ for the common coefficient and $-0.793$ for the population mean. Individual intervals remain wide, and 19 of the 100 consumers meet the illustrative selection criterion.

Shrinkage stabilizes estimates for people with little history, but it does not remove the lack of information. Use both coefficient rankings and uncertainty intervals to choose test candidates. Associations with observed prices do not establish the causal effect of discounts. Randomly split candidates into comparison groups and evaluate incremental profit as well as purchase rates.

Marketing Science in Theory and Practice connects these business questions, theory, implementation, and decisions. Chapter 6 and the implementation on the support page provide further guidance for applying the model to your own data.