什麼是購物籃分析?

Python 的 Market Basket Analysis

Isaiah Hull

Visiting Associate Professor of Finance, BI Norwegian Business School

選擇書店動線配置

 

此圖顯示書店動線:將小說與傳記分在一區,詩集與歷史分在一區。

 

此圖顯示書店動線:將小說與詩集分在一區,傳記與歷史分在一區。

Python 的 Market Basket Analysis

探索交易資料

TID Transaction
1 biography, history
2 fiction
3 biography, poetry
4 fiction, history
5 biography
... ...
75000 fiction, poetry

 

  • TID = 每筆交易的唯一 ID。

 

  • Transaction = 一起購買的獨特品項集合。
Python 的 Market Basket Analysis

什麼是購物籃分析?

  1. 找出常被一起購買的商品。

    • 傳記與歷史
    • 小說與詩集
  2. 根據結果提出建議。

    • 將傳記與歷史區放在一起。
    • 小說與歷史區分開。
Python 的 Market Basket Analysis

購物籃分析的應用情境

  1. 建立 Netflix 風格的推薦引擎。
  2. 提升電商商品推薦。
  3. 零售情境的交叉銷售。
  4. 改善庫存管理。
  5. 進一步加購(upsell)。
Python 的 Market Basket Analysis

運用購物籃分析

TID Transaction
11 fiction, biography
12 fiction, biography
13 history, biography
... ...
19 fiction, biography
20 fiction, biography
... ...
  • 購物籃分析
    • 建立關聯規則
    • 找出常被一起購買的品項
  • 關聯規則
    • {前件} $\rightarrow$ {後件}
      • {fiction} $\rightarrow$ {biography}
Python 的 Market Basket Analysis

載入資料

import pandas as pd

# Load transactions from pandas.
books = pd.read_csv("datasets/bookstore.csv")

# Print the header
print(books.head(2))
TID         Transaction                 
0    biography, history
1               fiction

若需要複習,請參考 Pandas Cheat Sheet

Python 的 Market Basket Analysis

建立交易記錄

 

# 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 the first transaction.
print(transactions[0])
['biography', 'history']
# Count the number of transactions that contain biography and fiction.
transactions.count(['biography', 'fiction'])
218
Python 的 Market Basket Analysis

提出建議

# Count the number of transactions that contain fiction and poetry.
transactions.count(['fiction', 'poetry'])
5357

此圖顯示書店動線:將小說與詩集分在一區,傳記與歷史分在一區。

Python 的 Market Basket Analysis

一起來練習吧!

Python 的 Market Basket Analysis

Preparing Video For Download...