Apriori 基础剪枝结果

Python 中的购物篮分析

Isaiah Hull

Visiting Associate Professor of Finance, BI Norwegian Business School

Apriori 与关联规则

  • Apriori 会剪枝项集。
    • 应用最小支持度阈值。
    • 变体可按项数剪枝。
    • 不涉及关联规则。
  • 关联规则。
    • 规则远多于项集。
    • {Bags, Boxes}:Bags -> Boxes 或 Boxes -> Bags。
Python 中的购物篮分析

如何计算关联规则

  • 从 Apriori 结果生成规则。
    • nk 很大时难以枚举。
    • 可能抵消 Apriori 的项集剪枝。
  • 减少关联规则数量。
    • mlxtend 模块提供规则剪枝方法。
    • association_rules() 传入频繁项、指标和阈值。
Python 中的购物篮分析

如何计算关联规则

# 导入 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)
Python 中的购物篮分析

剪枝的重要性

# 打印规则
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 ...
Python 中的购物篮分析

剪枝的重要性

# 计算关联规则
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
Python 中的购物篮分析

探索规则集

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)
Python 中的购物篮分析

用其他指标剪枝

# 计算关联规则
rules = association_rules(frequent_itemsets,
                          metric = "antecedent support", 
                          min_threshold = 0.002)

# 打印规则数量
print(len(rules))
3899
Python 中的购物篮分析

Passons à la pratique !

Python 中的购物篮分析

Preparing Video For Download...