关联分析 = 找"买 A 的人通常也买 B"的规则。本文是"商业分析四大算法"系列的第 2 篇,基于 UCI Online Retail II(2009-2011 英国在线零售 525,461 行),从数学到 ROI 5 层递进,所有数字均来自本机真实运行。
关联分析 3 个核心指标:
Support(X) = P(X) 项集出现概率
Confidence(X→Y) = P(Y|X) 买了X又买Y的条件概率
Lift(X→Y) = P(Y|X) / P(Y) 比随机买Y高多少倍
判定标准:
Lift > 1 值得推 (正相关)
Lift > 3 强规则 (可信营销动作)
Confidence > 0.5 规则可信
Support > 0.05 不能太小 (统计意义)
关键洞察:Lift = 1 是独立,> 1 是正相关,< 1 是负相关。**营销动作只看 Lift > 1.5**。
数据集: UCI Online Retail II (45MB xlsx, 525,461 行, 8 列, 13 个月)。
import pandas as pd
from mlxtend.preprocessing import TransactionEncoder
df = pd.read_excel("data/online_retail_II.xlsx", engine="openpyxl")
df.columns = [c.strip().replace(" ", "") for c in df.columns]
df = df.dropna(subset=["CustomerID"])
df = df[~df["InvoiceNo"].str.startswith("C")] # 去掉退货
df = df[(df["Quantity"] > 0) & (df["Price"] > 0)]
# 选高频商品 (出现 ≥100 次) 降维
top_items = df["Description"].value_counts()
top_items = top_items[top_items >= 100].index
df_top = df[df["Description"].isin(top_items)]
# 转 basket 格式
baskets = df_top.groupby("InvoiceNo")["Description"].apply(list).tolist()
te = TransactionEncoder()
oht = te.fit_transform(baskets, sparse=True)
df_encoded = pd.DataFrame.sparse.from_spmatrix(oht, columns=te.columns_)
from mlxtend.frequent_patterns import fpgrowth, apriori, association_rules
# FP-Growth (min_support=0.02)
fi = fpgrowth(df_encoded, min_support=0.02, use_colnames=True)
# 关联规则
rules = association_rules(fi, metric="lift", min_threshold=1.2)
| Antecedent | Consequent | Support | Confidence | Lift |
|---|---|---|---|---|
| HEART OF WICKER SMALL | HEART OF WICKER LARGE | 2.6% | 56.2% | 10.47 |
| HEART OF WICKER LARGE | HEART OF WICKER SMALL | 2.6% | 49.2% | 10.47 |
| LUNCH BAG SUKI DESIGN | LUNCH BAG SPACEBOY DESIGN | 2.4% | 47.6% | 9.73 |
| HOME BUILDING BLOCK WORD | LOVE BUILDING BLOCK WORD | 2.8% | 44.5% | 8.71 |
| 60 PINK PAISLEY CAKE CASES | 60 TEATIME FAIRY CAKE CASES | 2.5% | 50.4% | 8.25 |
基于真实 support/confidence 的年化收入计算:
for rule in top_10_rules:
monthly_invoices = 1430 # 18,586/13 月
affected = monthly_invoices * rule.support # 含 antecedent 的订单
additional = affected * rule.confidence # 还会买 consequent
revenue = additional * £20 * 0.30 * 12 # 年化
total += revenue
完 · 2026-08-24 · Chase's Personal Page · 100% 本机真实运行