
Image by Author
You run an online bookstore with 500 titles and 50,000 customer transactions. Calculating metrics for every possible book combination means evaluating over 124,000 potential rules. Even with Python, checking every combination gets expensive fast.
This is where the Apriori algorithm comes in. Instead of checking every possible combination, Apriori uses a simple strategy: if a set of items appears rarely, any larger set containing those items will be even rarer. This allows the algorithm to skip large portions of the search space.
This guide shows you how to use Python’s mlxtend library to find frequent itemsets automatically, turning weeks of computation into seconds.
Understanding the Apriori Approach
The Apriori algorithm solves a practical problem. When you have thousands of products and transactions, manually calculating which items appear together becomes impossible. The algorithm finds “frequent itemsets,” which are groups of items that appear together often enough to matter.
Here’s the key insight: if individual items rarely appear, combinations containing those items will be even rarer. Apriori drops these unlikely combinations early, focusing computational effort on patterns that actually exist in your data.
You control what counts as “frequent” through a minimum support threshold. This threshold filters out noise and rare combinations, leaving you with patterns worth examining. Setting support at 0.05 means an itemset must appear in at least 5% of transactions to be considered frequent.
Preparing Your Data for Apriori
The Apriori algorithm needs data in a specific format called one-hot encoding. Each row represents a transaction, and each column represents a product. The value is True if that product appeared in the transaction, False otherwise.
import pandas as pd
from mlxtend.preprocessing import TransactionEncoder
from mlxtend.frequent_patterns import apriori
# Bookstore transaction data: 25 transactions across multiple titles
transactions = [
['Harry Potter', 'Hunger Games'],
['Hunger Games', 'Divergent'],
['Harry Potter', 'Twilight'],
['Divergent', 'Hunger Games', 'Twilight'],
['Harry Potter', 'Hunger Games', 'Percy Jackson'],
['Lord of the Rings', 'Hobbit'],
['1984', 'Brave New World'],
['Harry Potter', 'Lord of the Rings'],
['Hunger Games', 'Twilight'],
['Divergent', 'Maze Runner'],
['Harry Potter', 'Hunger Games'],
['Twilight', 'Vampire Academy'],
['Lord of the Rings', 'Hobbit', 'Game of Thrones'],
['Harry Potter', 'Divergent'],
['Hunger Games', 'Divergent'],
['1984', 'Animal Farm'],
['Harry Potter', 'Hunger Games', 'Twilight'],
['Lord of the Rings', 'Silmarillion'],
['Divergent', 'Hunger Games'],
['Harry Potter', 'Percy Jackson'],
['Twilight', 'Hunger Games'],
['Lord of the Rings', 'Hobbit'],
['Harry Potter', 'Hunger Games'],
['Divergent', 'Insurgent'],
['Harry Potter', 'Twilight', 'Hunger Games']
]
# Convert to one-hot encoded format
encoder = TransactionEncoder()
onehot_array = encoder.fit_transform(transactions)
onehot_df = pd.DataFrame(onehot_array, columns=encoder.columns_)
print(f"Dataset shape: {onehot_df.shape}")
print("\nFirst 5 transactions:")
print(onehot_df.head())
This creates a DataFrame where True means a book was purchased in that transaction, and False means it wasn’t. The output shows 25 transactions across 15 unique book titles. This one-hot encoded format is the same structure used when calculating support, confidence, and lift manually, though here we’re working with a larger dataset.
Output:
Dataset shape: (25, 15) First 5 transactions:
Finding Frequent Itemsets
Now you can apply the Apriori algorithm with a minimum support threshold. Starting with 0.05 means you’re looking for itemsets that appear in at least 5% of transactions (at least 2 transactions in our 25-transaction dataset).
# Apply Apriori algorithm with minimum support threshold
frequent_itemsets = apriori(onehot_df, min_support=0.05, use_colnames=True)
print(f"Found {len(frequent_itemsets)} frequent itemsets")
print("\nAll itemsets sorted by support:")
print(frequent_itemsets.sort_values('support', ascending=False).reset_index(drop=True))
The algorithm identifies all itemsets that meet the support threshold. The results show both individual popular books and combinations that appear frequently together.
Output:
Found 15 frequent itemsets
All itemsets sorted by support:
support itemsets
0 0.48 (Hunger Games)
1 0.40 (Harry Potter)
2 0.28 (Divergent)
3 0.28 (Twilight)
4 0.24 (Harry Potter, Hunger Games)
5 0.20 (Lord of the Rings)
6 0.20 (Hunger Games, Twilight)
7 0.16 (Divergent, Hunger Games)
8 0.12 (Hobbit)
9 0.12 (Harry Potter, Twilight)
10 0.12 (Hobbit, Lord of the Rings)
11 0.08 (1984)
12 0.08 (Percy Jackson)
13 0.08 (Harry Potter, Percy Jackson)
14 0.08 (Harry Potter, Twilight, Hunger Games)
The Hunger Games appears in 48% of transactions, making it the most popular title. Harry Potter follows at 40%. The strongest two-book combination is Harry Potter and The Hunger Games, appearing together in 24% of transactions.
Understanding the Results
The frequent itemsets include both individual items and combinations. Looking at the size distribution helps you understand what patterns exist in your data.
# Add column showing itemset length
frequent_itemsets['length'] = frequent_itemsets['itemsets'].apply(lambda x: len(x))
# Distribution of itemset sizes
print("Itemsets by size:")
print(frequent_itemsets['length'].value_counts().sort_index())
# Examine 2-item combinations specifically
two_item_sets = frequent_itemsets[frequent_itemsets['length'] == 2]
print(f"\nFound {len(two_item_sets)} frequent 2-item combinations:")
print(two_item_sets.sort_values('support', ascending=False).reset_index(drop=True))
Output:
Itemsets by size: 1 8 2 6 3 1 Name: length, dtype: int64 Found 6 frequent 2-item combinations: support itemsets length 0 0.24 (Hunger Games, Harry Potter) 2 1 0.20 (Hunger Games, Twilight) 2 2 0.16 (Divergent, Hunger Games) 2 3 0.12 (Twilight, Harry Potter) 2 4 0.12 (Lord of the Rings, Hobbit) 2 5 0.08 (Percy Jackson, Harry Potter) 2
The results show eight single-item itemsets, six two-item combinations, and one three-item combination. The two-item combinations reveal which books customers frequently buy together. Harry Potter and The Hunger Games appear together in 24% of transactions, which is the strongest two-book pair in the dataset.
These two-item and three-item combinations are especially valuable for business decisions. They’re specific enough to act on (you can create bundles or recommendations) but simple enough to implement (placing two books near each other, or suggesting one when the other is purchased).
Choosing the Right Support Threshold
The support threshold determines how many itemsets you find. Set it too low and you’ll get flooded with rare, possibly meaningless combinations. Set it too high and you might miss valuable patterns.
# Compare different support thresholds
thresholds = [0.05, 0.10, 0.20, 0.30]
for threshold in thresholds:
itemsets = apriori(onehot_df, min_support=threshold, use_colnames=True)
print(f"Support {threshold:4.2f}: {len(itemsets):3d} itemsets found")
Output:
Support 0.05: 15 itemsets found Support 0.10: 11 itemsets found Support 0.20: 5 itemsets found Support 0.30: 2 itemsets found
At 0.05 (5% of transactions), you get 15 itemsets representing real patterns. At 0.30 (30%), only two itemsets remain — just the most popular individual titles. The 0.05 threshold strikes a balance, finding genuine patterns without overwhelming you with noise.
Your business context should guide this choice. High-volume retailers might use 0.20 to focus on the strongest patterns. Specialty stores with diverse catalogs might use 0.05 to capture niche but valuable combinations. Seasonal items may have lower support but might still be worth bundling during peak periods.
From Itemsets to Business Decisions
These 15 frequent itemsets represent purchasing patterns in your bookstore data. They tell you which books customers buy together, informing product placement, bundle offers, and recommendation algorithms.
The next step is converting these itemsets into association rules with confidence and lift metrics. While itemsets show what combinations exist, rules show directional relationships: “Customers who buy Harry Potter are likely to also buy The Hunger Games.” This transforms patterns into recommendations you can act on.
If you’re new to these concepts, our guide on understanding market basket analysis covers the fundamentals of how association rules work and why they matter for business decisions.
