Environment

Python 3.14.6, NumPy 2.4.6, SciPy 1.18.1, Matplotlib 3.11.2.

Overview

Chapter 5, “Modeling Consumer-Goods Purchases,” of Marketing Science in Theory and Practice represents purchase counts and brand choices with probability distributions. This article follows the chapter through loyalty measures, the derivation of the negative binomial distribution (NBD), its combination with a Dirichlet distribution, and estimation and comparison in Python.

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

import matplotlib.pyplot as plt
from matplotlib import font_manager
from matplotlib.ticker import FuncFormatter, MaxNLocator, ScalarFormatter
import numpy as np
from scipy import optimize, special, stats
from IPython.display import Latex, display

# ノートブックのフォルダー、またはリポジトリ直下から実行する。
base = Path.cwd()
if (base / "blog/05/05_nb.ipynb").exists():
    base = base / "blog/05"
FIG_DIR = base / "05_nb_files"
FIG_DIR.mkdir(exist_ok=True)


def sig3(value):
    """末尾のゼロを残して有効数字3桁にする。整数の回数は整数で扱う。"""
    return format(float(value), "#.3g").removesuffix(".")


def show_math(tex):
    r"""重要式の \( ... \) を、表示用の $$ ... $$ に変換する。"""
    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 = FIG_DIR / filename
    fig.savefig(path, format="svg", bbox_inches="tight")
    # SVGに対応しないビューアー向けのPNGは、ファイルにせず出力だけに含める。
    preview = BytesIO()
    fig.savefig(preview, format="png", dpi=120, bbox_inches="tight")
    plt.close(fig)
    display({"image/svg+xml": path.read_text(encoding="utf-8"),
             "image/png": b64encode(preview.getvalue()).decode("ascii")}, raw=True)


np.set_printoptions(formatter={"float_kind": sig3})
fonts = {font.name for font in font_manager.fontManager.ttflist}
for candidate in ("Hiragino Sans", "Noto Sans CJK JP", "IPAexGothic", "Yu Gothic"):
    if candidate in fonts:
        plt.rcParams["font.family"] = candidate
        break
plt.rcParams.update({"font.size": 11, "axes.unicode_minus": False,
                     "svg.fonttype": "path", "svg.hashsalt": "blog05"})
COLORS = ["#3274A1", "#D58B27", "#419578"]

print("仮想環境:wa-src(3.14.6)")
print(f"Python:{platform.python_version()} / OS:{platform.system()}")
for package in ("numpy", "scipy", "matplotlib", "ipython"):
    print(f"{package}:{version(package)}")
仮想環境:wa-src(3.14.6)
Python:3.14.6 / OS:Darwin
numpy:2.4.6
scipy:1.18.1
matplotlib:3.11.2
ipython:9.18.1

1. How should we read loyalty measures?

The chapter begins with a practical goal: increasing repeat purchasing. In its example, loyal customers’ average monthly purchases rose from 3.10 to 3.30, while total brand sales barely changed. Some company details and figures were altered, and without a comparison group the action’s effect cannot be determined.

Brands with smaller market shares tend to have both lower period penetration—the proportion buying at least once—and slightly fewer purchases per buyer. This pattern is called double jeopardy. A lower average count than a competitor does not by itself show weaker customer attachment. First examine the number of buyers and the purchases per buyer separately.

2. Model purchase counts with the NBD

Individual purchases and differences between people

Let $X$ be a person’s purchase count over a fixed period and $\mu$ their expected count. We assume purchases occur independently at a constant rate within each person and use a Poisson distribution. A common $\mu$ for everyone would not capture differences between infrequent and frequent buyers, so we let $\mu$ follow a gamma distribution. Here $r$ is the shape and $\lambda$ the rate; the scale is $1/\lambda$.

show_math(r"""\(
\begin{aligned}
X\mid\mu&\sim\operatorname{Poisson}(\mu), &
P(X=x\mid\mu)&=\frac{e^{-\mu}\mu^x}{x!},\quad x=0,1,\ldots,\\
\mathbb{E}[X\mid\mu]&=\mu, & \operatorname{Var}(X\mid\mu)&=\mu,\\
\mu&\sim\operatorname{Gamma}(r,\lambda), &
f(\mu)&=\frac{\lambda^r}{\Gamma(r)}\mu^{r-1}e^{-\lambda\mu},\quad\mu>0,\\
\mathbb{E}[\mu]&=\frac r\lambda, & \operatorname{Var}(\mu)&=\frac r{\lambda^2}.
\end{aligned}
\)""")

$$ \begin{aligned} X\mid\mu&\sim\operatorname{Poisson}(\mu), & P(X=x\mid\mu)&=\frac{e^{-\mu}\mu^x}{x!},\quad x=0,1,\ldots,\\ \mathbb{E}[X\mid\mu]&=\mu, & \operatorname{Var}(X\mid\mu)&=\mu,\\ \mu&\sim\operatorname{Gamma}(r,\lambda), & f(\mu)&=\frac{\lambda^r}{\Gamma(r)}\mu^{r-1}e^{-\lambda\mu},\quad\mu>0,\\ \mathbb{E}[\mu]&=\frac r\lambda, & \operatorname{Var}(\mu)&=\frac r{\lambda^2}. \end{aligned} $$

Integrate over unobserved expected purchase counts

For each $\mu$, weight the purchase probability by the probability density of $\mu$ and integrate. Combine the exponential and power terms, substitute $t=(1+\lambda)\mu$, and use the gamma-function definition to obtain the NBD.

show_math(r"""\(
\begin{aligned}
P(X=x)
&=\int_0^\infty P(X=x\mid\mu)f(\mu)\,d\mu\\
&=\int_0^\infty\frac{e^{-\mu}\mu^x}{x!}
  \frac{\lambda^r\mu^{r-1}e^{-\lambda\mu}}{\Gamma(r)}\,d\mu\\
&=\frac{\lambda^r}{\Gamma(r)x!}
  \int_0^\infty\mu^{x+r-1}e^{-(1+\lambda)\mu}\,d\mu.\\
t&=(1+\lambda)\mu,\quad\mu=\frac{t}{1+\lambda},\quad
d\mu=\frac{dt}{1+\lambda},\\
P(X=x)
&=\frac{\lambda^r}{\Gamma(r)x!}
  \int_0^\infty\left(\frac{t}{1+\lambda}\right)^{x+r-1}
  e^{-t}\frac{dt}{1+\lambda}\\
&=\frac{\lambda^r}{\Gamma(r)x!(1+\lambda)^{x+r}}
  \underbrace{\int_0^\infty t^{x+r-1}e^{-t}\,dt}_{\Gamma(x+r)}\\
&=\frac{\Gamma(x+r)}{\Gamma(r)x!}
  \left(\frac{\lambda}{1+\lambda}\right)^r
  \left(\frac{1}{1+\lambda}\right)^x.
\end{aligned}
\)""")

$$ \begin{aligned} P(X=x) &=\int_0^\infty P(X=x\mid\mu)f(\mu)\,d\mu\\ &=\int_0^\infty\frac{e^{-\mu}\mu^x}{x!} \frac{\lambda^r\mu^{r-1}e^{-\lambda\mu}}{\Gamma(r)}\,d\mu\\ &=\frac{\lambda^r}{\Gamma(r)x!} \int_0^\infty\mu^{x+r-1}e^{-(1+\lambda)\mu}\,d\mu.\\ t&=(1+\lambda)\mu,\quad\mu=\frac{t}{1+\lambda},\quad d\mu=\frac{dt}{1+\lambda},\\ P(X=x) &=\frac{\lambda^r}{\Gamma(r)x!} \int_0^\infty\left(\frac{t}{1+\lambda}\right)^{x+r-1} e^{-t}\frac{dt}{1+\lambda}\\ &=\frac{\lambda^r}{\Gamma(r)x!(1+\lambda)^{x+r}} \underbrace{\int_0^\infty t^{x+r-1}e^{-t}\,dt}_{\Gamma(x+r)}\\ &=\frac{\Gamma(x+r)}{\Gamma(r)x!} \left(\frac{\lambda}{1+\lambda}\right)^r \left(\frac{1}{1+\lambda}\right)^x. \end{aligned} $$

Express the model in terms of mean, variance, and penetration

Following the book’s implementation, set $M=r/\lambda$ and $K=r$. The mean $M$ includes people with zero purchases. Total variance is the mean of within-person variances plus the variance of individual means. At fixed $M$, smaller $K$ implies greater variation.

show_math(r"""\(
\begin{aligned}
\lambda&=K/M,\quad
\frac{\lambda}{1+\lambda}=\frac{K}{K+M},\quad
\frac{1}{1+\lambda}=\frac{M}{K+M},\\
P(X=x\mid M,K)&=\frac{\Gamma(x+K)}{\Gamma(K)x!}
\left(\frac K{K+M}\right)^K\left(\frac M{K+M}\right)^x,\\
\mathbb{E}[X]&=\mathbb{E}[\mathbb{E}[X\mid\mu]]
=\mathbb{E}[\mu]=r/\lambda=M,\\
\operatorname{Var}(X)&=\mathbb{E}[\operatorname{Var}(X\mid\mu)]
+\operatorname{Var}(\mathbb{E}[X\mid\mu])\\
&=\mathbb{E}[\mu]+\operatorname{Var}(\mu)
=\frac r\lambda+\frac r{\lambda^2}=M+\frac{M^2}{K}.
\end{aligned}
\)""")

show_math(r"""\(
\begin{aligned}
P(X=0)&=\frac{\Gamma(K)}{\Gamma(K)\,0!}
\left(\frac K{K+M}\right)^K\left(\frac M{K+M}\right)^0
=\left(\frac K{K+M}\right)^K,\\
b&=P(X\geq1)=1-P(X=0),\\
w&=\mathbb{E}[X\mid X\geq1]
=\sum_{x=1}^\infty x\frac{P(X=x)}b
=\frac{\mathbb{E}[X]}b=\frac Mb,\qquad M=bw.
\end{aligned}
\)""")

$$ \begin{aligned} \lambda&=K/M,\quad \frac{\lambda}{1+\lambda}=\frac{K}{K+M},\quad \frac{1}{1+\lambda}=\frac{M}{K+M},\\ P(X=x\mid M,K)&=\frac{\Gamma(x+K)}{\Gamma(K)x!} \left(\frac K{K+M}\right)^K\left(\frac M{K+M}\right)^x,\\ \mathbb{E}[X]&=\mathbb{E}[\mathbb{E}[X\mid\mu]] =\mathbb{E}[\mu]=r/\lambda=M,\\ \operatorname{Var}(X)&=\mathbb{E}[\operatorname{Var}(X\mid\mu)] +\operatorname{Var}(\mathbb{E}[X\mid\mu])\\ &=\mathbb{E}[\mu]+\operatorname{Var}(\mu) =\frac r\lambda+\frac r{\lambda^2}=M+\frac{M^2}{K}. \end{aligned} $$

$$ \begin{aligned} P(X=0)&=\frac{\Gamma(K)}{\Gamma(K)\,0!} \left(\frac K{K+M}\right)^K\left(\frac M{K+M}\right)^0 =\left(\frac K{K+M}\right)^K,\\ b&=P(X\geq1)=1-P(X=0),\\ w&=\mathbb{E}[X\mid X\geq1] =\sum_{x=1}^\infty x\frac{P(X=x)}b =\frac{\mathbb{E}[X]}b=\frac Mb,\qquad M=bw. \end{aligned} $$

Here $b$ is category penetration during the period, and $w$ is mean purchase count among category buyers. The NBD calculates both from one distribution. It assumes stable purchase rates, so check fit when the period contains strong seasonality or changes in customers’ circumstances.

3. Which brand does a customer choose?

Combine Dirichlet and multinomial distributions

Let $N_i$ be category purchase count and $\mathbf{X}_i$ the brand-count vector. We use a Dirichlet distribution for the choice-probability vector $\mathbf{p}_i$, with parameter vector $\mathbf{a}=(\alpha_1,\ldots,\alpha_J)$. Expected category purchases $\mu_i$ and $\mathbf{p}_i$ are assumed independent.

show_math(r"""\(
\begin{aligned}
\mu_i&\sim\operatorname{Gamma}(K,K/M),\quad
N_i\mid\mu_i\sim\operatorname{Poisson}(\mu_i),\\
\mathbf{p}_i&\sim\operatorname{Dirichlet}(\mathbf{a}),\quad
\alpha_0=\sum_{j=1}^J\alpha_j,\quad\sum_jp_{ij}=1,\\
f(\mathbf{p}_i\mid\mathbf{a})
&=\frac{\Gamma(\alpha_0)}{\prod_j\Gamma(\alpha_j)}
\prod_jp_{ij}^{\alpha_j-1},\\
\mathbf{X}_i\mid N_i=n,\mathbf{p}_i&\sim\operatorname{Multinomial}(n,\mathbf{p}_i),\\
P(\mathbf{X}_i=\mathbf{x}_i\mid n,\mathbf{p}_i)
&=\frac{n!}{\prod_jx_{ij}!}\prod_jp_{ij}^{x_{ij}},\quad\sum_jx_{ij}=n,\\
s_j&=\mathbb{E}[p_{ij}]=\frac{\alpha_j}{\alpha_0},\qquad
\operatorname{Var}(p_{ij})=\frac{s_j(1-s_j)}{\alpha_0+1},\\
M_j&=\mathbb{E}[X_{ij}]=\mathbb{E}[\mu_ip_{ij}]
=\mathbb{E}[\mu_i]\mathbb{E}[p_{ij}]=Ms_j.
\end{aligned}
\)""")

$$ \begin{aligned} \mu_i&\sim\operatorname{Gamma}(K,K/M),\quad N_i\mid\mu_i\sim\operatorname{Poisson}(\mu_i),\\ \mathbf{p}_i&\sim\operatorname{Dirichlet}(\mathbf{a}),\quad \alpha_0=\sum_{j=1}^J\alpha_j,\quad\sum_jp_{ij}=1,\\ f(\mathbf{p}_i\mid\mathbf{a}) &=\frac{\Gamma(\alpha_0)}{\prod_j\Gamma(\alpha_j)} \prod_jp_{ij}^{\alpha_j-1},\\ \mathbf{X}_i\mid N_i=n,\mathbf{p}_i&\sim\operatorname{Multinomial}(n,\mathbf{p}_i),\\ P(\mathbf{X}_i=\mathbf{x}_i\mid n,\mathbf{p}_i) &=\frac{n!}{\prod_jx_{ij}!}\prod_jp_{ij}^{x_{ij}},\quad\sum_jx_{ij}=n,\\ s_j&=\mathbb{E}[p_{ij}]=\frac{\alpha_j}{\alpha_0},\qquad \operatorname{Var}(p_{ij})=\frac{s_j(1-s_j)}{\alpha_0+1},\\ M_j&=\mathbb{E}[X_{ij}]=\mathbb{E}[\mu_ip_{ij}] =\mathbb{E}[\mu_i]\mathbb{E}[p_{ij}]=Ms_j. \end{aligned} $$

Here $s_j$ is market share measured by purchase counts. At the same shares, a smaller $\alpha_0$ gives more uneven individual choice probabilities. The book also derives the joint brand-count distribution as the product of the NBD and the Dirichlet-multinomial distribution obtained by integrating out choice probabilities.

Start from the probability of never buying a brand

Fix the choice probability of brand $j$ at $p$. The probability of not choosing it in any of $n$ purchases is $(1-p)^n$. Average this first over the Poisson distribution, then the gamma distribution, and finally the beta distribution of $p$.

show_math(r"""\(
\begin{aligned}
P(X_{ij}=0\mid\mu,p)
&=\sum_{n=0}^\infty(1-p)^n\frac{e^{-\mu}\mu^n}{n!}
=e^{-\mu}e^{\mu(1-p)}=e^{-\mu p},\\
P(X_{ij}=0\mid p)
&=\frac{(K/M)^K}{\Gamma(K)}
\int_0^\infty\mu^{K-1}e^{-(K/M+p)\mu}\,d\mu\\
&=\frac{(K/M)^K}{\Gamma(K)}\frac{\Gamma(K)}{(K/M+p)^K}
=\left(\frac K{K+Mp}\right)^K.
\end{aligned}
\)""")

show_math(r"""\(
\begin{aligned}
p_{ij}&\sim\operatorname{Beta}(\alpha_j,\alpha_0-\alpha_j),\qquad
B(a,b)=\frac{\Gamma(a)\Gamma(b)}{\Gamma(a+b)},\\
P(X_{ij}=0)
&=\frac{\displaystyle\int_0^1(1+Mp/K)^{-K}
p^{\alpha_j-1}(1-p)^{\alpha_0-\alpha_j-1}\,dp}
{B(\alpha_j,\alpha_0-\alpha_j)}\\
&={}_2F_1\!\left(K,\alpha_j;\alpha_0;-M/K\right),\\
b_j&=1-P(X_{ij}=0),\qquad w_j=\frac{M_j}{b_j}=\frac{Ms_j}{b_j}.
\end{aligned}
\)""")

$$ \begin{aligned} P(X_{ij}=0\mid\mu,p) &=\sum_{n=0}^\infty(1-p)^n\frac{e^{-\mu}\mu^n}{n!} =e^{-\mu}e^{\mu(1-p)}=e^{-\mu p},\\ P(X_{ij}=0\mid p) &=\frac{(K/M)^K}{\Gamma(K)} \int_0^\infty\mu^{K-1}e^{-(K/M+p)\mu}\,d\mu\\ &=\frac{(K/M)^K}{\Gamma(K)}\frac{\Gamma(K)}{(K/M+p)^K} =\left(\frac K{K+Mp}\right)^K. \end{aligned} $$

$$ \begin{aligned} p_{ij}&\sim\operatorname{Beta}(\alpha_j,\alpha_0-\alpha_j),\qquad B(a,b)=\frac{\Gamma(a)\Gamma(b)}{\Gamma(a+b)},\\ P(X_{ij}=0) &=\frac{\displaystyle\int_0^1(1+Mp/K)^{-K} p^{\alpha_j-1}(1-p)^{\alpha_0-\alpha_j-1}\,dp} {B(\alpha_j,\alpha_0-\alpha_j)}\\ &={}_2F_1\!\left(K,\alpha_j;\alpha_0;-M/K\right),\\ b_j&=1-P(X_{ij}=0),\qquad w_j=\frac{M_j}{b_j}=\frac{Ms_j}{b_j}. \end{aligned} $$

The gamma integral uses the same substitution as above. The final beta integral is written using the Gaussian hypergeometric function $\!{}_2F_1$. With $M,K,\alpha_0$ fixed, a smaller share corresponds to both lower $b_j$ and lower $w_j$.

Buying only one brand during a finite observation period does not imply a choice probability of 1. For example, when $p=0.600$, the probability of choosing that brand on both of two purchases is $0.600^2=0.360$. Observed “100% loyalty” over a limited period differs from a preference that always selects the same brand.

4. Estimate the model and compare results in Python

Include people with zero purchases

In practice, left-join purchase counts to the customer master and retain eligible people with no purchases as zeros. Use the same observation period for everyone and count purchase occasions rather than quantities. If the data contain only members, members also form the penetration denominator.

As in the book, we simulate 500 people, one year, and three brands with random seed 42. We set $M=3.00$, $K=0.800$, $\alpha_0=10$, and mean shares of 50%, 30%, and 20%. NumPy’s gamma distribution takes the scale $M/K$, which is the reciprocal of the rate.

rng = np.random.default_rng(42)
M_true, K_true, alpha0 = 3.00, 0.800, 10
shares_true = np.array([0.500, 0.300, 0.200])
brands = ["A", "B", "C"]
n_people = 500

# 元ノートブックと同じ順番で乱数を生成する。
mu = rng.gamma(shape=K_true, scale=M_true / K_true, size=n_people)
x = rng.poisson(mu)
probabilities = rng.dirichlet(alpha0 * shares_true, size=n_people)
brand_counts = np.zeros((n_people, len(brands)), dtype=int)
for i, total in enumerate(x):
    # 0回の対象者も行を残す。1購買機会につき1ブランドを選ぶ設定。
    if total > 0:
        choices = rng.choice(len(brands), size=int(total), p=probabilities[i])
        brand_counts[i] = np.bincount(choices, minlength=len(brands))

pprint({"対象者数": n_people, "0回購買者数": int(np.sum(x == 0)),
        "平均回数": sig3(x.mean()), "不偏分散": sig3(x.var(ddof=1))})
print("先頭5人のブランド別購買回数(列:A、B、C)")
pprint(brand_counts[:5])

# 図1:生成に使った分布。同じ平均でも、NBDは0回と高頻度側が多い。
grid = np.linspace(0.0100, 15, 500)
counts_grid = np.arange(21)
fig, axes = plt.subplots(1, 2, figsize=(11, 4), layout="constrained")
axes[0].plot(grid, stats.gamma.pdf(grid, K_true, scale=M_true / K_true),
             color=COLORS[0])
axes[0].set(title="図1a 期待購買回数の個人差", xlabel="期待購買回数 μ", ylabel="確率密度")
axes[1].plot(counts_grid, stats.poisson.pmf(counts_grid, M_true), "o--",
             color=COLORS[1], label="ポアソン(全員の期待回数が同じ)")
axes[1].plot(counts_grid, stats.nbinom.pmf(counts_grid, K_true, K_true / (K_true + M_true)),
             "s-", color=COLORS[0], label="NBD(期待回数に個人差がある)")
axes[1].set(title="図1b 平均3.00回の分布を比較", xlabel="購買回数", ylabel="確率")
axes[1].xaxis.set_major_locator(MaxNLocator(integer=True))
axes[1].legend(fontsize=9)
save_svg(fig, "01_generating_distributions.svg")
{'0回購買者数': 145, '不偏分散': '13.1', '対象者数': 500, '平均回数': '2.82'}
先頭5人のブランド別購買回数(列:A、B、C)
array([[1, 7, 0],
       [1, 6, 0],
       [0, 0, 0],
       [3, 1, 0],
       [0, 0, 0]])
# 図2:0回の対象者を含む実測度数。ここでの実測は模擬データの集計を指す。
observed_counts = np.bincount(x)
x_values = np.arange(len(observed_counts))
fig, ax = plt.subplots(figsize=(10, 4), layout="constrained")
ax.bar(x_values, observed_counts, color=COLORS[0])
ax.set(title="図2 カテゴリの年間購買回数(模擬データ500人)",
       xlabel="購買回数", ylabel="人数")
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
save_svg(fig, "02_category_counts.svg")

# 図3:同じ12人について、潜在的な選択確率と観測された回数を並べる。
fig, axes = plt.subplots(1, 2, figsize=(10, 5), layout="constrained")
for ax, values, title, integer in (
    (axes[0], probabilities[:12], "図3a 生成した選択確率", False),
    (axes[1], brand_counts[:12], "図3b その人の購買回数", True),
):
    vmax = max(float(values.max()), 1)
    ax.imshow(values, cmap="Blues", vmin=0, vmax=vmax, aspect="auto")
    ax.set(xticks=range(3), xticklabels=brands,
           yticks=range(12), yticklabels=range(1, 13),
           xlabel="ブランド", ylabel="対象者ID", title=title)
    for (row, col), value in np.ndenumerate(values):
        label = str(int(value)) if integer else sig3(value)
        ax.text(col, row, label, ha="center", va="center", fontsize=9,
                color="white" if value > vmax * 0.550 else "black")
save_svg(fig, "03_individual_brand_choices.svg")

There are 145 people with zero purchases. The mean is 2.82 and the unbiased variance is 13.1, so variance exceeds the mean. The left panel of Figure 3 shows the probabilities used to generate the data, which are not directly observed in real data. The right panel includes people with no purchases and people buying only one brand.

Estimate M and K by maximum likelihood

Use sample mean $\bar{x}$ and unbiased variance $v$ to obtain initial values, then maximize the log-likelihood. The variance denominator differs from the usual method-of-moments version, but we follow the book in using it for initialization. We optimize $\log M$ and $\log K$ to keep the parameters positive.

show_math(r"""\(
\begin{aligned}
\bar{x}&=\frac1n\sum_i x_i,\qquad
v=\frac1{n-1}\sum_i(x_i-\bar{x})^2,\\
\widetilde{M}&=\bar{x},\quad
v=\bar{x}+\frac{\bar{x}^2}{\widetilde{K}}
\ \Rightarrow\ v-\bar{x}=\frac{\bar{x}^2}{\widetilde{K}}
\ \Rightarrow\ \widetilde{K}=\frac{\bar{x}^2}{v-\bar{x}},\\
\ell(M,K\mid\mathbf{x})&=\sum_i\log P(X=x_i\mid M,K)\\
&=\sum_i\left[\log\Gamma(x_i+K)-\log\Gamma(K)-\log\Gamma(x_i+1)\right.\\
&\hspace{3em}\left.+K\log\frac{K}{K+M}+x_i\log\frac{M}{K+M}\right].
\end{aligned}
\)""")

$$ \begin{aligned} \bar{x}&=\frac1n\sum_i x_i,\qquad v=\frac1{n-1}\sum_i(x_i-\bar{x})^2,\\ \widetilde{M}&=\bar{x},\quad v=\bar{x}+\frac{\bar{x}^2}{\widetilde{K}} \ \Rightarrow\ v-\bar{x}=\frac{\bar{x}^2}{\widetilde{K}} \ \Rightarrow\ \widetilde{K}=\frac{\bar{x}^2}{v-\bar{x}},\\ \ell(M,K\mid\mathbf{x})&=\sum_i\log P(X=x_i\mid M,K)\\ &=\sum_i\left[\log\Gamma(x_i+K)-\log\Gamma(K)-\log\Gamma(x_i+1)\right.\\ &\hspace{3em}\left.+K\log\frac{K}{K+M}+x_i\log\frac{M}{K+M}\right]. \end{aligned} $$

def nbd_logpmf(values, M, K):
    """大きな階乗を直接計算せず、対数ガンマ関数で確率を求める。"""
    return (special.gammaln(values + K) - special.gammaln(K)
            - special.gammaln(values + 1)
            + K * np.log(K / (K + M))
            + values * np.log(M / (K + M)))


def negative_loglik(log_parameters):
    M, K = np.exp(log_parameters)
    return -np.sum(nbd_logpmf(x, M, K))


mean, variance = x.mean(), x.var(ddof=1)
K_init = mean**2 / (variance - mean) if variance > mean else 1.00
result = optimize.minimize(
    negative_loglik, np.log([mean, max(K_init, 0.100)]),
    method="Nelder-Mead",
    options={"xatol": 1.00e-6, "fatol": 1.00e-6, "maxiter": 10000},
)
if not result.success:
    raise RuntimeError(f"最適化が収束しなかった:{result.message}")

M_hat, K_hat = np.exp(result.x)
pprint({"推定M": sig3(M_hat), "推定K": sig3(K_hat),
        "最適化成功": bool(result.success)})

fitted = np.exp(nbd_logpmf(x_values, M_hat, K_hat))
fig, ax = plt.subplots(figsize=(10, 4), layout="constrained")
ax.bar(x_values, observed_counts / n_people, color=COLORS[0], alpha=0.650,
       label="模擬データの実測割合")
ax.plot(x_values, fitted, "o-", color=COLORS[1], label="推定したNBD")
ax.set(title="図4 実測分布とNBDの比較", xlabel="購買回数", ylabel="割合")
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
ax.legend()
save_svg(fig, "04_nbd_fit.svg")
{'推定K': '0.833', '推定M': '2.82', '最適化成功': True}

The estimates are $\hat{M}=2.82$ and $\hat{K}=0.833$. They do not exactly match the generating values because this is one random sample of 500 people.

Test goodness of fit

Pool high-count categories with small expected frequencies, ending with “11 or more purchases.” Include probability beyond the largest observed count so that expected and observed totals agree. With $L$ categories, subtract the two estimated parameters when calculating degrees of freedom.

show_math(r"""\(
Q=\sum_{h=1}^L\frac{(O_h-E_h)^2}{E_h},\qquad
\nu=L-1-2,\qquad p_{\mathrm{test}}=P(\chi^2_\nu\geq Q).
\)""")

$$ Q=\sum_{h=1}^L\frac{(O_h-E_h)^2}{E_h},\qquad \nu=L-1-2,\qquad p_{\mathrm{test}}=P(\chi^2_\nu\geq Q). $$

success_prob = K_hat / (K_hat + M_hat)
expected = fitted * n_people
cutoff = int(x.max())
while cutoff > 1 and expected[cutoff] < 5:
    cutoff -= 1

obs_grouped = np.r_[observed_counts[:cutoff], observed_counts[cutoff:].sum()]
tail = stats.nbinom.sf(cutoff - 1, K_hat, success_prob) * n_people
exp_grouped = np.r_[expected[:cutoff], tail]
degrees = len(obs_grouped) - 1 - 2
if degrees <= 0 or np.any(exp_grouped < 5):
    raise ValueError("区間のまとめ方を見直す必要がある")

chi2_value = np.sum((obs_grouped - exp_grouped)**2 / exp_grouped)
p_value = stats.chi2.sf(chi2_value, degrees)
pprint({"最後の区間": f"{cutoff}回以上", "区間数": len(obs_grouped),
        "自由度": degrees, "カイ二乗統計量": sig3(chi2_value),
        "p値": sig3(p_value)})

# 各区間の差を期待人数の平方根で割り、偏りの位置を確認する。
residuals = (obs_grouped - exp_grouped) / np.sqrt(exp_grouped)
labels = [str(i) for i in range(cutoff)] + [f"{cutoff}以上"]
fig, ax = plt.subplots(figsize=(10, 4), layout="constrained")
ax.bar(labels, residuals, color=COLORS[0])
ax.axhline(0, color="#555555", linewidth=1)
ax.set(title="図5 区間ごとの標準化した差", xlabel="購買回数の区間",
       ylabel="(実測人数 − 期待人数)/ √期待人数")
save_svg(fig, "05_fit_residuals.svg")
{'p値': '0.650', 'カイ二乗統計量': '6.87', '区間数': 12, '最後の区間': '11回以上', '自由度': 9}

The statistic is 6.87 with 9 degrees of freedom and $p=0.650$. At the 5% level, we cannot reject the null hypothesis that purchase counts follow the NBD. This does not prove fit; the example uses data generated from an NBD. This p-value uses a chi-square approximation. Parameters are fitted to individual counts before grouping, and bins are merged based on the data. When an accurately calibrated significance level is needed, use a parametric bootstrap that repeats both fitting and bin merging.

Compare observed brand measures

The book’s implementation does not estimate Dirichlet parameters. It uses a simplified model with observed shares and common $\hat{K}$. Replacing individual choice probabilities with average shares makes it different from the Dirichlet-NBD model above. The theoretical values below are benchmarks from this simplified model.

show_math(r"""\(
\widehat{s}_j=\frac{\sum_i X_{ij}}{\sum_iN_i},\quad
\widehat{M}_j=\widehat{M}\widehat{s}_j,\quad
b_j^{\mathrm{simple}}=1-\left(\frac{\widehat{K}}
{\widehat{K}+\widehat{M}_j}\right)^{\widehat{K}},\quad
w_j^{\mathrm{simple}}=\frac{\widehat{M}_j}{b_j^{\mathrm{simple}}}.
\)""")

$$ \widehat{s}_j=\frac{\sum_i X_{ij}}{\sum_iN_i},\quad \widehat{M}_j=\widehat{M}\widehat{s}_j,\quad b_j^{\mathrm{simple}}=1-\left(\frac{\widehat{K}} {\widehat{K}+\widehat{M}_j}\right)^{\widehat{K}},\quad w_j^{\mathrm{simple}}=\frac{\widehat{M}_j}{b_j^{\mathrm{simple}}}. $$

shares = brand_counts.sum(axis=0) / x.sum()
brand_mean = M_hat * shares
b_simple = 1 - (K_hat / (K_hat + brand_mean))**K_hat
w_simple = brand_mean / b_simple
buyers = (brand_counts > 0).sum(axis=0)
b_observed = buyers / n_people
w_observed = brand_counts.sum(axis=0) / buyers

for j, brand in enumerate(brands):
    pprint({"ブランド": brand, "シェア(%)": sig3(100 * shares[j]),
            "浸透率:実測 / 簡略理論(%)": [sig3(100 * b_observed[j]),
                                               sig3(100 * b_simple[j])],
            "購買者当たり回数:実測 / 簡略理論": [sig3(w_observed[j]),
                                                 sig3(w_simple[j])]})

fig, axes = plt.subplots(1, 2, figsize=(11, 4), layout="constrained")
positions = np.arange(len(brands))
for ax, obs, theory, title, ylabel in (
    (axes[0], 100 * b_observed, 100 * b_simple, "図6a 期間浸透率", "対象者中の割合(%)"),
    (axes[1], w_observed, w_simple, "図6b 購買者当たりの平均回数", "回数(回/年)"),
):
    ax.bar(positions - 0.180, obs, width=0.360, color=COLORS[0], label="模擬データの実測値")
    ax.bar(positions + 0.180, theory, width=0.360, color=COLORS[1], label="簡略モデルの理論値")
    ax.set(xticks=positions, xticklabels=brands, xlabel="ブランド", ylabel=ylabel, title=title)
    ax.legend(fontsize=9)
save_svg(fig, "06_brand_comparison.svg")
{'シェア(%)': '51.0',
 'ブランド': 'A',
 '浸透率:実測 / 簡略理論(%)': ['54.6', '56.7'],
 '購買者当たり回数:実測 / 簡略理論': ['2.64', '2.54']}
{'シェア(%)': '29.0',
 'ブランド': 'B',
 '浸透率:実測 / 簡略理論(%)': ['43.0', '43.5'],
 '購買者当たり回数:実測 / 簡略理論': ['1.91', '1.89']}
{'シェア(%)': '20.0',
 'ブランド': 'C',
 '浸透率:実測 / 簡略理論(%)': ['29.8', '35.0'],
 '購買者当たり回数:実測 / 簡略理論': ['1.89', '1.61']}

For brand C, observed period penetration is 29.8%, versus 35.0% under the simplified model. Observed purchases per buyer are 1.89, versus a theoretical 1.61. These differences include sampling variation and the effect of simplification. A high purchase count alone does not establish strong attachment or a successful action.

Finally, we plot double jeopardy with the book’s theoretical settings: five brands, $M=4$, $K=0.800$, and $\alpha_0=10$. This is a theoretical calculation with fixed conditions, not an estimation result. Overlaying the simplified model shows that the two calculations differ.

example_shares = np.array([0.350, 0.250, 0.200, 0.130, 0.0700])
example_brands = ["A", "B", "C", "D", "E"]
M_example, K_example, alpha0_example = 4, 0.800, 10

# 超幾何関数で、選択確率の個人差を含めた期間浸透率を求める。
b_full = 1 - special.hyp2f1(
    K_example, alpha0_example * example_shares, alpha0_example, -M_example / K_example
)
w_full = M_example * example_shares / b_full
b_approx = 1 - (K_example / (K_example + M_example * example_shares))**K_example
w_approx = M_example * example_shares / b_approx

fig, axes = plt.subplots(1, 2, figsize=(11, 4), layout="constrained")
for ax, full, simple, title, ylabel in (
    (axes[0], 100 * b_full, 100 * b_approx, "図7a シェアと期間浸透率", "期間浸透率(%)"),
    (axes[1], w_full, w_approx, "図7b シェアと購買者当たり回数", "平均購買回数(回/年)"),
):
    ax.plot(100 * example_shares, full, "o-", color=COLORS[0], label="ディリクレNBD")
    ax.plot(100 * example_shares, simple, "s--", color=COLORS[1], label="共通Kの簡略モデル")
    for brand, share, value in zip(example_brands, example_shares, full):
        offset = (0, 10) if ax is axes[1] else (0, -16)
        ax.annotate(brand, (100 * share, value), xytext=offset,
                    textcoords="offset points", ha="center", fontsize=10)
    ax.set(title=title, xlabel="購買回数ベースの市場シェア(%)", ylabel=ylabel)
    ax.margins(y=0.200)
    ax.legend(fontsize=9)
save_svg(fig, "07_double_jeopardy.svg")

print("ディリクレNBDの理論値(AからEの順)")
pprint({"浸透率(%)": [sig3(value * 100) for value in b_full],
        "購買者当たりの平均回数": [sig3(value) for value in w_full]})
ディリクレNBDの理論値(AからEの順)
{'浸透率(%)': ['53.1', '44.5', '38.9', '29.0', '17.8'],
 '購買者当たりの平均回数': ['2.64', '2.25', '2.06', '1.79', '1.57']}

Brand A, with 35% share, has 53.1% penetration and 2.64 purchases per buyer. Brand E, with 7% share, has 17.8% penetration and 1.57 purchases per buyer. Differences in purchase frequency can therefore be read alongside differences in brand size.

Conclusion

This article used the NBD and Dirichlet distribution to model purchasing and calculated benchmarks for purchase counts and period penetration in Python.

Keep non-buyers, observation periods, and the target population consistent. Differences between observed and theoretical values can guide further investigation of distribution, awareness, first purchases, and repeat purchases. Check sampling variation and use a comparison group to evaluate an action’s effect.

Marketing Science in Theory and Practice connects business questions, theory, implementation, and interpretation. Chapter 5’s full code and additional derivations are also available for applying these models to business data.