# -*- coding: utf-8 -*-
"""P7-2 BDS Association Rule Mining.ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1Uk4gqoyuXgyg-PkXLM8bEVdLG-W-CwAa
"""

pip install apyori

pip install mlxtend

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
#from apyori import apriori

data = pd.read_csv("/content/bread_basket.csv")
data.head()

transactions = []
# Combine items in the same transaction into one place
for i in data.Transaction.unique():
    list_trans = list(set(data[data.Transaction == i]["Item"]))
    if len(list_trans) > 0:
        transactions.append(list_trans)

print(transactions)

"""The Apriori module requires a data frame with values of 0 and 1 or True and False. Therefore, we will use One Hot Encode the data to meet the requirement of the Apriori module given by mlxtend library"""

import mlxtend
from mlxtend.preprocessing import TransactionEncoder
from mlxtend.frequent_patterns import association_rules, apriori

trans_encoding = TransactionEncoder()
df2 = trans_encoding.fit(transactions).transform(transactions)
df3 = pd.DataFrame(df2, columns=trans_encoding.columns_)

df3.head()

"""The frequent sets are found using the apriori function. We will use the min_support = 0.05 , which implies the minimum support required for an itemset to be chosen. Meanwhile,use_colnames = True keeps column names for itemsets to make them more understandable."""

frequent_set = apriori(df3, min_support = 0.05, use_colnames = True)

frequent_set

"""From these frequent sets, We want to find the association rules which determine if A is bought, then B is also purchased"""

rules = association_rules(frequent_set, metric = 'lift', min_threshold = 1)

rules

"""Conclusion:
As we can see, the results consist of two association rules only. Cake and Coffee are bought more frequently than random with the lift = 1.1 and 53% confidence.
"""

# Install required libraries
# pip install mlxtend

import pandas as pd
from mlxtend.preprocessing import TransactionEncoder
from mlxtend.frequent_patterns import apriori, association_rules

# Step 1: Load the dataset
data = pd.read_csv("/content/bread_basket.csv")
print(data.head())

# Step 2: Create a list of transactions
transactions = []
for t_id in data["Transaction"].unique():
    items = list(set(data[data["Transaction"] == t_id]["Item"]))
    if items:
        transactions.append(items)

print(f"\nTotal Transactions: {len(transactions)}")

# Step 3: Convert to one-hot encoded DataFrame
te = TransactionEncoder()
encoded_data = te.fit(transactions).transform(transactions)
df = pd.DataFrame(encoded_data, columns=te.columns_)

print("\nOne-hot encoded data sample:")
print(df.head())

# Step 4: Generate frequent itemsets using Apriori
frequent_items = apriori(df, min_support=0.05, use_colnames=True)
print("\nFrequent Itemsets:")
print(frequent_items)

# Step 5: Generate association rules
rules = association_rules(frequent_items, metric="lift", min_threshold=1)
print("\nAssociation Rules:")
print(rules[['antecedents', 'consequents', 'support', 'confidence', 'lift']])

# Step 6: Summary
print("\nConclusion:")
print("Items like Cake and Coffee are often bought together with high support and confidence.")