0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

(Apriori)とアソシエーションルール

Posted at
# Program Name: market_basket_analysis.py  
# Creation Date: 20250606  
# Overview: Perform market basket analysis using Apriori and visualize association rules  
# Usage: Run in Python (Jupyter/Colab) with mlxtend, matplotlib, pandas installed

# -------------------- Install Required Libraries --------------------
!pip install pandas mlxtend matplotlib seaborn --quiet

# -------------------- Import Libraries --------------------
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from mlxtend.preprocessing import TransactionEncoder
from mlxtend.frequent_patterns import apriori, association_rules

# -------------------- Parameters / 取引データ --------------------
# 仮想的な顧客購入履歴 / Sample transactions
dataset = [
    ['milk', 'bread', 'butter'],
    ['bread', 'diaper', 'beer', 'eggs'],
    ['milk', 'bread', 'diaper', 'beer'],
    ['milk', 'bread', 'diaper', 'butter'],
    ['bread', 'butter']
]

# -------------------- Step 1: データのバイナリ化 / Encode the dataset --------------------
te = TransactionEncoder()
te_ary = te.fit(dataset).transform(dataset)
df = pd.DataFrame(te_ary, columns=te.columns_)

# -------------------- Step 2: 頻出アイテムセット抽出 / Extract Frequent Itemsets --------------------
frequent_itemsets = apriori(df, min_support=0.4, use_colnames=True)

# -------------------- Step 3: アソシエーションルールの抽出 / Derive Association Rules --------------------
rules = association_rules(frequent_itemsets, metric="lift", min_threshold=1.0)

# -------------------- Step 4: ルール上位表示 / Display Top Rules --------------------
print(rules[['antecedents', 'consequents', 'support', 'confidence', 'lift']].sort_values(by='lift', ascending=False))

# -------------------- Step 5: プロット(Lift vs Confidence) --------------------
plt.figure(figsize=(8, 6))
sns.scatterplot(data=rules, x='confidence', y='lift', size='support', hue='support', palette='viridis', sizes=(100, 1000), legend=False)

# 英語表記 / Plot labels in English
plt.title('Association Rules: Lift vs Confidence')
plt.xlabel('Confidence')
plt.ylabel('Lift')
plt.grid(True)
plt.show()

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?