Environment
Python 3.14.6, NumPy 2.4.6, pandas 2.3.3, SciPy 1.18.1, scikit-learn 1.9.1, Matplotlib 3.11.2.
Overview
A first-time buyer and a returning customer may need different information, even if they receive the same message. This article introduces Chapter 2, “Classifying Customers,” of Marketing Science in Theory and Practice . We use total spending and order counts to describe customer differences, then use k-means and Gaussian mixture models (GMMs) to consider possible marketing actions.
Using the same real-world data as the book, we work through preprocessing, clustering, and membership probabilities in Python. Clustering does not establish whether an action works; it helps us choose whom to target and what to test.
Setup code (imports and display settings)
from pathlib import Path
from pprint import pprint
from importlib.metadata import version
from io import BytesIO
from base64 import b64encode
import platform
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import font_manager
from matplotlib.patches import Ellipse
from matplotlib.ticker import FuncFormatter, MaxNLocator, ScalarFormatter
from scipy.stats import chi2
from sklearn.cluster import KMeans
from sklearn.mixture import GaussianMixture
from sklearn.preprocessing import StandardScaler
from IPython.display import Latex, display
# ノートブックのあるディレクトリ、またはリポジトリ直下から実行する。
BASE = Path.cwd()
if (BASE / "blog/02/02_nb.ipynb").exists():
BASE = BASE / "blog/02"
FIG_DIR = BASE / "02_nb_files"
FIG_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をファイルとノートブック出力の両方に保存する。"""
# 自動目盛りも、小数が現れる場合は有効数字3桁にそろえる。
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,
metadata={"image/svg+xml": {"width": min(860, int(fig.get_figwidth() * 96))},
"image/png": {"width": min(860, int(fig.get_figwidth() * 96))}})
np.set_printoptions(formatter={"float_kind": sig3})
pd.options.display.float_format = 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": "blog02"})
tick3 = FuncFormatter(lambda value, _: sig3(value))
colors = ["#3274A1", "#D58B27", "#419578", "#9D5F95"]
print("仮想環境:wa-src(3.14.6)")
print(f"Python:{platform.python_version()}")
for package in ("numpy", "pandas", "scipy", "scikit-learn", "matplotlib"):
print(f"{package}:{version(package)}")
仮想環境:wa-src(3.14.6)
Python:3.14.6
numpy:2.4.6
pandas:2.3.3
scipy:1.18.1
scikit-learn:1.9.1
matplotlib:3.11.2
1. Which customers should receive which message?
The chapter starts from the fact that customers of the same age or gender can behave differently. STP stands for Segmentation, dividing customers into groups; Targeting, choosing priority groups; and Positioning, deciding what value to communicate. Here we begin by grouping customers using their purchase histories.
We use UCI Online Retail , which contains transactions from a UK online retailer between December 2010 and December 2011. Keeping only rows with a customer ID, positive quantity, and positive unit price leaves 4,338 customers.
Total spending is the sum of quantity times unit price. Order count is the number of distinct invoice numbers. Spending here is not net revenue after subtracting returns and cancellations. The following code creates these two columns for each customer. Before running it, convert the UCI Excel file to CSV without renaming columns, gzip it, and place it at data/online_retail.csv.gz relative to the notebook.
# 書籍のCSVを読み込み、取引明細を1行1顧客に集計する。
raw = pd.read_csv(
BASE / "data/online_retail.csv.gz",
usecols=["CustomerID", "InvoiceNo", "Quantity", "UnitPrice"],
dtype={"CustomerID": "Int64", "InvoiceNo": "string"},
)
retail = raw.loc[
raw["CustomerID"].notna() & (raw["Quantity"] > 0) & (raw["UnitPrice"] > 0)
].copy()
retail["amount"] = retail["Quantity"] * retail["UnitPrice"]
customers = retail.groupby("CustomerID", sort=True).agg(
spend=("amount", "sum"),
orders=("InvoiceNo", "nunique"),
)
print(f"分析対象:{len(customers):,}顧客")
print("spend:総支出額(GBP)、orders:注文回数")
print(customers.head().to_string())
分析対象:4,338顧客
spend:総支出額(GBP)、orders:注文回数
spend orders
CustomerID
12346 7.72e+04 1
12347 4.31e+03 7
12348 1.80e+03 4
12349 1.76e+03 1
12350 334 1
2. Do not calculate distances directly from money and counts
Spending and order counts have different units and ranges. Calculating distances directly would give spending differences too much influence. A small number of customers also have very large values. We add 1 to each value, take the natural logarithm, and then standardize each feature to mean 0 and variance 1.
Let $x_{ij}$ be feature $j$ of customer $i$, and let $n$ be the customer count. We calculate the mean $\bar{u}_j$ and standard deviation $s_j$ after the log transform, then form the standardized vector $\mathbf{z}_i$. The variance uses denominator $n$, as in StandardScaler.
show_math(r"""\(
\begin{aligned}
u_{ij}&=\log(1+x_{ij}), &
\bar{u}_j&=\frac{1}{n}\sum_{i=1}^{n}u_{ij},\\
s_j^2&=\frac{1}{n}\sum_{i=1}^{n}(u_{ij}-\bar{u}_j)^2, &
s_j&=\sqrt{s_j^2},\\
z_{ij}&=\frac{u_{ij}-\bar{u}_j}{s_j}, &
\mathbf{z}_i&=(z_{i1},z_{i2}).
\end{aligned}
\)""")
values = customers[["spend", "orders"]].to_numpy(dtype=float)
log_values = np.log1p(values)
scaler = StandardScaler()
Z = scaler.fit_transform(log_values)
print("標準化した先頭3顧客(列順:総支出額、注文回数)")
pprint(Z[:3])
# 上段は元の単位、下段は対数変換後。全顧客を表示する。
fig, axes = plt.subplots(2, 2, figsize=(9, 6.30), layout="constrained")
for j, name in enumerate(("総支出額(GBP)", "注文回数(回)")):
axes[0, j].hist(values[:, j], bins=50, color=colors[j])
axes[0, j].set(xlabel=name, ylabel="顧客数", title="変換前")
axes[1, j].hist(log_values[:, j], bins=35, color=colors[j])
axes[1, j].set(xlabel=f"log(1 + {name})", ylabel="顧客数", title="対数変換後")
axes[0, j].xaxis.set_major_locator(MaxNLocator(4))
save_svg(fig, "01_distributions.svg")
$$ \begin{aligned} u_{ij}&=\log(1+x_{ij}), & \bar{u}_j&=\frac{1}{n}\sum_{i=1}^{n}u_{ij},\\ s_j^2&=\frac{1}{n}\sum_{i=1}^{n}(u_{ij}-\bar{u}_j)^2, & s_j&=\sqrt{s_j^2},\\ z_{ij}&=\frac{u_{ij}-\bar{u}_j}{s_j}, & \mathbf{z}_i&=(z_{i1},z_{i2}). \end{aligned} $$
標準化した先頭3顧客(列順:総支出額、注文回数)
array([[3.71, -0.955],
[1.41, 1.07],
[0.716, 0.386]])
In the top row of Figure 1, a few large customers stretch the horizontal axes. After the log transform, the bottom row makes the distribution from small to large customers easier to see. The log transform compresses differences between large values; standardization puts features on comparable scales. These are different roles.
We use Euclidean distance to measure how close customers are. For a simple calculation, set $\mathbf{z}_A=(0,1)$ and $\mathbf{z}_B=(2,2)$. Square the coordinate differences, add them, and take the square root. These are illustrative points, not customers from the data.
show_math(r"""\(
\begin{aligned}
d(\mathbf{z}_A,\mathbf{z}_B)
&=\sqrt{\sum_{j=1}^{2}(z_{Aj}-z_{Bj})^2}\\
&=\sqrt{(0-2)^2+(1-2)^2}\\
&=\sqrt{4+1}=\sqrt{5}\approx 2.24.
\end{aligned}
\)""")
example = np.array([[0, 1], [2, 2]])
pprint(sig3(np.linalg.norm(example[0] - example[1])))
$$ \begin{aligned} d(\mathbf{z}_A,\mathbf{z}_B) &=\sqrt{\sum_{j=1}^{2}(z_{Aj}-z_{Bj})^2}\\ &=\sqrt{(0-2)^2+(1-2)^2}\\ &=\sqrt{4+1}=\sqrt{5}\approx 2.24. \end{aligned} $$
'2.24'
3. Use k-means to group customers by purchase size
k-means repeatedly assigns each customer to the nearest centroid and updates each centroid to the mean of its cluster. The objective is to reduce the sum of squared distances to the centroids, or SSE.
Let $C_k$ be the customers in cluster $k$, $n_k$ its size, and $\mathbf{c}_k$ its centroid. Holding the assignments fixed and differentiating SSE with respect to coordinate $c_{kj}$ shows why the centroid is the mean.
show_math(r"""\(
\begin{aligned}
\mathrm{SSE}&=\sum_{k=1}^{K}\sum_{i\in C_k}\|\mathbf{z}_i-\mathbf{c}_k\|^2\\
&=\sum_{k=1}^{K}\sum_{i\in C_k}\sum_{j=1}^{2}(z_{ij}-c_{kj})^2,\\
\frac{\partial\mathrm{SSE}}{\partial c_{kj}}
&=2\sum_{i\in C_k}(c_{kj}-z_{ij})\\
&=2n_kc_{kj}-2\sum_{i\in C_k}z_{ij}=0,\\
n_kc_{kj}&=\sum_{i\in C_k}z_{ij}
\quad\Longrightarrow\quad
\mathbf{c}_k=\frac{1}{n_k}\sum_{i\in C_k}\mathbf{z}_i.
\end{aligned}
\)""")
$$ \begin{aligned} \mathrm{SSE}&=\sum_{k=1}^{K}\sum_{i\in C_k}\|\mathbf{z}_i-\mathbf{c}_k\|^2\\ &=\sum_{k=1}^{K}\sum_{i\in C_k}\sum_{j=1}^{2}(z_{ij}-c_{kj})^2,\\ \frac{\partial\mathrm{SSE}}{\partial c_{kj}} &=2\sum_{i\in C_k}(c_{kj}-z_{ij})\\ &=2n_kc_{kj}-2\sum_{i\in C_k}z_{ij}=0,\\ n_kc_{kj}&=\sum_{i\in C_k}z_{ij} \quad\Longrightarrow\quad \mathbf{c}_k=\frac{1}{n_k}\sum_{i\in C_k}\mathbf{z}_i. \end{aligned} $$
The number of clusters $K$ must be specified in advance. The elbow method examines how SSE decreases as $K$ grows. It does not choose the cluster count with the lowest SSE. A point where the decrease becomes slower is a candidate, but we must also ask whether the groups support meaningful differences in marketing actions.
# 複数の初期値で学習し、各Kで最もSSEが小さい結果を使う。
models = {}
for k in range(1, 11):
models[k] = KMeans(n_clusters=k, n_init=20, random_state=42).fit(Z)
sse = np.array([model.inertia_ for model in models.values()])
fig, ax = plt.subplots(figsize=(7, 4), layout="constrained")
ax.plot(range(1, 11), sse, "o-", color=colors[0])
ax.set(xlabel="クラスタ数 K", ylabel="SSE", xticks=range(1, 11))
ax.grid(alpha=0.250)
save_svg(fig, "02_elbow.svg")
# 本文と同じK=4を採用し、番号を購入規模の小さい順に並べ直す。
km = models[4]
order = np.argsort(scaler.inverse_transform(km.cluster_centers_).sum(axis=1))
mapping = np.empty(4, dtype=int)
mapping[order] = np.arange(4)
labels = mapping[km.labels_]
centers = km.cluster_centers_[order]
customers["segment"] = labels + 1
In Figure 2, SSE falls sharply until about $K=3$, then more slowly. The chapter uses $K=4$ to illustrate four levels of purchase size. This does not mean that customers naturally fall into exactly four types.
After clustering, we interpret the groups in the original units. The next figure shows customer counts, total spending, and order counts from left to right. Points are medians, and lines run from the first to the third quartile.
grouped = customers.groupby("segment")
summary = grouped.agg(n=("spend", "size"),
spend_median=("spend", "median"),
orders_median=("orders", "median"))
print(summary.to_string())
fig, axes = plt.subplots(1, 3, figsize=(9, 4), layout="constrained")
segments = np.arange(1, 5)
axes[0].bar(segments, summary["n"], color=colors)
axes[0].set(ylabel="顧客数")
for ax, feature, unit in zip(axes[1:], ("spend", "orders"), ("総支出額(GBP)", "注文回数(回)")):
q = grouped[feature].quantile([0.250, 0.500, 0.750]).unstack()
for k, color in zip(segments, colors):
low, median, high = q.loc[k].to_numpy()
ax.errorbar(k, median, yerr=[[median - low], [high - median]],
fmt="o", capsize=5, color=color)
ax.set(ylabel=unit)
for ax in axes:
ax.set(xlabel="セグメント", xticks=segments)
ax.grid(axis="y", alpha=0.250)
save_svg(fig, "03_segment_profiles.svg")
n spend_median orders_median
segment
1 1514 224 1.00
2 1456 708 2.00
3 1032 2.04e+03 6.00
4 336 6.41e+03 15.0
The low-spending, mostly one-time group has 1,514 customers and a median of one order. The high-spending, frequent group has 336 customers and a median of 15.0 orders. Before naming a group, check its size, spending, and order counts in the original units. Calling a small group of large buyers “valuable customers” does not tell us which action they need.
4. Use GMM membership probabilities to examine ambiguity
A GMM combines several normal distributions and represents each customer’s membership with probabilities. Here $\pi_k$ is a component’s proportion, $\mathbf{m}_k$ its mean vector, and $\mathbf{S}_k$ the covariance matrix describing its spread and orientation. $\mathcal{N}$ denotes a normal probability density.
The membership probability $\gamma_{ik}$ is the joint density of component $k$ and the customer’s features divided by the density summed over all components. Writing the numerator as $q_{ik}$ also makes it easy to check that the probabilities sum to 1.
show_math(r"""\(
\begin{aligned}
q_{ik}&=\pi_k\mathcal{N}(\mathbf{z}_i\mid\mathbf{m}_k,\mathbf{S}_k),\\
p(\mathbf{z}_i)&=\sum_{j=1}^{K}q_{ij},\\
\gamma_{ik}&=\frac{p(k,\mathbf{z}_i)}{p(\mathbf{z}_i)}
=\frac{q_{ik}}{\sum_{j=1}^{K}q_{ij}},\\
\sum_{k=1}^{K}\gamma_{ik}&=\frac{\sum_{k=1}^{K}q_{ik}}{\sum_{j=1}^{K}q_{ij}}=1.
\end{aligned}
\)""")
# 所属確率の計算だけを示す仮の値。実データの推定結果ではない。
q_example = np.array([0.0800, 0.0200, 0.0900, 0.0100])
p_example = q_example / q_example.sum()
pprint(p_example)
show_math(r"""\(
\begin{aligned}
\sum_{j=1}^{4}q_{ij}&=0.0800+0.0200+0.0900+0.0100=0.200,\\
\gamma_{i3}&=\frac{0.0900}{0.200}=0.450,\\
\mathbf{p}_i&=(0.400,\ 0.100,\ 0.450,\ 0.0500),\\
1-\max_k\gamma_{ik}&=1-0.450=0.550.
\end{aligned}
\)""")
$$ \begin{aligned} q_{ik}&=\pi_k\mathcal{N}(\mathbf{z}_i\mid\mathbf{m}_k,\mathbf{S}_k),\\ p(\mathbf{z}_i)&=\sum_{j=1}^{K}q_{ij},\\ \gamma_{ik}&=\frac{p(k,\mathbf{z}_i)}{p(\mathbf{z}_i)} =\frac{q_{ik}}{\sum_{j=1}^{K}q_{ij}},\\ \sum_{k=1}^{K}\gamma_{ik}&=\frac{\sum_{k=1}^{K}q_{ik}}{\sum_{j=1}^{K}q_{ij}}=1. \end{aligned} $$
array([0.400, 0.100, 0.450, 0.0500])
$$ \begin{aligned} \sum_{j=1}^{4}q_{ij}&=0.0800+0.0200+0.0900+0.0100=0.200,\\ \gamma_{i3}&=\frac{0.0900}{0.200}=0.450,\\ \mathbf{p}_i&=(0.400,\ 0.100,\ 0.450,\ 0.0500),\\ 1-\max_k\gamma_{ik}&=1-0.450=0.550. \end{aligned} $$
GMM fitting uses the expectation-maximization (EM) algorithm. It calculates membership probabilities from the current means, covariances, and proportions, then uses those probabilities as weights to update the parameters. We fix the number of components at four to compare with k-means.
gmm = GaussianMixture(n_components=4, covariance_type="full",
n_init=20, random_state=42, reg_covar=0.00100).fit(Z)
gmm_order = np.argsort(scaler.inverse_transform(gmm.means_).sum(axis=1))
proba = gmm.predict_proba(Z)[:, gmm_order]
labels_gmm = proba.argmax(axis=1)
means = gmm.means_[gmm_order]
covariances = gmm.covariances_[gmm_order]
max_probability = proba.max(axis=1)
# 両手法を同じ軸・同じ範囲で比較する。
fig, axes = plt.subplots(1, 2, figsize=(9, 4.50), sharex=True, sharey=True,
layout="constrained")
for ax, assigned, center, title in zip(
axes, (labels, labels_gmm), (centers, means), ("k-means", "GMM")
):
for k, color in enumerate(colors):
points = Z[assigned == k]
ax.scatter(points[:, 0], points[:, 1], s=8, alpha=0.400,
color=color, label=str(k + 1))
ax.scatter(center[:, 0], center[:, 1], marker="X", s=75, color="black")
ax.set(title=title, xlabel="総支出額:対数変換・標準化後")
ax.legend(title="番号", fontsize=9)
axes[0].set_ylabel("注文回数:対数変換・標準化後")
# GMMの各正規分布の95%確率楕円。推定平均の信頼区間ではない。
for mean, covariance, color in zip(means, covariances, colors):
eigenvalues, eigenvectors = np.linalg.eigh(covariance)
width, height = 2 * np.sqrt(chi2.ppf(0.950, df=2) * eigenvalues)
angle = np.degrees(np.arctan2(eigenvectors[1, 0], eigenvectors[0, 0]))
axes[1].add_patch(Ellipse(mean, width, height, angle=angle,
fill=False, edgecolor=color, linewidth=1.50))
save_svg(fig, "04_model_comparison.svg")
In Figure 4, both methods arrange groups along purchase size. Each GMM ellipse encloses 95% of the corresponding normal distribution’s probability; it is not a confidence region for the mean. Order counts are integers, so the observed points form horizontal bands. The normal approximation does not exactly follow this pattern.
Next, colors show membership probabilities for each component. Near boundaries, probability is shared across several components. We renumber groups within each model, so the same number need not refer to the same customers.
fig, axes = plt.subplots(2, 2, figsize=(9, 6.30), sharex=True, sharey=True,
layout="constrained")
for k, ax in enumerate(axes.flat):
dots = ax.scatter(Z[:, 0], Z[:, 1], c=proba[:, k], cmap="viridis",
vmin=0, vmax=1, s=8)
ax.set(title=f"成分 {k + 1}", xlabel="総支出額:対数変換・標準化後",
ylabel="注文回数:対数変換・標準化後")
fig.colorbar(dots, ax=axes, label="所属確率", format=tick3, shrink=0.800)
save_svg(fig, "05_membership_maps.svg")
# 最大の所属確率が低い顧客を1人選び、4成分への確率を確認する。
boundary = int(np.argmin(max_probability))
threshold = 0.800
pprint({"最大所属確率の中央値": sig3(np.median(max_probability)),
"最大所属確率が0.800未満の割合(%)": sig3(100 * np.mean(max_probability < threshold))})
print("分類が曖昧な1顧客の所属確率(成分1〜4)")
pprint(proba[boundary])
fig, axes = plt.subplots(1, 2, figsize=(9, 4), layout="constrained")
axes[0].hist(max_probability, bins=np.linspace(0.250, 1, 31), color=colors[0])
axes[0].axvline(threshold, color="black", linestyle="--", label="目安:0.800")
axes[0].set(xlabel="最大の所属確率", ylabel="顧客数")
axes[0].set_xticks([0.400, 0.600, 0.800, 1])
axes[0].xaxis.set_major_formatter(tick3)
axes[0].legend()
axes[1].bar(segments, proba[boundary], color=colors)
axes[1].set(xlabel="成分", ylabel="所属確率", xticks=segments, ylim=(0, 1),
title="分類が曖昧な1顧客")
axes[1].yaxis.set_major_formatter(tick3)
for k, probability in zip(segments, proba[boundary]):
axes[1].text(k, probability + 0.0250, sig3(probability), ha="center", fontsize=9)
save_svg(fig, "06_membership_uncertainty.svg")
{'最大所属確率が0.800未満の割合(%)': '20.8', '最大所属確率の中央値': '0.944'}
分類が曖昧な1顧客の所属確率(成分1〜4)
array([0.00, 0.297, 0.372, 0.331])
In Figure 6, the median maximum membership probability is 0.944, and 20.8% of customers have a maximum below 0.800. The vertical line at 0.800 is an illustrative threshold, not a general rule. These probabilities describe membership under the model, not responses to a coupon. Even a high probability does not establish a customer’s motives or values.
5. Turn the groups into ideas for marketing actions
The chapter suggests encouraging a second purchase for low-spending, mostly one-time customers, offering related categories to medium-spending repeat customers, and maintaining relationships with high-spending frequent customers. These are ideas based on observed behavior, not proven effects.
The dataset includes many wholesalers. For high-spending customers, also check whether they are businesses or individuals and what products they buy. Customers near group boundaries leave room to compare several proposals instead of assigning one action to everyone.
To test an action, randomly split customers within each segment into treatment and control groups. Compare repeat-purchase rates, gross profit, unsubscribe rates, and other relevant outcomes. If there is no difference, reconsider the action, features, or cluster count. Do not stop after drawing the clusters: check the difference between customers who received the action and those who did not.
Conclusion
This article introduced a workflow for preprocessing purchase histories, grouping customers with k-means and GMMs, and considering whom to target.
k-means summarizes differences in purchase size, while GMM membership probabilities also describe uncertainty in the assignments. Both require interpreting results in the original units and testing marketing effects separately.
Chapter 2 of the book also covers feature selection, detailed comparisons of the clusters, and descriptions of the resulting customer groups. The full implementation is available on the support page .
Data reference: D. Chen, Online Retail , UCI, 2015 (CC BY 4.0 ). We filter the book’s CSV and aggregate it by customer. The theoretical reference is C. M. Bishop, Pattern Recognition and Machine Learning, Japanese edition, Maruzen Publishing, 2012.