识别关联规则

Python 中的购物篮分析

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

探索数据

print(transactions[:5])
[['language', 'travel', 'humor', 'fiction'],
 ['humor', 'language'],
 ['humor', 'biography', 'cooking'],
 ['cooking', 'language'],
 ['travel']]
Python 中的购物篮分析

关联规则

  • 关联规则

    • 包含前件与后件
      • {health} $\rightarrow$ {cooking}
  • 多前件规则

    • {humor, travel} $\rightarrow$ {language}
  • 多后件规则

    • {biography} $\rightarrow$ {history, language}
Python 中的购物篮分析

选择规则的难点

  • 找到有用的规则很难。

    • 所有可能规则的集合很大。
    • 大多规则无用。
    • 必须舍弃大部分规则。
  • 若仅限于简单规则会怎样?

    • 一个前件和一个后件。
    • 即使小数据集也不易。
Python 中的购物篮分析

生成规则

 

  • fiction
  • poetry
  • history
  • biography
  • cooking

 

  • health
  • travel
  • language
  • humor
Python 中的购物篮分析

生成规则

小说 规则 诗歌 规则 ... 幽默 规则
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 中的购物篮分析

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

统计规则数量

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

该图显示规则总数随唯一项数量的变化。

Python 中的购物篮分析

前瞻

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

开始练习!

Python 中的购物篮分析

Preparing Video For Download...