Learning path: Find Structure Without Labels: Clustering, PCA and Recommenders · Step 5 of 6
Association Rules and Market Basket Analysis: Support, Confidence, Lift and Apriori
Which items are bought together? Work out support, confidence and lift by hand on eight baskets, then let Apriori in mlxtend find 240 rules in 14,963 real grocery baskets.
What you will learn
- Score a rule by hand with support, confidence and lift
- Explain how Apriori skips rare itemsets
- Find frequent itemsets and rules with mlxtend
- Turn 38,765 grocery lines into baskets and read the top rules
Before you start
- Basic Python lists
- pandas groupby
A shop keeps its till receipts. Look through them and crisps and cola keep turning up together. So the shop puts them on the same shelf: bought together, put together. A pattern like "if crisps, then cola" is an association rule, and finding them in receipts is called market basket analysis.
There's no answer column here. The rules come from the baskets alone, which makes this unsupervised learning.
Score the rule crisps → cola by hand
Here are eight small baskets. In a rule, the left side (crisps) is the antecedent and the right side (cola) is the consequent.
- Support says how common the pair is: half of all baskets have both.
- Confidence says how often the rule holds: 80% of crisps buyers also take cola.
- Lift says whether the rule beats plain popularity. Cola is in 62.5% of baskets anyway; among crisps buyers it's 80%. A lift above 1 means crisps make cola more likely than usual.
The same in Python
import pandas as pd
from mlxtend.frequent_patterns import (
apriori, association_rules)
from mlxtend.preprocessing import TransactionEncoder
baskets = [["crisps", "cola", "bread"],
["crisps", "cola"], ["milk", "bread"],
["crisps", "cola", "milk"],
["bread", "milk", "eggs"],
["crisps", "salsa"], ["cola", "bread"],
["crisps", "cola", "eggs"]]
n = len(baskets)
crisps = sum("crisps" in b for b in baskets)
cola = sum("cola" in b for b in baskets)
both = sum("crisps" in b and "cola" in b
for b in baskets)
print(n, crisps, cola, both)
8 5 5 4
baskets is a list of lists, one list per receipt. (mlxtend is a separate library; if it is missing, run pip install mlxtend.) The counts match what we found by hand. Now the three numbers:
support = both / n
confidence = both / crisps
lift = confidence / (cola / n)
print("support ", support)
print("confidence", confidence)
print("lift ", round(lift, 2))
support 0.5
confidence 0.8
lift 1.28
Why we need lift: eggs → crisps
eggs = sum("eggs" in b for b in baskets)
both = sum("eggs" in b and "crisps" in b
for b in baskets)
confidence = both / eggs
lift = confidence / (crisps / n)
print(confidence, round(lift, 2))
0.5 0.8
A confidence of 0.5 sounds okay: half the egg buyers take crisps. But crisps are in 5 of 8 baskets anyway, so eggs don't help. The lift of 0.8 is below 1, which means no better than chance. Confidence alone can fool you; lift catches it.
Apriori: skip every set with a rare item
With eight baskets, hand work is fine. With thousands of baskets and hundreds of items there are far too many combinations to count. The Apriori algorithm takes a shortcut:
- Count every single item and drop the ones below the minimum support.
- Build pairs only from the items that survived, count them, drop the rare ones. Then triples, and so on.
The trick: if an item is rare, every set that contains it must be rare too, so Apriori never counts those sets. With min_support=0.25 (2 of our 8 baskets), salsa is in only one basket. So no pair with salsa is ever counted.
In mlxtend, TransactionEncoder first turns the baskets into a table of True and False:
te = TransactionEncoder()
data = te.fit(baskets).transform(baskets)
toy = pd.DataFrame(data, columns=te.columns_)
toy
bread cola crisps eggs milk salsa
0 True True True False False False
1 False True True False False False
2 True False False False True False
3 False True True False True False
4 True False False True True False
5 False False True False False True
6 True True False False False False
7 False True True True False False
Then apriori finds the frequent itemsets, and association_rules builds rules from them, keeping those with a lift of at least 1:
frequent = apriori(toy, min_support=0.25,
use_colnames=True)
rules = association_rules(frequent,
metric="lift", min_threshold=1.0)
print(len(frequent), len(rules))
8 4
Eight frequent itemsets: five single items (all but salsa) and three pairs. Four rules survive the lift filter:
rules = rules.sort_values(["lift", "confidence"],
ascending=False)
for _, r in rules.iterrows():
a = ", ".join(sorted(r["antecedents"]))
c = ", ".join(sorted(r["consequents"]))
print(a, "->", c, "| sup", r["support"],
"| conf", round(r["confidence"], 2),
"| lift", round(r["lift"], 2))
milk -> bread | sup 0.25 | conf 0.67 | lift 1.33
bread -> milk | sup 0.25 | conf 0.5 | lift 1.33
cola -> crisps | sup 0.5 | conf 0.8 | lift 1.28
crisps -> cola | sup 0.5 | conf 0.8 | lift 1.28
Bread and milk both ways, crisps and cola both ways. Crisps → cola has lift 1.28, just like our hand maths. Notice a rule and its reverse share the same support and lift, but not always the same confidence (0.67 against 0.5).
Real grocery receipts
df = pd.read_csv("Groceries_dataset.csv")
print(df.shape)
df.head(3)
(38765, 3)
Member_number Date itemDescription
0 1808 21-07-2015 tropical fruit
1 2552 05-01-2015 whole milk
2 2300 19-09-2015 pip fruit
One row per item bought: 38,765 lines. To get baskets, we group by member and date, so one member on one day is one basket:
groups = df.groupby(["Member_number", "Date"])
real = groups["itemDescription"].apply(
lambda items: sorted(set(items))).tolist()
print(len(real), "baskets")
print(real[0])
14963 baskets
['sausage', 'semi-finished bread', 'whole milk', 'yogurt']
set removes an item bought twice in the same basket. The same encoder builds the True/False table:
te = TransactionEncoder()
data = te.fit(real).transform(real)
X = pd.DataFrame(data, columns=te.columns_)
print(X.shape)
(14963, 167)
14,963 baskets and 167 items. In a real shop most items are rare, so the minimum support must be low. 0.001 means a set must appear in about 15 baskets:
frequent = apriori(X, min_support=0.001,
use_colnames=True)
rules = association_rules(frequent,
metric="lift", min_threshold=1.0)
print(len(frequent), "itemsets,", len(rules), "rules")
750 itemsets, 240 rules
The strongest rules by lift
top = rules.sort_values(["lift", "confidence"],
ascending=False).head(4)
for _, r in top.iterrows():
a = ", ".join(sorted(r["antecedents"]))
c = ", ".join(sorted(r["consequents"]))
print(a, "->", c, "| sup", round(r["support"], 4),
"| lift", round(r["lift"], 2))
whole milk, yogurt -> sausage | sup 0.0015 | lift 2.18
sausage -> whole milk, yogurt | sup 0.0015 | lift 2.18
sausage, whole milk -> yogurt | sup 0.0015 | lift 1.91
yogurt -> sausage, whole milk | sup 0.0015 | lift 1.91
The top rule is whole milk and yogurt → sausage, with a lift of 2.18. But the support is only 0.0015, about one and a half baskets in a thousand. So always check support too: a high lift on a handful of baskets may not be worth a shelf move.
A strong rule can mean placing items side by side, or a breakfast bundle. But a rule only shows what happens together. It doesn't prove one item causes the other to be bought.
Common mistakes
- Trusting confidence alone. Eggs → crisps had 0.5 confidence and a lift of 0.8, worse than chance.
- Ignoring support. A high lift from 1 or 2 baskets in a thousand is fragile.
- Setting min_support too high on real data. Most items are rare, so you find almost nothing.
- Treating each line as a basket. Group the lines into baskets first (member and date here).
- Reading a rule as cause and effect. It only shows what's bought together.
Quick recap
| Measure | Formula | crisps → cola |
|---|---|---|
| Support | baskets with both / all baskets | 4 / 8 = 0.5 |
| Confidence | both / baskets with the antecedent | 4 / 5 = 0.8 |
| Lift | confidence / share of baskets with the consequent | 0.8 / 0.625 = 1.28 |
| Apriori | Skip every set that contains a rare item | 8 itemsets, 4 rules (toy); 750 itemsets, 240 rules (groceries) |
Try it yourself
On the real baskets, find the rules where whole milk is the consequent. Which one has the highest lift?
The notebook and the grocery dataset are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Dimensionality Reduction with PCA: 13 Columns Down to 2
Next →Recommender Systems: Item-Based Collaborative Filtering with Cosine Similarity
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
K-Means Clustering: Find Groups in Data With No Labels
How k-means finds groups without labels: the assign-update loop worked by hand on eight homes, then KMeans on 2,600 customers, bad random starts, k-means++ and why you scale first.
Choosing k for K-Means: the Elbow Method and the Silhouette Score
K-means always returns exactly k groups, even when k is wrong. Use the elbow plot and the silhouette score to pick k for 2,600 customers, then describe each group in plain words.
Hierarchical Clustering and DBSCAN: Dendrograms, Linkage, eps and Noise
Two more ways to find groups: agglomerative clustering builds a family tree of merges (the dendrogram), and DBSCAN grows clusters from crowds and leaves loners out as noise. Shown on eight homes, 2,600 customers and two moons.
Dimensionality Reduction with PCA: 13 Columns Down to 2
PCA squeezes many columns into a few new ones and keeps most of the information. Reduce 178 wines from 13 columns to 2, see why scaling comes first, pick the number of components and use PCA in a pipeline.