辨識關聯規則

Python 的 Market Basket Analysis

Isaiah Hull

Visiting Associate Professor of Finance, BI Norwegian Business School

載入與準備資料

import pandas as pd

# Load transactions from pandas.
books = pd.read_csv("datasets/bookstore.csv")
# Split transaction strings into lists.
transactions = books['Transaction'].apply(lambda t: t.split(','))
# Convert DataFrame into list of strings.
transactions = list(transactions)
Python 的 Market Basket Analysis

探索資料

print(transactions[:5])
[['language', 'travel', 'humor', 'fiction'],
 ['humor', 'language'],
 ['humor', 'biography', 'cooking'],
 ['cooking', 'language'],
 ['travel']]
Python 的 Market Basket Analysis

關聯規則

  • 關聯規則

    • 含前件與後件
      • {health} $\rightarrow$ {cooking}
  • 多前件規則

    • {humor, travel} $\rightarrow$ {language}
  • 多後件規則

    • {biography} $\rightarrow$ {history, language}
Python 的 Market Basket Analysis

挑選規則的難度

  • 找出有用規則不容易。

    • 所有可能規則的集合很大。
    • 多數規則沒用。
    • 必須捨棄大多數規則。
  • 若只限於簡單規則呢?

    • 一個前件配一個後件。
    • 即使資料集很小,仍具挑戰。
Python 的 Market Basket Analysis

產生規則

 

  • fiction
  • poetry
  • history
  • biography
  • cooking

 

  • health
  • travel
  • language
  • humor
Python 的 Market Basket Analysis

產生規則

Fiction 規則 Poetry 規則 ... Humor 規則
fiction->poetry poetry->fiction ... humor->fiction
fiction->history poetry->history ... humor->history
fiction->biography poetry->biography ... humor->biography
fiction->cooking poetry->cooking ... humor->cooking
... ... ... ...
fiction->humor poetry->humor ...
Python 的 Market Basket Analysis

用 itertools 產生規則

from itertools import permutations

# Extract unique items.
flattened = [item for transaction in transactions for item in transaction]
items = list(set(flattened))
# Compute and print rules.
rules = list(permutations(items, 2))
print(rules)
[('fiction', 'poetry'), 
 ('fiction', 'history'),
 ...
 ('humor', 'travel'), 
 ('humor', 'language')]
Python 的 Market Basket Analysis

統計規則數量

# Print the number of rules
print(len(rules))
72

此圖顯示規則總數隨唯一項目數變化。

Python 的 Market Basket Analysis

先睹為快

# Import the association rules function
from mlxtend.frequent_patterns import association_rules
from mlxtend.frequent_patterns import apriori

# Compute frequent itemsets using the Apriori algorithm
frequent_itemsets = apriori(onehot, min_support = 0.001, 
                            max_len = 2, use_colnames = True)

# Compute all association rules for frequent_itemsets
rules = association_rules(frequent_itemsets, 
                            metric = "lift", 
                             min_threshold = 1.0)
Python 的 Market Basket Analysis

一起來練習吧!

Python 的 Market Basket Analysis

Preparing Video For Download...