新闻详情

新闻详情

首页 / 资讯中心 / 详情

Python Apriori 算法实战:购物篮分析 3 指标(支持度/置信度/提升度)代码实现

发布时间:2026/7/8 22:55:12
Python Apriori 算法实战:购物篮分析 3 指标(支持度/置信度/提升度)代码实现
Python Apriori 算法实战购物篮分析 3 指标支持度/置信度/提升度代码实现在零售行业理解顾客的购买行为模式是提升销售的关键。想象一下当你走进一家超市为什么啤酒和尿布总是摆在一起这背后隐藏着怎样的商业智慧本文将带你用Python从零实现经典的Apriori算法通过支持度、置信度和提升度三个核心指标揭开商品关联分析的神秘面纱。1. 购物篮分析基础与核心指标购物篮分析Market Basket Analysis是零售行业最常用的数据分析技术之一它通过挖掘顾客购买商品之间的关联关系帮助商家优化商品陈列、制定捆绑销售策略。这项技术的经典案例就是著名的啤酒与尿布故事——沃尔玛通过数据分析发现购买尿布的年轻父亲们经常会顺便购买啤酒。1.1 核心指标解析购物篮分析主要依赖三个核心指标支持度Support衡量商品组合出现的频率支持度 同时包含A和B的订单数 / 总订单数置信度Confidence衡量购买A后也购买B的条件概率置信度 同时包含A和B的订单数 / 包含A的订单数提升度Lift衡量A对B购买概率的提升程度提升度 支持度 / ( (包含A的订单数/总订单数) × (包含B的订单数/总订单数) )1.2 指标应用场景对比指标计算方式商业意义阈值判断标准支持度P(A∩B)商品组合的普遍性越高越好置信度P(BA) P(A∩B)/P(A)购买A后购买B的可能性提升度P(A∩B)/(P(A)×P(B))组合销售效果相比单独销售的提升程度1表示有效组合提示在实际业务中提升度1的组合才值得关注表示商品间存在正相关关系。提升度1表示独立1则表示负相关。2. 数据准备与预处理2.1 模拟数据集生成为了演示完整的分析流程我们先创建一个模拟的零售交易数据集import pandas as pd from itertools import combinations # 生成模拟交易数据 transactions [ [牛奶, 面包, 尿布], [可乐, 面包, 尿布, 啤酒], [牛奶, 尿布, 啤酒, 鸡蛋], [面包, 牛奶, 尿布, 啤酒], [面包, 牛奶, 尿布, 可乐] ] # 转换为DataFrame格式 df pd.DataFrame(transactions) print(原始交易数据示例) print(df.head())2.2 数据预处理关键步骤原始交易数据需要转换为适合Apriori算法的格式独热编码转换from mlxtend.preprocessing import TransactionEncoder te TransactionEncoder() te_ary te.fit(transactions).transform(transactions) df_encoded pd.DataFrame(te_ary, columnste.columns_) print(\n独热编码后的数据) print(df_encoded.head())频繁项集统计# 统计单项出现频率 item_counts df_encoded.sum().sort_values(ascendingFalse) print(\n商品出现频率) print(item_counts)3. Apriori算法实现3.1 算法核心思想Apriori算法基于先验原理如果一个项集是频繁的那么它的所有子集也一定是频繁的。这种自上而下的搜索策略大大减少了需要计算的项集数量。算法流程找出所有频繁1项集基于频繁k项集生成候选k1项集剪枝去除支持度低于阈值的候选重复步骤2-3直到不能生成更大的频繁项集3.2 Python完整实现from collections import defaultdict def apriori(df, min_support0.5): Apriori算法实现 # 初始化 itemsets [frozenset([i]) for i in df.columns] freq_itemsets [] k 1 while itemsets: # 计算支持度 support_counts defaultdict(int) for _, row in df.iterrows(): for itemset in itemsets: if itemset.issubset(row[row1].index): support_counts[itemset] 1 # 筛选频繁项集 freq_items [itemset for itemset in itemsets if support_counts[itemset]/len(df) min_support] freq_itemsets.extend(freq_items) # 生成下一轮候选项集 itemsets set() for i in range(len(freq_items)): for j in range(i1, len(freq_items)): new_itemset freq_items[i] | freq_items[j] if len(new_itemset) k1: itemsets.add(new_itemset) itemsets list(itemsets) k 1 return freq_itemsets, support_counts # 运行算法 min_support 0.4 freq_itemsets, support_counts apriori(df_encoded, min_support) print(\n频繁项集支持度≥{}.format(min_support)) for itemset in freq_itemsets: print(itemset, 支持度:, support_counts[itemset]/len(df_encoded))4. 关联规则挖掘与指标计算4.1 从频繁项集生成规则def generate_rules(freq_itemsets, support_counts, min_confidence0.7): 生成关联规则并计算指标 rules [] for itemset in freq_itemsets: if len(itemset) 1: for antecedent in combinations(itemset, len(itemset)-1): antecedent frozenset(antecedent) consequent itemset - antecedent support support_counts[itemset] / len(df_encoded) confidence support_counts[itemset] / support_counts[antecedent] # 计算提升度 consequent_support support_counts[consequent] / len(df_encoded) lift confidence / consequent_support if confidence min_confidence: rules.append({ rule: f{antecedent} → {consequent}, support: round(support, 3), confidence: round(confidence, 3), lift: round(lift, 3) }) return rules # 生成关联规则 rules generate_rules(freq_itemsets, support_counts, min_confidence0.6) rules_df pd.DataFrame(rules) print(\n关联规则) print(rules_df.sort_values(lift, ascendingFalse))4.2 结果可视化分析import matplotlib.pyplot as plt import seaborn as sns # 绘制规则热力图 pivot_table rules_df.pivot(indexrule, columnsmetric, valuesvalue) plt.figure(figsize(10, 6)) sns.heatmap(pivot_table, annotTrue, cmapYlGnBu, fmt.2f) plt.title(关联规则指标热力图) plt.tight_layout() plt.show()5. 实战应用与策略建议5.1 商业决策支持基于我们的分析结果可以得出以下商业策略商品陈列优化将尿布和啤酒摆放在相邻位置提升度2.4牛奶和面包组合展示支持度60%捆绑销售策略推出尿布啤酒优惠套餐牛奶面包早餐组合促销库存管理当尿布库存不足时提前预警啤酒可能需要补货根据牛奶销售预测调整面包采购量5.2 性能优化技巧当处理大规模零售数据时可以采用以下优化策略并行计算from joblib import Parallel, delayed def parallel_apriori(df, min_support, n_jobs4): 并行化Apriori实现 # 实现略...FP-Growth算法替代from mlxtend.frequent_patterns import fpgrowth # 使用FP-Growth算法 freq_itemsets fpgrowth(df_encoded, min_support0.4, use_colnamesTrue)内存优化使用稀疏矩阵存储交易数据分批处理大规模数据集6. 扩展应用与进阶思考购物篮分析不仅适用于零售行业还可以应用于电商推荐系统购买了X商品的顾客也购买了Y基于关联规则的交叉销售医疗诊断症状与疾病的关联分析药物组合使用模式挖掘网络安全异常行为模式检测攻击特征关联分析实际项目中我曾遇到一个有趣的案例一家连锁超市通过购物篮分析发现高端红酒和高级奶酪的购买组合在工作日晚上特别频繁。进一步调查发现这源于附近办公楼的白领们下班后的购物习惯。超市于是调整了这两类商品的陈列位置并在每周四晚上推出品酒活动使这两类商品的联合销售额提升了35%。
网站建设 高端定制 企业官网