Environment
Python 3.14.6, Polars 2.1.0, pandas 2.3.3, mlxtend 0.24.0, NumPy 2.4.6, Matplotlib 3.11.2.
Overview
Sales rankings alone do not tell us which products to place together or recommend as a pair. This article introduces Chapter 8, “Finding Co-purchase Patterns,” of Marketing Science in Theory and Practice . We examine how to extract product combinations from purchase records and interpret the results.
Following the chapter, we explain the growth in candidate combinations, Apriori and Eclat, and support, confidence, and lift. We then work through a Python implementation using public grocery purchase data.
Setup code (imports and display settings)
from pathlib import Path
from pprint import pprint
from collections import Counter
from importlib.metadata import version
from io import BytesIO
from base64 import b64encode
import platform
import numpy as np
import pandas as pd
import polars as pl
import matplotlib.pyplot as plt
import matplotlib_fontja # 日本語のフォントを設定する。
from matplotlib.colors import ListedColormap
from matplotlib.ticker import FuncFormatter, MaxNLocator, ScalarFormatter
from mlxtend.frequent_patterns import apriori, association_rules
from IPython.display import Latex, display
# Notebookのフォルダー、またはリポジトリ直下から実行できる。
BASE = Path.cwd()
if (BASE / "blog/08/08_nb.ipynb").exists():
BASE = BASE / "blog/08"
FIG_DIR = BASE / "08_nb_files"
FIG_DIR.mkdir(exist_ok=True)
def sig3(value):
"""末尾のゼロを残して、有効数字3桁で表示する。"""
return format(float(value), "#.3g").removesuffix(".")
def show_math(tex):
# 重要式は \( ... \) で記述し、出力時は $$ ... $$ に統一する。
# HTMLへの変換でも区切りが二重にならないようにする。
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を保存し、NotebookにはSVGと閲覧用PNGを埋め込む。"""
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 x, _: str(int(x)) if float(x).is_integer() else sig3(x)
))
path = FIG_DIR / filename
fig.savefig(path, format="svg", bbox_inches="tight", metadata={"Date": None})
# 未信頼のNotebookでも図を読めるよう、PNGは出力欄だけに埋め込む。
preview = BytesIO()
fig.savefig(preview, format="png", dpi=120, bbox_inches="tight")
plt.close(fig)
width = min(950, int(fig.get_figwidth() * 96))
display({
"image/svg+xml": path.read_text(),
"image/png": b64encode(preview.getvalue()).decode("ascii"),
}, raw=True, metadata={
"image/svg+xml": {"width": width},
"image/png": {"width": width},
})
np.set_printoptions(formatter={"float_kind": sig3})
pd.options.display.float_format = sig3
plt.rcParams.update({
"font.size": 11,
"axes.spines.top": False,
"axes.spines.right": False,
"axes.unicode_minus": False,
"svg.fonttype": "path",
"svg.hashsalt": "blog08",
})
BLUE, ORANGE, GRAY = "#336A91", "#B85D29", "#B5BDC4"
print("仮想環境:wa-src(3.14.6)")
print(f"Python:{platform.python_version()}")
for package in ("polars", "pandas", "mlxtend", "numpy", "matplotlib", "pyarrow"):
print(f"{package}:{version(package)}")
仮想環境:wa-src(3.14.6)
Python:3.14.6
polars:2.1.0
pandas:2.3.3
mlxtend:0.24.0
numpy:2.4.6
matplotlib:3.11.2
pyarrow:23.0.1
1. Why do we need to reduce the candidates?
We turn the goal “increase the number of products bought together” into the analytical task “choose product $Y$ to recommend with product $X$.” Association analysis first counts itemsets in shopping baskets, then builds rules of the form $X\Rightarrow Y$.
With $n$ products, there are $2^n$ subsets because each product can be included or excluded. Removing the empty set and single-product sets gives the candidate count $I_n$ for sets of two or more products. A set of $k$ products yields $2^k-2$ rules when empty antecedents and consequents are excluded. The binomial theorem also gives the total rule count $R_n$.
show_math(r"\(I_n=\sum_{k=2}^{n}\binom{n}{k}=2^n-1-n\)")
show_math(r"""
\(
\begin{aligned}
R_n&=\sum_{k=2}^{n}\binom{n}{k}(2^k-2)\\
&=\left\{\sum_{k=0}^{n}\binom{n}{k}2^k-1-2n\right\}
-2\left\{\sum_{k=0}^{n}\binom{n}{k}-1-n\right\}\\
&=\{(1+2)^n-1-2n\}-2\{(1+1)^n-1-n\}\\
&=3^n-2^{n+1}+1.
\end{aligned}
\)
""")
# 商品数を変え、候補数の増え方を対数目盛りで確認する。
n = np.arange(2, 21)
itemset_counts = 2 ** n - n - 1
rule_counts = 3 ** n - 2 ** (n + 1) + 1
print(f"商品10種類:集合の候補 {2 ** 10 - 10 - 1:,}、ルールの候補 {3 ** 10 - 2 ** 11 + 1:,}")
fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
ax.semilogy(n, itemset_counts, "o-", color=BLUE, label="商品2個以上の集合")
ax.semilogy(n, rule_counts, "s-", color=ORANGE, label="向きを区別したルール")
ax.set(xlabel="商品の種類数", ylabel="候補数(対数目盛り)",
title="図1 商品が増えると候補数が急増する")
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
ax.grid(axis="y", alpha=0.250)
ax.legend()
save_svg(fig, "01_candidates.svg")
$$ I_n=\sum_{k=2}^{n}\binom{n}{k}=2^n-1-n $$
$$ \begin{aligned} R_n&=\sum_{k=2}^{n}\binom{n}{k}(2^k-2)\\ &=\left\{\sum_{k=0}^{n}\binom{n}{k}2^k-1-2n\right\} -2\left\{\sum_{k=0}^{n}\binom{n}{k}-1-n\right\}\\ &=\{(1+2)^n-1-2n\}-2\{(1+1)^n-1-n\}\\ &=3^n-2^{n+1}+1. \end{aligned} $$
商品10種類:集合の候補 1,013、ルールの候補 57,002
Even ten products produce 57,002 rules. Examining and interpreting all of them is difficult. We therefore begin by removing infrequent itemsets to reduce the candidates.
2. Extract frequent itemsets and evaluate rules
Apriori: reduce candidates from small sets upward
Support is the number of baskets containing an itemset divided by the total number of baskets. We retain an itemset as frequent if its support meets the chosen minimum.
If products are added to set $S$ to form $U$, every basket containing $U$ must also contain $S$. Let $T(S)$ be the set of basket IDs containing $S$. The following relationship holds.
show_math(r"""
\(
\begin{aligned}
S\subseteq U&\ \Rightarrow\ T(U)\subseteq T(S)
\ \Rightarrow\ |T(U)|\leq |T(S)|,\\
\mathrm{Supp}(U)&=\frac{|T(U)|}{N}
\leq\frac{|T(S)|}{N}=\mathrm{Supp}(S).
\end{aligned}
\)
""")
# 説明用の10件。商品3が少ないので、それを含む集合も頻出にならない。
toy = [{1, 2}, {1, 2}, {3}, {1}, {2}, {4}, {5}, {6}, {7}, {8}]
candidates = [{1}, {2}, {3}, {1, 2}, {1, 3}]
supports = [sum(s <= basket for basket in toy) / len(toy) for s in candidates]
labels = ["{1}", "{2}", "{3}", "{1, 2}", "{1, 3}"]
min_support_toy = 0.200
fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
bars = ax.barh(labels, supports,
color=[BLUE if s >= min_support_toy else GRAY for s in supports])
ax.bar_label(bars, labels=[sig3(s) for s in supports], padding=4)
ax.axvline(min_support_toy, color=ORANGE, linestyle="--", label="最小支持度 0.200")
ax.invert_yaxis()
ax.set(xlim=(0, 0.390), xlabel="支持度",
title="図2 商品3を含む候補は最小支持度を満たさない")
ax.legend(loc="lower right")
save_svg(fig, "02_pruning.svg")
$$ \begin{aligned} S\subseteq U&\ \Rightarrow\ T(U)\subseteq T(S) \ \Rightarrow\ |T(U)|\leq |T(S)|,\\ \mathrm{Supp}(U)&=\frac{|T(U)|}{N} \leq\frac{|T(S)|}{N}=\mathrm{Supp}(S). \end{aligned} $$
We can therefore also discard larger candidates containing an infrequent subset. Apriori uses this property while working through one-product, two-product, and larger sets. The gray regions in Figure 2 explain support. During actual search, once product 3 is discarded, combinations containing it need not be generated.
Eclat: intersect basket IDs
Eclat stores basket IDs for each product and calculates support from their intersections. For products 1 and 2 in Figure 2, the common IDs are 1 and 2. A depth-first search extends sets and stops a branch when support falls below the minimum.
# 買い物の番号は1から始める。& は集合の共通部分を求める演算である。
tid_1 = {i for i, basket in enumerate(toy, start=1) if 1 in basket}
tid_2 = {i for i, basket in enumerate(toy, start=1) if 2 in basket}
common_ids = tid_1 & tid_2
pprint({"商品1": sorted(tid_1), "商品2": sorted(tid_2), "共通ID": sorted(common_ids)})
show_math(r"""
\(
T(\{1,2\})=\{1,2,4\}\cap\{1,2,5\}=\{1,2\},\qquad
\mathrm{Supp}(\{1,2\})=\frac{2}{10}=0.200.
\)
""")
{'共通ID': [1, 2], '商品1': [1, 2, 4], '商品2': [1, 2, 5]}
$$ T(\{1,2\})=\{1,2,4\}\cap\{1,2,5\}=\{1,2\},\qquad \mathrm{Supp}(\{1,2\})=\frac{2}{10}=0.200. $$
Eclat can reduce repeated scans of the records, but storing ID sets requires memory. The chapter considers method choice in relation to the number of products and typical basket size.
Support, confidence, and lift
Let $X$ and $Y$ be disjoint itemsets. Let $N$ be the total basket count, $n_X$ the count containing $X$, $n_Y$ the count containing $Y$, and $n_{XY}$ the count containing both. Let $A_X$ and $A_Y$ be the events that a basket contains every item in $X$ and $Y$, respectively. The combined itemset is $X\cup Y$, whereas the event that both are present is $A_X\cap A_Y$. We calculate the three measures from these counts.
show_math(r"""
\(
\begin{aligned}
\mathrm{Supp}(X\cup Y)&=\frac{n_{XY}}{N}=P(A_X\cap A_Y),\\
\mathrm{Conf}(X\Rightarrow Y)
&=\frac{\mathrm{Supp}(X\cup Y)}{\mathrm{Supp}(X)}
=\frac{n_{XY}/N}{n_X/N}
=\frac{n_{XY}}{n_X}=P(A_Y\mid A_X).
\end{aligned}
\)
""")
show_math(r"""
\(
\begin{aligned}
\mathrm{Lift}(X\Rightarrow Y)
&=\frac{\mathrm{Conf}(X\Rightarrow Y)}{\mathrm{Supp}(Y)}
=\frac{n_{XY}/n_X}{n_Y/N}\\
&=\frac{Nn_{XY}}{n_Xn_Y}
=\frac{P(A_X\cap A_Y)}{P(A_X)P(A_Y)}.
\end{aligned}
\)
""")
$$ \begin{aligned} \mathrm{Supp}(X\cup Y)&=\frac{n_{XY}}{N}=P(A_X\cap A_Y),\\ \mathrm{Conf}(X\Rightarrow Y) &=\frac{\mathrm{Supp}(X\cup Y)}{\mathrm{Supp}(X)} =\frac{n_{XY}/N}{n_X/N} =\frac{n_{XY}}{n_X}=P(A_Y\mid A_X). \end{aligned} $$
$$ \begin{aligned} \mathrm{Lift}(X\Rightarrow Y) &=\frac{\mathrm{Conf}(X\Rightarrow Y)}{\mathrm{Supp}(Y)} =\frac{n_{XY}/n_X}{n_Y/N}\\ &=\frac{Nn_{XY}}{n_Xn_Y} =\frac{P(A_X\cap A_Y)}{P(A_X)P(A_Y)}. \end{aligned} $$
Support describes scale, while confidence is the fraction of baskets containing $X$ that also contain $Y$. Popular products can have high confidence with many other products, so we also examine lift, which divides confidence by the overall purchase rate of $Y$.
Under independence, $P(A_X\cap A_Y)=P(A_X)P(A_Y)$, giving lift 1. A value above 1 indicates more co-occurrence than under independence; a value below 1 indicates less. A value above 1 alone does not establish statistical reliability or a marketing effect.
3. Analyze grocery purchases in Python
Group products into baskets
We use the same Groceries data as the chapter. From 38,765 item rows, select member number, purchase date, and product name, then group products by member and date. Remove duplicate products within each group. Because transaction IDs are unavailable, multiple shopping trips by the same member on the same day are combined. Before running the code, gzip the CSV from the data source linked at the end of this article and place it at data/Groceries data.csv.gz relative to the notebook.
raw = pl.read_csv(BASE / "data/Groceries data.csv.gz").select(
["Member_number", "Date", "itemDescription"]
)
transactions_df = raw.group_by(
["Member_number", "Date"], maintain_order=True
).agg(pl.col("itemDescription").unique(maintain_order=True).alias("items"))
transactions = transactions_df["items"].to_list()
N = len(transactions)
all_items = raw["itemDescription"].unique().sort().to_list()
print(f"商品明細:{raw.height:,}行、買い物:{N:,}件、商品:{len(all_items)}種類")
pprint(transactions[:3], width=90)
# 商品は各買い物の中で一度だけ数える。
size_counts = Counter(map(len, transactions))
item_counts = Counter(item for basket in transactions for item in basket)
top_items = item_counts.most_common(8)[::-1]
fig, axes = plt.subplots(1, 2, figsize=(11, 4.5), layout="constrained")
axes[0].bar(list(sorted(size_counts)), [size_counts[k] for k in sorted(size_counts)], color=BLUE)
axes[0].set(xlabel="1回の買い物に含む商品の種類数", ylabel="買い物件数",
title="買い物の大きさ")
axes[0].xaxis.set_major_locator(MaxNLocator(integer=True))
axes[1].barh([name for name, _ in top_items], [count / N for _, count in top_items], color=BLUE)
axes[1].set(xlabel="支持度", title="購入される割合が高い8商品")
axes[1].xaxis.set_major_locator(MaxNLocator(nbins=4))
fig.suptitle("図3 14,963件の買い物と167種類の商品")
save_svg(fig, "03_transactions.svg")
商品明細:38,765行、買い物:14,963件、商品:167種類
[['tropical fruit', 'rolls/buns', 'candy'],
['whole milk', 'tropical fruit', 'chocolate'],
['pip fruit', 'other vegetables', 'flour']]
In Figure 3, whole milk has high support at 0.158. Co-purchases involving such a popular product should not automatically be interpreted as a strong relationship.
Encode purchases and run Apriori
Create matrix $\mathbf{B}$ with baskets as rows and products as columns. Use True for a purchase and False otherwise, then convert to pandas for mlxtend. Figure 4 shows part of the matrix.
# 書籍と同じく、各商品を含むかどうかをPolarsで表す。
baskets_pl = pl.DataFrame({
item: [item in transaction for transaction in transactions]
for item in all_items
})
baskets = baskets_pl.to_pandas()
print(f"購入有無の行列:{baskets.shape[0]:,}行 × {baskets.shape[1]}列")
show_math(r"\(\mathbf{B}=(b_{ij})\in\{0,1\}^{14963\times167}\)")
preview_items = ["tropical fruit", "rolls/buns", "candy", "whole milk",
"chocolate", "other vegetables", "soda", "sausage"]
fig, ax = plt.subplots(figsize=(9, 4.5), layout="constrained")
ax.imshow(baskets[preview_items].iloc[:10].to_numpy().astype(int),
cmap=ListedColormap(["#EEF1F4", BLUE]), vmin=0, vmax=1, aspect="auto")
ax.set_xticks(range(len(preview_items)), preview_items, rotation=30, ha="right")
ax.set_yticks(range(10), range(1, 11))
ax.set(ylabel="買い物番号", title="図4 最初の10件・8商品の購入有無(青:購入あり)")
save_svg(fig, "04_purchase_matrix.svg")
購入有無の行列:14,963行 × 167列
$$ \mathbf{B}=(b_{ij})\in\{0,1\}^{14963\times167} $$
As in the chapter, the minimum support is 0.00500. With 14,963 baskets, an itemset must appear in at least 75. We obtain 126 frequent itemsets: 89 single-product sets and 37 two-product sets.
MIN_SUPPORT = 0.00500
frequent_itemsets = apriori(baskets, min_support=MIN_SUPPORT, use_colnames=True)
# 集合の中の商品名を並べ替え、再実行しても読みやすい表示にする。
def item_label(items):
return " + ".join(sorted(items))
pair_table = frequent_itemsets.loc[
frequent_itemsets["itemsets"].map(len) == 2
].copy()
pair_table["商品"] = pair_table["itemsets"].map(item_label)
pair_table = pair_table.sort_values(["support", "商品"], ascending=[False, True])
print(f"頻出アイテムセット:{len(frequent_itemsets)}個")
print(pair_table[["商品", "support"]].head().to_string(index=False, float_format=sig3))
# 最小支持度を変えて、残る集合の数を比較する。
thresholds = [0.00250, 0.00500, 0.0100, 0.0200]
counts = []
for threshold in thresholds:
found = apriori(baskets, min_support=threshold, use_colnames=True)
sizes = found["itemsets"].map(len)
counts.append((int((sizes == 1).sum()), int((sizes >= 2).sum())))
single_counts, multiple_counts = np.array(counts).T
fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
positions = np.arange(len(thresholds))
ax.bar(positions, single_counts, color=BLUE, label="商品1個")
bars = ax.bar(positions, multiple_counts, bottom=single_counts,
color=ORANGE, label="商品2個以上")
ax.bar_label(bars, labels=[str(a + b) for a, b in counts], padding=4)
ax.set_xticks(positions, [sig3(value) for value in thresholds])
ax.set(xlabel="最小支持度", ylabel="頻出アイテムセット数", ylim=(0, 310),
title="図5 支持度の下限を上げると残る集合が減る")
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
ax.legend()
save_svg(fig, "05_support_threshold.svg")
頻出アイテムセット:126個
商品 support
other vegetables + whole milk 0.0148
rolls/buns + whole milk 0.0140
soda + whole milk 0.0116
whole milk + yogurt 0.0112
other vegetables + rolls/buns 0.0106
In Figure 5, a minimum of 0.0200 removes all sets with two or more products. Higher thresholds miss smaller combinations; lower thresholds leave more candidates to inspect. Choose the threshold according to the number of baskets and the feasible scale of an action.
Generate rules and read the results
Following the chapter, generate rules with confidence at least 0.0200 and retain those with lift at least 1. Six of 74 rules remain. Combining opposite directions leaves three product pairs.
all_rules = association_rules(
frequent_itemsets, metric="confidence", min_threshold=0.0200
)
rules = all_rules.loc[all_rules["lift"] >= 1].copy()
rules["ルール"] = (
rules["antecedents"].map(item_label) + " → " + rules["consequents"].map(item_label)
)
rules = rules.sort_values(["support", "confidence", "lift", "ルール"],
ascending=[False, False, False, True])
print(f"確信度で抽出:{len(all_rules)}件、リフト値で絞った後:{len(rules)}件")
print(rules[["ルール", "support", "confidence", "lift"]].to_string(
index=False, float_format=sig3
))
# リフト値は向きを逆にしても同じなので、右図では1組につき1回描く。
rules["組"] = [
" / ".join(sorted(a | b))
for a, b in zip(rules["antecedents"], rules["consequents"])
]
unique_pairs = rules.drop_duplicates("組").sort_values("lift")
fig, axes = plt.subplots(1, 2, figsize=(11, 4.5), layout="constrained")
axes[0].scatter(all_rules["confidence"], all_rules["lift"], color=GRAY,
s=35, label="確信度で抽出した74件")
axes[0].scatter(rules["confidence"], rules["lift"], color=BLUE,
s=40, label="リフト値1以上の6件")
axes[0].axhline(1, color=ORANGE, linestyle="--")
axes[0].set(xlabel="確信度", ylabel="リフト値", title="全ルールの位置")
axes[0].xaxis.set_major_locator(MaxNLocator(nbins=4))
axes[0].legend(loc="lower right", fontsize=9)
bars = axes[1].barh(unique_pairs["組"], unique_pairs["lift"], color=BLUE)
axes[1].bar_label(bars, labels=[sig3(x) for x in unique_pairs["lift"]], padding=4)
axes[1].axvline(1, color=ORANGE, linestyle="--")
axes[1].set(xlim=(0, 1.30), xlabel="リフト値", title="絞り込み後の3組")
fig.suptitle("図6 確信度の高さとリフト値の高さを分けて確認する")
save_svg(fig, "06_rules.svg")
確信度で抽出:74件、リフト値で絞った後:6件
ルール support confidence lift
sausage → soda 0.00595 0.0986 1.01
soda → sausage 0.00595 0.0613 1.01
sausage → yogurt 0.00575 0.0952 1.11
yogurt → sausage 0.00575 0.0669 1.11
frankfurter → other vegetables 0.00515 0.136 1.12
other vegetables → frankfurter 0.00515 0.0421 1.12
We verify the chapter’s sausage-to-soda rule using the original counts. There are 903 baskets containing sausage, 1,453 containing soda, and 89 containing both.
x = baskets["sausage"]
y = baskets["soda"]
n_x, n_y, n_xy = int(x.sum()), int(y.sum()), int((x & y).sum())
support = n_xy / N
confidence = n_xy / n_x
baseline = n_y / N
lift = confidence / baseline
reverse_confidence = n_xy / n_y
pprint({"全件数": N, "sausage": n_x, "soda": n_y, "両方": n_xy})
# 分母・分子は元の整数のまま計算し、表示時だけ丸める。
show_math(rf"""
\(
\begin{{aligned}}
\mathrm{{Supp}}&=\frac{{{n_xy}}}{{{N}}}\approx {sig3(support)},\\
\mathrm{{Conf}}&=\frac{{{n_xy}/{N}}}{{{n_x}/{N}}}
=\frac{{{n_xy}}}{{{n_x}}}\approx {sig3(confidence)},\\
\mathrm{{Lift}}&=\frac{{{n_xy}/{n_x}}}{{{n_y}/{N}}}
=\frac{{{n_xy}\times {N}}}{{{n_x}\times {n_y}}}\approx {sig3(lift)}.
\end{{aligned}}
\)
""")
fig, axes = plt.subplots(1, 2, figsize=(10, 4), layout="constrained")
values = [100 * baseline, 100 * confidence]
bars = axes[0].bar(["全体", "sausageあり"], values, color=[GRAY, BLUE])
axes[0].bar_label(bars, labels=[sig3(v) for v in values], padding=4)
axes[0].set(ylim=(0, 12), ylabel="sodaを含む割合(%)", title="9.71%と9.86%の比較")
values = [100 * confidence, 100 * reverse_confidence]
bars = axes[1].bar(["sausage → soda", "soda → sausage"], values, color=[BLUE, ORANGE])
axes[1].bar_label(bars, labels=[sig3(v) for v in values], padding=4)
axes[1].set(ylim=(0, 12), ylabel="確信度(%)", title="ルールの向きで分母が変わる")
fig.suptitle("図7 併買89件から割合を計算する")
save_svg(fig, "07_rule_interpretation.svg")
{'sausage': 903, 'soda': 1453, '両方': 89, '全件数': 14963}
$$ \begin{aligned} \mathrm{Supp}&=\frac{89}{14963}\approx 0.00595,\\ \mathrm{Conf}&=\frac{89/14963}{903/14963} =\frac{89}{903}\approx 0.0986,\\ \mathrm{Lift}&=\frac{89/903}{1453/14963} =\frac{89\times 14963}{903\times 1453}\approx 1.01. \end{aligned} $$
Overall, 9.71% of baskets contain soda, compared with 9.86% of baskets containing sausage. Lift is 1.01, indicating a weak association. Reverse confidence is 6.13%, but lift is unchanged. Figure 7 makes the different comparison groups and denominators explicit.
To test this rule, target users who have sausage in their basket but have not yet added soda. The observed difference alone does not show that sales will increase. When proposing the action, show the number of relevant baskets alongside the rule measures.
Conclusion
This article explained how Apriori and Eclat reduce co-purchase candidates, how three measures evaluate them, and how to reproduce the chapter’s analysis in Python.
Association rules suggest actions; they do not establish causality. Randomly assign users to recommendation and no-recommendation groups and compare item counts and profit after costs. Set the evaluation period and criteria in advance, then decide whether to expand, revise, or stop the action.
The book covers the workflow from framing the question to testing actions. Its support page includes the full chapter code and implementations of Apriori and Eclat without relying on these libraries.
Data reference: Rashik Rahman, Groceries dataset for Market Basket Analysis (MBA) , Version 2. The CSV identified as CC0 in the chapter is compressed without modification for distribution with the book.