Apriori
import pandas as pd
\n", "
from mlxtend.frequent_patterns import apriori, association_rules
\n",
"from mlxtend.preprocessing import TransactionEncoder\n",
"\ n", "\n", "
Step 1: Read the data\n",
"transactions = [['eggs', 'milk','bread'],\n", "['eggs', 'apple'],\n", "['milk', 'bread'],\n", "['apple', 'milk'],\n", "['milk', 'apple', 'bread']]
\n", "\n", "\n", "\n", "
step 2: Encode the data\n", "te=TransactionEncoder()\n", "te_array=te.fit(transactions).transform(transactions)
\n",
"df=pd.DataFrame(te_array, columns=te.columns_)
\n",
"df
\n", "\n", "\n", "\n", "
Step 3: Find the frequent itemsets \n", "
freq_items = apriori(df, min_support = 0.5, use_colnames = True)
\n", "
print(freq_items)
\n", "\n", "\n", "\n", "
Step 4: Generate the association rules \n", "
rules = association_rules(freq_items, metric ='support', min_threshold=0.05)
\n", "
rules = rules.sort_values(['support', 'confidence'], ascending =[False,False])
print(rules)