Визначення правил асоціацій

Маркет-баcкет аналіз у 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)
Маркет-баcкет аналіз у Python

Дослідження даних

print(transactions[:5])
[['language', 'travel', 'humor', 'fiction'],
 ['humor', 'language'],
 ['humor', 'biography', 'cooking'],
 ['cooking', 'language'],
 ['travel']]
Маркет-баcкет аналіз у Python

Правила асоціацій

  • Правило асоціації

    • Містить антецедент і консеквент
      • {health} $\rightarrow$ {cooking}
  • Правило з кількома антецедентами

    • {humor, travel} $\rightarrow$ {language}
  • Правило з кількома консеквентами

    • {biography} $\rightarrow$ {history, language}
Маркет-баcкет аналіз у Python

Складність вибору правил

  • Знайти корисні правила складно.

    • Можливих правил дуже багато.
    • Більшість правил некорисні.
    • Потрібно відкидати більшість правил.
  • А якщо обмежитись простими правилами?

    • Один антецедент і один консеквент.
    • Все одно складно, навіть для малого набору даних.
Маркет-баcкет аналіз у Python

Генерування правил

 

  • fiction
  • poetry
  • history
  • biography
  • cooking

 

  • health
  • travel
  • language
  • humor
Маркет-баcкет аналіз у Python

Генерування правил

Правила для 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 ...
Маркет-баcкет аналіз у 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')]
Маркет-баcкет аналіз у Python

Підрахунок правил

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

Графік показує загальну кількість правил залежно від кількості унікальних елементів.

Маркет-баcкет аналіз у 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)
Маркет-баcкет аналіз у Python

Давайте потренуємось!

Маркет-баcкет аналіз у Python

Preparing Video For Download...