Python 中的购物篮分析
Isaiah Hull
Visiting Associate Professor of Finance, BI Norwegian Business School
mlxtend 模块提供规则剪枝方法。association_rules() 传入频繁项、指标和阈值。# 导入 Apriori 算法
from mlxtend.frequent_patterns import apriori, association_rules
# 读取独热编码的新奇礼品数据
onehot = pd.read_csv('datasets/online_retail_onehot.csv')
# 应用 Apriori 算法
frequent_itemsets = apriori(onehot,
use_colnames=True,
min_support=0.0001)
# 计算关联规则
rules = association_rules(frequent_itemsets,
metric = "support",
min_threshold = 0.0)
# 打印规则
print(rules)
antecedents ... conviction
0 (CARDHOLDER GINGHAM CHRISTMAS TREE) ... inf
...
79505 (SET OF 3 HEART COOKIE CUTTERS) ... 1.998496
# 打印频繁项集
print(frequent_itemsets)
support itemsets
0 0.000752 ( 50'S CHRISTMAS GIFT BAG LARGE)
...
4707 0.000752 (PIZZA PLATE IN BOX, CHRISTMAS ...
# 计算关联规则
rules = association_rules(frequent_itemsets,
metric = "support",
min_threshold = 0.001)
# 打印规则
print(rules)
antecedents conviction
0 (BIRTHDAY CARD, RETRO SPOT) ... 2.977444
1 (JUMBO BAG RED RETROSPOT) ... 1.247180
print(rules.columns)
Index(['antecedents', 'consequents', 'antecedent support',
'consequent support', 'support', 'confidence', 'lift', 'leverage',
'conviction'],
dtype='object')
print(rules[['antecedents','consequents']])
antecedents consequents
0 (JUMBO BAG RED RETROSPOT) (BIRTHDAY CARD, RETRO SPOT)
1 (BIRTHDAY CARD, RETRO SPOT) (JUMBO BAG RED RETROSPOT)
# 计算关联规则
rules = association_rules(frequent_itemsets,
metric = "antecedent support",
min_threshold = 0.002)
# 打印规则数量
print(len(rules))
3899
Python 中的购物篮分析