Apriori 基本剪枝

Python 的 Market Basket Analysis

Isaiah Hull

Visiting Associate Professor of Finance, BI Norwegian Business School

Apriori 與關聯規則

  • Apriori 會剪枝項集。
    • 套用最小支持度門檻。
    • 修改版可依項目數剪枝。
    • 不會告訴我們關聯規則。
  • 關聯規則。
    • 關聯規則遠多於項集。
    • {Bags, Boxes}:Bags -> Boxes 或 Boxes -> Bags。
Python 的 Market Basket Analysis

如何計算關聯規則

  • 由 Apriori 結果計算規則。
    • nk 很大時難以枚舉。
    • 可能抵銷 Apriori 對項集的剪枝。
  • 減少關聯規則數量。
    • mlxtend 模組提供關聯規則剪枝方法。
    • association_rules() 接受頻繁項、評估指標與門檻。
Python 的 Market Basket Analysis

如何計算關聯規則

# Import Apriori algorithm
from mlxtend.frequent_patterns import apriori, association_rules

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

# Apply Apriori algorithm
frequent_itemsets = apriori(onehot, 
                            use_colnames=True, 
                            min_support=0.0001)
# Compute association rules
rules = association_rules(frequent_itemsets,
                          metric = "support", 
                          min_threshold = 0.0)
Python 的 Market Basket Analysis

剪枝的重要性

# Print the rules.
print(rules)
                               antecedents  ... conviction
0      (CARDHOLDER GINGHAM CHRISTMAS TREE)  ...      inf
...
79505      (SET OF 3 HEART COOKIE CUTTERS)  ... 1.998496
# Print the frequent itemsets.
print(frequent_itemsets)
       support                                           itemsets
0     0.000752                   ( 50'S CHRISTMAS GIFT BAG LARGE)
...
4707  0.000752                  (PIZZA PLATE IN BOX, CHRISTMAS ...
Python 的 Market Basket Analysis

剪枝的重要性

# Compute association rules
rules = association_rules(frequent_itemsets,
                          metric = "support", 
                          min_threshold = 0.001)

# Print the rules.
print(rules)
                   antecedents      conviction  
0  (BIRTHDAY CARD, RETRO SPOT)  ...  2.977444 
1    (JUMBO BAG RED RETROSPOT)  ...  1.247180
Python 的 Market Basket Analysis

探索規則集合

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 的 Market Basket Analysis

用其他指標剪枝

# Compute association rules
rules = association_rules(frequent_itemsets,
                          metric = "antecedent support", 
                          min_threshold = 0.002)

# Print the number of rules.
print(len(rules))
3899
Python 的 Market Basket Analysis

一起來練習吧!

Python 的 Market Basket Analysis

Preparing Video For Download...