Environment

Python 3.14.6, NumPy 2.4.6, SciPy 1.18.1, pandas 2.3.3, lifetimes 0.11.3, Matplotlib 3.11.2.

Overview

This article introduces Chapter 10, “Identifying Valuable Customers,” of Marketing Science in Theory and Practice . We begin with the problem of judging customers only by past sales, then cover RFM, probabilistic models of purchasing and dropout, and LTV prediction in Python. Here LTV is the sum of expected gross profit after the observation period, discounted to present value.

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 pandas as pd
import matplotlib.pyplot as plt
import matplotlib_fontja  # 日本語フォントを設定する。
from matplotlib.ticker import FuncFormatter
from IPython.display import Latex, SVG, display
from lifetimes import BetaGeoFitter, GammaGammaFitter
from lifetimes.utils import (
    summary_data_from_transaction_data,
    calibration_and_holdout_data,
)

print(f"Python {platform.python_version()} / wa-src(3.14.6)")
for package in ("numpy", "scipy", "pandas", "matplotlib", "matplotlib-fontja", "lifetimes"):
    print(f"{package}: {version(package)}")

# リポジトリのルート、またはノートブックのある場所から実行できる。
out_dir = Path("blog/10/10_nb_files") if Path("blog/10").is_dir() else Path("10_nb_files")
out_dir.mkdir(parents=True, exist_ok=True)
plt.rcParams.update({"font.size": 11, "axes.spines.top": False, "axes.spines.right": False})
colors = ["#2563a6", "#d97935", "#358773"]


def sig3(value):
    """計算値を丸めず、表示だけを有効数字3桁にする。"""
    return "0" if value == 0 else f"{float(value):#.3g}".removesuffix(".")


def show_math(formula):
    r"""重要な式は \( ... \) で受け、LaTeXの出力欄へ表示する。"""
    formula = formula.strip()
    assert formula.startswith(r"\(") and formula.endswith(r"\)")
    display(Latex("$$\n" + formula[2:-2].strip() + "\n$$"))


def show_table(frame):
    print(frame.to_string(float_format=sig3))


def save_plot(fig, name):
    """軸の小数表記をそろえ、SVGを保存してノートブックにも埋め込む。"""
    formatter = FuncFormatter(lambda value, _: str(int(value)) if value == int(value) else sig3(value))
    for ax in fig.axes:
        if ax.xaxis.get_scale() == "linear":
            ax.xaxis.set_major_formatter(formatter)
        if ax.yaxis.get_scale() == "linear" and ax.get_ylabel() != "顧客ID":
            ax.yaxis.set_major_formatter(formatter)
    path = out_dir / f"{name}.svg"
    fig.savefig(path, format="svg", bbox_inches="tight")
    plt.close(fig)
    display(SVG(filename=str(path)))
Python 3.14.6 / wa-src(3.14.6)
numpy: 2.4.6
scipy: 1.18.1
pandas: 2.3.3
matplotlib: 3.11.2
matplotlib-fontja: 1.1.0
lifetimes: 0.11.3

1. Will past high-value customers buy again?

The chapter opens with a case in which members ranked highly by cumulative spending include customers who have not bought for a long time. Meanwhile, customers whose purchasing has recently increased do not yet rank highly by cumulative spending. When revising membership tiers, check these two groups separately.

Let $H_i$ be customer $i$’s history, $\bar m_i$ expected gross profit per purchase, $\Delta Y_{i,h}$ the purchase count in future period $h$, and $d$ the discount rate. If gross profit and purchase count are independent, LTV over $K$ periods is as follows.

show_math(r"""\(
\begin{aligned}
E[\mathrm{LTV}_i^{(K)}\mid H_i]
&=\sum_{h=1}^{K}\frac{E[\bar m_i\Delta Y_{i,h}\mid H_i]}{(1+d)^h}\\
&=\sum_{h=1}^{K}\frac{\bar m_i E[\Delta Y_{i,h}\mid H_i]}{(1+d)^h}.
\end{aligned}
\)""")

$$ \begin{aligned} E[\mathrm{LTV}_i^{(K)}\mid H_i] &=\sum_{h=1}^{K}\frac{E[\bar m_i\Delta Y_{i,h}\mid H_i]}{(1+d)^h}\\ &=\sum_{h=1}^{K}\frac{\bar m_i E[\Delta Y_{i,h}\mid H_i]}{(1+d)^h}. \end{aligned} $$

Purchase-count predictions include both the probability of being alive and the purchase rate. “Alive” means still able to continue purchasing. In e-commerce without a formal cancellation process, dropout is not directly observed and must be inferred from history.

For acquisition decisions, compare LTV from acquisition onward with customer acquisition cost over a consistent scope. Do not directly compare an existing customer’s remaining LTV with past acquisition spending.

2. Summarize histories with RFM

Conventional RFM uses time since the last purchase, purchase frequency, and spending. It supports score-based grouping but does not directly predict future purchase counts. The model in this chapter uses the following definitions instead.

SymbolMeaning in this implementation
$x$Additional purchase days, excluding the first
$t_x$Weeks from the first to the last purchase day
$T$Weeks from the first purchase to the end of observation
$m$Average gross profit per purchase day, excluding the first day

Transactions on the same day are combined and counted as one purchase day. BG/NBD models purchase events in continuous time, so we use its forecasts as an approximation to purchase days. If customers often make several purchases on the same day, assess the effect of this aggregation separately. A more recent last purchase puts $t_x$ closer to $T$.

3. Model purchasing and dropout probabilistically

From Pareto/NBD to BG/NBD

Pareto/NBD models purchases while alive as a Poisson process and time to dropout as an exponential distribution. Individual purchase and dropout rates each follow a gamma distribution.

BG/NBD keeps the purchase process but assumes dropout occurs with a fixed probability immediately after an additional purchase. Purchase rate $\lambda$ and dropout probability $\theta$ are independent, and customers do not return after dropout. The second gamma parameter below is a rate.

show_math(r"""\(
\lambda\sim\mathrm{Gamma}(r,\alpha),\qquad
\theta\sim\mathrm{Beta}(a,b),\qquad
E[\lambda]=\frac r\alpha,\quad E[\theta]=\frac a{a+b}.
\)""")

$$ \lambda\sim\mathrm{Gamma}(r,\alpha),\qquad \theta\sim\mathrm{Beta}(a,b),\qquad E[\lambda]=\frac r\alpha,\quad E[\theta]=\frac a{a+b}. $$

Add the alive and dropout likelihoods

Split the likelihood of the history into $L_A$, for a customer still alive at observation end, and $L_D$, for dropout after the last purchase. Because this is a likelihood for a history including purchase times, the $x!$ found in a Poisson count probability does not appear.

show_math(r"""\(
L_A=(1-\theta)^x\lambda^x e^{-\lambda T},\qquad
L_D=\theta(1-\theta)^{x-1}\lambda^x e^{-\lambda t_x}\quad(x>0).
\)""")

$$ L_A=(1-\theta)^x\lambda^x e^{-\lambda T},\qquad L_D=\theta(1-\theta)^{x-1}\lambda^x e^{-\lambda t_x}\quad(x>0). $$

Averaging over individual differences is marginalization. Substitute either $T$ or $t_x$ for $z$, and set $u=(\alpha+z)\lambda$. The purchase-rate integral then simplifies as follows.

show_math(r"""\(
\begin{aligned}
G(z)&=\int_0^\infty\lambda^x e^{-\lambda z}
\frac{\alpha^r\lambda^{r-1}e^{-\alpha\lambda}}{\Gamma(r)}\,d\lambda\\
&=\frac{\alpha^r}{\Gamma(r)}\int_0^\infty
\lambda^{r+x-1}e^{-(\alpha+z)\lambda}\,d\lambda\\
&=\frac{\alpha^r}{\Gamma(r)(\alpha+z)^{r+x}}
\int_0^\infty u^{r+x-1}e^{-u}\,du\\
&=\frac{\alpha^r\Gamma(r+x)}{\Gamma(r)(\alpha+z)^{r+x}}.
\end{aligned}
\)""")

$$ \begin{aligned} G(z)&=\int_0^\infty\lambda^x e^{-\lambda z} \frac{\alpha^r\lambda^{r-1}e^{-\alpha\lambda}}{\Gamma(r)}\,d\lambda\\ &=\frac{\alpha^r}{\Gamma(r)}\int_0^\infty \lambda^{r+x-1}e^{-(\alpha+z)\lambda}\,d\lambda\\ &=\frac{\alpha^r}{\Gamma(r)(\alpha+z)^{r+x}} \int_0^\infty u^{r+x-1}e^{-u}\,du\\ &=\frac{\alpha^r\Gamma(r+x)}{\Gamma(r)(\alpha+z)^{r+x}}. \end{aligned} $$

For dropout, use the beta function $B(a,b)=\int_0^1\theta^{a-1}(1-\theta)^{b-1}d\theta$. Combine the exponents and recognize the beta-function definition.

show_math(r"""\(
\begin{aligned}
A&=\frac1{B(a,b)}\int_0^1\theta^{a-1}(1-\theta)^{b+x-1}\,d\theta
=\frac{B(a,b+x)}{B(a,b)},\\
D&=\frac1{B(a,b)}\int_0^1\theta^a(1-\theta)^{b+x-2}\,d\theta
=\frac{B(a+1,b+x-1)}{B(a,b)},\\
\frac DA&=\frac{\Gamma(a+1)\Gamma(b+x-1)}{\Gamma(a)\Gamma(b+x)}
=\frac a{b+x-1},\\
P(\mathrm{alive}\mid x,t_x,T)
&=\frac{AG(T)}{AG(T)+DG(t_x)}\\
&=\left[1+\frac a{b+x-1}
\left(\frac{\alpha+T}{\alpha+t_x}\right)^{r+x}\right]^{-1}\quad(x>0).
\end{aligned}
\)""")

$$ \begin{aligned} A&=\frac1{B(a,b)}\int_0^1\theta^{a-1}(1-\theta)^{b+x-1}\,d\theta =\frac{B(a,b+x)}{B(a,b)},\\ D&=\frac1{B(a,b)}\int_0^1\theta^a(1-\theta)^{b+x-2}\,d\theta =\frac{B(a+1,b+x-1)}{B(a,b)},\\ \frac DA&=\frac{\Gamma(a+1)\Gamma(b+x-1)}{\Gamma(a)\Gamma(b+x)} =\frac a{b+x-1},\\ P(\mathrm{alive}\mid x,t_x,T) &=\frac{AG(T)}{AG(T)+DG(t_x)}\\ &=\left[1+\frac a{b+x-1} \left(\frac{\alpha+T}{\alpha+t_x}\right)^{r+x}\right]^{-1}\quad(x>0). \end{aligned} $$

The final step uses $\Gamma(s+1)=s\Gamma(s)$ and the ratio of the $G(z)$ terms. For $x=0$, the dropout term is absent and the alive probability is 1. This is a model assumption, not a claim that every one-time customer will return.

Predict gross profit with the gamma-gamma model

Let $z_j$ be gross profit on a purchase day, with $z_j\mid\nu\sim\mathrm{Gamma}(p,\nu)$ and $\nu\sim\mathrm{Gamma}(q,v)$. If the average across $x$ days is $m$, total gross profit is $xm$. The posterior and expected gross profit take the following form.

show_math(r"""\(
\begin{aligned}
\nu\mid x,m&\sim\mathrm{Gamma}(q+px,v+xm),\\
\bar m=E[p/\nu\mid x,m]
&=\frac{p(v+xm)}{px+q-1}\\
&=\frac{px}{px+q-1}m+
\frac{q-1}{px+q-1}\frac{pv}{q-1}\qquad(q>1).
\end{aligned}
\)""")

$$ \begin{aligned} \nu\mid x,m&\sim\mathrm{Gamma}(q+px,v+xm),\\ \bar m=E[p/\nu\mid x,m] &=\frac{p(v+xm)}{px+q-1}\\ &=\frac{px}{px+q-1}m+ \frac{q-1}{px+q-1}\frac{pv}{q-1}\qquad(q>1). \end{aligned} $$

For shape greater than 1, the expected reciprocal of a gamma-distributed variable is its rate divided by shape minus 1. Splitting the expression shows a weighted average of the individual’s observed value and the population mean. Less history gives more weight to the population mean. Purchase frequency and average gross profit are also assumed independent. The gamma distribution supports only positive values, so the model cannot be directly applied to zero or negative gross profit, for example after returns.

4. Calculate LTV in Python

4.1 Aggregate transactions by customer

Using the book’s random seed, generate histories for 3,000 customers. Everyone first purchases on January 1, 2022, and is observed through year-end. Gross profit is set to 40% of sales. These are simulated histories for demonstrating the method, not a company’s actual results.

rng = np.random.default_rng(123)
n_customers = 3000
start, end = pd.Timestamp("2022-01-01"), pd.Timestamp("2022-12-31")
observation_days = (end - start).days

# NumPyのガンマ分布には、レートの逆数であるscaleを渡す。
rates = rng.gamma(0.500, 1 / (1.25 * 7), n_customers)
dropout = rng.beta(0.500, 2.50, n_customers)
amount_rates = rng.gamma(3, 1 / 6000, n_customers)
rows = []

for customer, (rate, theta, nu) in enumerate(zip(rates, dropout, amount_rates), start=1):
    amount = max(1, int(rng.gamma(2, 1 / nu)))
    rows.append((customer, start, max(1, int(amount * 0.400))))
    if rate < 1.00e-8:
        continue
    elapsed = 0
    while True:
        elapsed += rng.exponential(1 / rate)
        if elapsed >= observation_days:
            break
        amount = max(1, int(rng.gamma(2, 1 / nu)))
        date = start + pd.Timedelta(days=int(elapsed))
        rows.append((customer, date, max(1, int(amount * 0.400))))
        if rng.random() < theta:
            break

transactions = pd.DataFrame(rows, columns=["customer_id", "date", "gross_profit"])
rfm = summary_data_from_transaction_data(
    transactions, "customer_id", "date", monetary_value_col="gross_profit",
    observation_period_end=end, freq="D", freq_multiplier=7,
)
print(f"顧客数: {len(rfm)} / 取引件数: {len(transactions)}")
show_table(rfm.head())

fig, axes = plt.subplots(1, 3, figsize=(12, 3.70), layout="constrained")
for ax, column, label, color in zip(
    axes, ("frequency", "recency", "monetary_value"),
    ("追加の購買日数", "初回から最終購買まで(週)", "購買日ごとの平均粗利(円)"), colors,
):
    values = rfm.loc[rfm.frequency > 0, column] if column == "monetary_value" else rfm[column]
    ax.hist(values, bins=30, color=color, edgecolor="white")
    ax.set(xlabel=label, ylabel="顧客数")
fig.suptitle("図1 顧客別の購買履歴(粗利は追加購買のある顧客)")
save_plot(fig, "01_rfm")
顧客数: 3000 / 取引件数: 26255
             frequency  recency    T  monetary_value
customer_id                                         
1                 22.0     50.9 52.0             673
2                 1.00     6.29 52.0             794
3                 1.00     46.9 52.0        2.89e+03
4                 6.00     7.57 52.0             453
5                 4.00     22.6 52.0        1.43e+03

4.2 Fit BG/NBD and check its predictions

Figure 1 contains many customers with few purchase days. Fit the model and compare their counts with purchase days regenerated over the same observation period. Regularization limits extreme parameter estimates.

x, tx, age = rfm.frequency, rfm.recency, rfm["T"]
bg = BetaGeoFitter(penalizer_coef=0.00100).fit(x, tx, age)
pprint({name: sig3(value) for name, value in bg.params_.items()})

# 推定した分布から購買時刻を作り、元データと同様に購買日を数える。
check_rng = np.random.default_rng(456)
r, alpha, a, b = (bg.params_[name] for name in ("r", "alpha", "a", "b"))
check_rates = check_rng.gamma(r, 1 / (alpha * 7), len(rfm))
check_dropout = check_rng.beta(a, b, len(rfm))
generated = np.zeros(len(rfm), dtype=int)
for i, (rate, theta, weeks) in enumerate(zip(check_rates, check_dropout, age)):
    elapsed, days = 0, set()
    while rate > 1.00e-8:
        elapsed += check_rng.exponential(1 / rate)
        if elapsed >= weeks * 7:
            break
        if int(elapsed) > 0:
            days.add(int(elapsed))
        if check_rng.random() < theta:
            break
    generated[i] = len(days)

fig, ax = plt.subplots(figsize=(8, 3.80), layout="constrained")
positions = np.arange(8)
for shift, values, label, color in (
    (-0.200, x.to_numpy(dtype=int), "観測値", colors[0]),
    (0.200, generated, "モデル生成値", colors[1]),
):
    counts = np.bincount(np.minimum(values, 7), minlength=8)
    ax.bar(positions + shift, counts, width=0.400, color=color, label=label)
ax.set(xlabel="追加の購買日数(7は7日以上)", ylabel="顧客数", title="図2 観測期間内の当てはまり")
ax.set_xticks(positions)
ax.legend()
save_plot(fig, "02_fit")
{'a': '0.477', 'alpha': '1.51', 'b': '2.15', 'r': '0.526'}

Figure 2 checks the training period. Next fit a separate model through the end of September and compare its predictions with October–December observations. Figure 3 averages results by training-period purchase count; MAE also measures errors at the individual level.

holdout = calibration_and_holdout_data(
    transactions, "customer_id", "date", calibration_period_end="2022-09-30",
    observation_period_end=end, freq="D", freq_multiplier=7,
)
bg_cal = BetaGeoFitter(penalizer_coef=0.00100).fit(
    holdout.frequency_cal, holdout.recency_cal, holdout.T_cal,
)
holdout["prediction"] = bg_cal.predict(
    holdout.duration_holdout.iloc[0],
    holdout.frequency_cal, holdout.recency_cal, holdout.T_cal,
)
mae = float(np.mean(np.abs(holdout.prediction - holdout.frequency_holdout)))
print(f"検証期間のMAE: {sig3(mae)} 日")
grouped = holdout.groupby(holdout.frequency_cal.clip(upper=8)).agg(
    actual=("frequency_holdout", "mean"), predicted=("prediction", "mean"),
    customers=("prediction", "size"),
)
fig, ax = plt.subplots(figsize=(8, 3.80), layout="constrained")
ax.plot(grouped.index, grouped.actual, "o-", color=colors[0], label="実績")
ax.plot(grouped.index, grouped.predicted, "s--", color=colors[1], label="予測")
ax.set(xlabel="学習期間の追加購買日数(8は8日以上)", ylabel="検証期間の平均購買日数",
       title=f"図3 未使用期間での検証(MAE = {sig3(mae)} 日)")
ax.legend()
save_plot(fig, "03_holdout")

# 生存確率は全観測期間で学習したbgを使う。
rfm["alive"] = bg.conditional_probability_alive(x, tx, age)
frequency_grid, recency_grid = np.meshgrid(np.arange(1, 16), np.arange(1, 53))
alive_grid = bg.conditional_probability_alive(frequency_grid, recency_grid, 52)
fig, ax = plt.subplots(figsize=(7, 4.60), layout="constrained")
mesh = ax.pcolormesh(frequency_grid, recency_grid, alive_grid, shading="nearest", cmap="viridis", vmin=0, vmax=1)
fig.colorbar(mesh, ax=ax, label="生存確率")
ax.set(xlabel="追加の購買日数", ylabel="初回から最終購買まで(週)",
       title="図4 生存確率(観測期間は52週に固定)")
save_plot(fig, "04_alive")
検証期間のMAE: 0.761 日

In Figure 4, customers with more recent last purchases have higher alive probabilities at the same frequency. Conversely, a long absence after previously frequent purchasing implies a greater chance of dropout.

4.3 Predict purchase days and gross profit

Let $Y(t)$ be the model’s cumulative purchase-event count over the next $t$ weeks. Here we use it as an approximation to purchase days. The library calculates the expectation $C(t)$ by integrating the purchase rate while alive. The indicator $I_s$ is 1 if the customer is alive at future time $T+s$ and 0 after dropout.

show_math(r"""\(
C(t)=E[Y(t)\mid H]=\int_0^t E[\lambda I_s\mid H]\,ds.
\)""")
rfm["purchases_52w"] = bg.predict(52, x, tx, age)
future_grid = bg.predict(52, frequency_grid, recency_grid, 52)
fig, ax = plt.subplots(figsize=(7, 4.60), layout="constrained")
mesh = ax.pcolormesh(frequency_grid, recency_grid, future_grid, shading="nearest", cmap="YlGnBu")
fig.colorbar(mesh, ax=ax, label="期待購買日数")
ax.set(xlabel="追加の購買日数", ylabel="初回から最終購買まで(週)",
       title="図5 今後52週の購買日数(観測期間は52週)")
save_plot(fig, "05_purchases")

# ガンマ–ガンマの学習には追加購買があり、平均粗利が正の顧客を使う。
repeat = rfm.loc[(x > 0) & (rfm.monetary_value > 0)]
gg = GammaGammaFitter(penalizer_coef=0).fit(repeat.frequency, repeat.monetary_value)
assert gg.params_["q"] > 1, "集団の期待粗利を有限にするためq > 1が必要である。"
pprint({name: sig3(value) for name, value in gg.params_.items()})
correlation = float(repeat.frequency.corr(repeat.monetary_value))
print(f"追加購買日数と平均粗利の相関: {sig3(correlation)}")
rfm["expected_profit"] = gg.conditional_expected_average_profit(x, rfm.monetary_value)

fig, ax = plt.subplots(figsize=(8, 3.80), layout="constrained")
counts = np.arange(31)
for observed, color in zip((1000, 4000, 8000), colors):
    estimate = gg.conditional_expected_average_profit(counts, observed)
    ax.plot(counts, estimate, color=color, label=f"実績平均 {observed} 円")
ax.set(xlabel="追加の購買日数", ylabel="予測する購買日当たり粗利(円)",
       title="図6 履歴件数による粗利予測の違い")
ax.legend()
save_plot(fig, "06_profit")

$$ C(t)=E[Y(t)\mid H]=\int_0^t E[\lambda I_s\mid H]\,ds. $$

{'p': '1.94', 'q': '2.92', 'v': '2.47e+03'}
追加購買日数と平均粗利の相関: 0.0179

Figure 5 reflects purchase rate as well as alive probability. In Figure 6, predictions for customers with few purchases move toward the population mean. A small correlation does not guarantee independence.

Next calculate 12 months of LTV. To make the calculation easy to follow, treat each month as 30 days. Take differences between cumulative predictions to obtain monthly purchase days, multiply by expected gross profit, and discount at 1% per month. Do not multiply by the alive probability again.

show_math(r"""\(
\begin{aligned}
t_h&=30h/7,\qquad E[\Delta Y_h\mid H]=C(t_h)-C(t_{h-1}),\\
\mathrm{LTV}^{(12)}&=\sum_{h=1}^{12}
\frac{\bar m\{C(t_h)-C(t_{h-1})\}}{(1+0.0100)^h}.
\end{aligned}
\)""")
months = np.arange(1, 13)
# 第0月を含む累積予測を作り、隣り合う月の差を取る。
cumulative = np.vstack([bg.predict(30 * month / 7, x, tx, age) for month in range(13)])
monthly_days = np.diff(cumulative, axis=0)
monthly_value = monthly_days * rfm.expected_profit.to_numpy() / (1 + 0.0100) ** months[:, None]
rfm["LTV"] = monthly_value.sum(axis=0)

top_customer = rfm.LTV.idxmax()
column = rfm.index.get_loc(top_customer)
fig, ax = plt.subplots(figsize=(8, 3.80), layout="constrained")
ax.bar(months, monthly_value[:, column], color=colors[0])
ax.set(xlabel="予測する月", ylabel="割引後の期待粗利(円)",
       title=f"図7 LTV上位1名の月別内訳(顧客ID {top_customer})")
ax.set_xticks(months)
save_plot(fig, "07_monthly_ltv")

$$ \begin{aligned} t_h&=30h/7,\qquad E[\Delta Y_h\mid H]=C(t_h)-C(t_{h-1}),\\ \mathrm{LTV}^{(12)}&=\sum_{h=1}^{12} \frac{\bar m\{C(t_h)-C(t_{h-1})\}}{(1+0.0100)^h}. \end{aligned} $$

4.4 Rank customers by LTV and consider actions

The sum of the 12 bars in Figure 7 is that customer’s LTV. Rank all customers by LTV and create segments at 30%, 60%, and 85% of cumulative LTV. These are shares of value, not shares of customers.

ranked = rfm.sort_values("LTV", ascending=False).copy()
ranked["cumulative_pct"] = ranked.LTV.cumsum() / ranked.LTV.sum() * 100
ranked["segment"] = pd.cut(
    ranked.cumulative_pct.clip(upper=100), bins=[0, 30, 60, 85, 100],
    labels=["Platinum", "Gold", "Silver", "General"], include_lowest=True,
)
show_table(ranked[["frequency", "alive", "expected_profit", "LTV", "segment"]].head())
summary = ranked.groupby("segment", observed=True).agg(
    customers=("LTV", "size"), mean_ltv=("LTV", "mean"), total_ltv=("LTV", "sum"),
)
summary["ltv_pct"] = summary.total_ltv / ranked.LTV.sum() * 100
show_table(summary.drop(columns="total_ltv"))

fig, axes = plt.subplots(1, 3, figsize=(13, 3.80), layout="constrained")
positive = ranked.loc[ranked.LTV > 0, "LTV"]
axes[0].hist(np.log10(positive), bins=30, color=colors[0], edgecolor="white")
axes[0].set(xlabel="log10(LTV / 円)", ylabel="顧客数", title="LTVの分布")
customer_pct = np.arange(1, len(ranked) + 1) / len(ranked) * 100
axes[1].plot(customer_pct, ranked.cumulative_pct, color=colors[1])
axes[1].plot([0, 100], [0, 100], ":", color="gray", label="均等な場合")
for threshold in (30, 60, 85):
    axes[1].axhline(threshold, color="gray", linestyle="--", linewidth=0.700)
axes[1].set(xlabel="LTV上位からの顧客割合(%)", ylabel="累積LTV(%)", title="LTVの集中度")
axes[1].legend()
top = ranked.head(5).sort_values("LTV")
axes[2].barh(np.arange(5), top.LTV, color=colors[2])
axes[2].set_yticks(np.arange(5), [str(i) for i in top.index])
axes[2].set(xlabel="12か月LTV(円)", ylabel="顧客ID", title="上位5名")
fig.suptitle("図8 LTVの分布と顧客ランキング")
save_plot(fig, "08_ranking")

# 出力前に、予測の範囲とLTVの集計を確認する。
assert np.isfinite(rfm.select_dtypes(include="number")).all().all()
assert rfm.alive.between(0, 1).all()
assert np.allclose(rfm.loc[x == 0, "alive"], 1)
assert monthly_days.min() >= -1.00e-8 and (rfm.LTV >= 0).all()
assert np.allclose(monthly_days.sum(axis=0), bg.predict(360 / 7, x, tx, age))
assert ranked.segment.notna().all()
             frequency  alive  expected_profit      LTV   segment
customer_id                                                      
2299               114  0.937         1.16e+04 9.47e+05  Platinum
50                62.0  0.985         1.34e+04 6.27e+05  Platinum
2422              83.0  0.993         7.71e+03 4.87e+05  Platinum
1799              96.0  0.986         5.22e+03 3.78e+05  Platinum
1170               129  0.993         3.86e+03 3.78e+05  Platinum
          customers  mean_ltv  ltv_pct
segment                               
Platinum         31  2.72e+05     29.8
Gold            117  7.32e+04     30.2
Silver          329  2.16e+04     25.0
General        2523  1.69e+03     15.0

4.5 Also examine uncertainty

The book finishes with estimation in PyMC-Marketing, MCMC diagnostics, and a 94% credible interval for expected LTV. Holding expected gross profit fixed, this interval represents uncertainty in BG/NBD parameters; it is not a prediction interval for realized profit. The detailed code is on the book’s support page .

Conclusion

This article introduced a workflow for estimating alive probabilities, future purchase days, and expected gross profit from purchase histories, then ranking customers by LTV.

LTV helps identify possible targets but does not directly show the profit caused by a coupon. Instead of choosing recipients solely by rank, compare treatment and control groups to assess additional profit and cost.

Marketing Science in Theory and Practice explains the assumptions, derivations, implementation, and interpretation in sequence. It can help clarify what can be predicted from a company’s purchase histories.

Reference: Fader, Hardie, and Lee (2005), “Counting Your Customers” the Easy Way , Marketing Science, 24(2), 275–284.