Nhận diện luật kết hợp

Phân tích giỏ hàng trong Python

Isaiah Hull

Visiting Associate Professor of Finance, BI Norwegian Business School

Tải và chuẩn bị dữ liệu

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)
Phân tích giỏ hàng trong Python

Khám phá dữ liệu

print(transactions[:5])
[['language', 'travel', 'humor', 'fiction'],
 ['humor', 'language'],
 ['humor', 'biography', 'cooking'],
 ['cooking', 'language'],
 ['travel']]
Phân tích giỏ hàng trong Python

Luật kết hợp

  • Luật kết hợp

    • Gồm tiền đề và kết quả
      • {sức khỏe} $\rightarrow$ {nấu ăn}
  • Luật nhiều tiền đề

    • {hài hước, du lịch} $\rightarrow$ {ngôn ngữ}
  • Luật nhiều kết quả

    • {tiểu sử} $\rightarrow$ {lịch sử, ngôn ngữ}
Phân tích giỏ hàng trong Python

Khó khăn khi chọn luật

  • Tìm luật hữu ích là khó.

    • Tập luật khả dĩ rất lớn.
    • Phần lớn không hữu ích.
    • Cần loại bỏ hầu hết.
  • Nếu chỉ xét luật đơn giản thì sao?

    • Một tiền đề và một kết quả.
    • Vẫn khó, ngay cả với dữ liệu nhỏ.
Phân tích giỏ hàng trong Python

Tạo luật

 

  • tiểu thuyết
  • thơ
  • lịch sử
  • tiểu sử
  • nấu ăn

 

  • sức khỏe
  • du lịch
  • ngôn ngữ
  • hài hước
Phân tích giỏ hàng trong Python

Tạo luật

Luật Tiểu thuyết Luật Thơ ... Luật Hài hước
tiểu thuyết->thơ thơ->tiểu thuyết ... hài hước->tiểu thuyết
tiểu thuyết->lịch sử thơ->lịch sử ... hài hước->lịch sử
tiểu thuyết->tiểu sử thơ->tiểu sử ... hài hước->tiểu sử
tiểu thuyết->nấu ăn thơ->nấu ăn ... hài hước->nấu ăn
... ... ... ...
tiểu thuyết->hài hước thơ->hài hước ...
Phân tích giỏ hàng trong Python

Tạo luật với 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')]
Phân tích giỏ hàng trong Python

Đếm số luật

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

Biểu đồ cho thấy tổng số luật theo số lượng mục duy nhất.

Phân tích giỏ hàng trong Python

Nhìn trước

# 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)
Phân tích giỏ hàng trong Python

Ayo berlatih!

Phân tích giỏ hàng trong Python

Preparing Video For Download...