연관 규칙 식별

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

규칙 선택의 어려움

  • 유용한 규칙 찾기는 어렵습니다.

    • 가능한 규칙 집합이 큽니다.
    • 대부분의 규칙은 유용하지 않습니다.
    • 대부분을 걸러내야 합니다.
  • 단순한 규칙으로 제한하면 어떨까요?

    • 선행 1개, 후행 1개.
    • 작은 데이터셋에도 여전히 도전적입니다.
Python으로 배우는 Market Basket Analysis

규칙 생성

 

  • fiction
  • poetry
  • history
  • biography
  • cooking

 

  • health
  • travel
  • language
  • humor
Python으로 배우는 Market Basket Analysis

규칙 생성

소설 규칙 시 규칙 ... 유머 규칙
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...