Apriori 算法

Python 中的购物篮分析

Isaiah Hull

Visiting Associate Professor of Finance, BI Norwegian Business School

项集计数

$${n \choose k} = \frac{n!}{(n-k)!k!}$$

物品数 项集大小 组合数
3461 0 1
3461 1 3461
3461 2 5,987,530
3461 3 6,903,622,090
3461 4 5,968,181,296,805
Python 中的购物篮分析

项集计数

$$\sum_{k=0}^{n}{n \choose k} = 2^{n}$$

  • $n = 3461 \rightarrow 2^{3461}$
  • $2^{3461}>>10^{82}$
  • 宇宙中的原子数:$10^{82}$。
Python 中的购物篮分析

减少项集数量

  • 无法考虑所有项集。
    • 甚至无法枚举。
  • 如何在不评估的情况下去掉项集?
    • 可设定最大 $k$。
  • Apriori 提供替代方案。
    • 无需枚举全部项集。
    • 提供合理的剪枝规则。
Python 中的购物篮分析

Apriori 原理

  • Apriori 原理。
    • 频繁集的子集也频繁。
    • 保留已知频繁的集合。
    • 剪枝不确定频繁的集合。
  • 蜡烛 = 不频繁
    • -> {蜡烛, 标牌} = 不频繁
  • {蜡烛, 标牌} = 不频繁
    • -> {蜡烛, 标牌, 盒子} = 不频繁
  • {蜡烛, 标牌, 盒子} = 不频繁
    • -> {蜡烛, 标牌, 盒子, 袋子} = 不频繁
Python 中的购物篮分析

Apriori 实现

# Import Apriori algorithm
from mlxtend.frequent_patterns import apriori

# Load one-hot encoded novelty gifts data
onehot = pd.read_csv('datasets/online_retail_onehot.csv')

# Print header.
print(onehot.head())
    50'S CHRISTMAS GIFT BAG LARGE ...  ZINC WILLIE WINKIE  CANDLE STICK  \
0                           False ...              False   
1                           False ...              False   
2                           False ...              False   
3                           False ...              False   
4                           False ...              False
Python 中的购物篮分析

Apriori 实现

# Compute frequent itemsets
frequent_itemsets = apriori(onehot, min_support = 0.0005, 
                            max_len = 4, use_colnames = True)

# Print number of itemsets
print(len(frequent_itemsets))
3652
Python 中的购物篮分析

Apriori 实现

# Print itemsets
print(frequent_itemsets.head())
      support                          itemsets
0     0.000752  ( 50'S CHRISTMAS GIFT BAG LARGE)
1     0.001504              ( DOLLY GIRL BEAKER)
...
1500  0.000752  (PING MICROWAVE APRON, FOOD CONTAINER SET 3 LO...
1501  0.000752  (WOOD 2 DRAWER CABINET WHITE FINISH, FOOD CONT...
...
Python 中的购物篮分析

Vamos praticar!

Python 中的购物篮分析

Preparing Video For Download...