Lesson 7 of 8 · Techniques
Association Rules
Learn market-basket analysis: support, confidence and lift with worked examples, the Apriori principle, a small Apriori in Python, and how to read rules safely.
- 16 min read
- Intermediate
- Reviewed
- Explain market-basket analysis and what an association rule says
- Calculate support, confidence and lift by hand and in Python
- Use the Apriori principle to search for frequent itemsets without checking every combination
- Read rules critically: lift below 1, rare items and spurious rules
- Find rules on real data with the mlxtend library
The idea in plain words
Every receipt is a list of products bought together. Market-basket analysis searches thousands of receipts for products that turn up together more often than chance would explain, and writes what it finds as rules such as "customers who buy salsa usually buy chips too". There are no labels and nothing to predict: like clustering, it looks for structure in the data itself.
A shop can use such rules to place products near each other, build bundles and promotions, or suggest "frequently bought together" items online. The same method works for anything that comes in groups: pages visited in one session, symptoms recorded in one visit, or error messages that appear in the same log file. In this lesson, a basket is one shopping trip, and an itemset is any group of products, such as bread + butter.
Support, confidence and lift
Here are 10 baskets from a tiny shop:
1 bread, butter, milk 6 milk, chips
2 bread, butter 7 bread, butter, milk
3 bread, milk 8 beer, chips
4 beer, chips, milk 9 bread, jam
5 bread, butter, jam, milk 10 beer, chips, milkThree numbers describe a rule. Support says how common an itemset is:
support(A) = baskets that contain A ÷ all baskets
support(bread) = 6 ÷ 10 = 0.6
support(bread + butter) = 4 ÷ 10 = 0.4 baskets 1, 2, 5 and 7Confidence says how often the rule is right: of the baskets with A, the share that also contain B.
confidence(A → B) = support(A + B) ÷ support(A)
confidence(butter → bread) = 0.4 ÷ 0.4 = 1.0 every basket with butter has bread
confidence(bread → butter) = 0.4 ÷ 0.6 = 0.67 two in three bread baskets have butterThe direction matters: the same pair gives two rules with different confidence. Lift compares the rule with chance: how much more likely B is in a basket with A than in any basket.
lift(A → B) = confidence(A → B) ÷ support(B)
lift(bread → butter) = 0.67 ÷ 0.4 = 1.67 butter is 1.67 times as likely with bread
lift(bread → milk) = 0.67 ÷ 0.7 = 0.95 milk is slightly LESS likely with breadA lift above 1 means the items appear together more often than chance; exactly 1 means they are independent; below 1 means they appear together less often than chance, as when people buy one instead of the other. Lift is the same in both directions. Python can do the counting:
baskets = [
{"bread", "butter", "milk"}, {"bread", "butter"}, {"bread", "milk"},
{"beer", "chips", "milk"}, {"bread", "butter", "jam", "milk"}, {"milk", "chips"},
{"bread", "butter", "milk"}, {"beer", "chips"}, {"bread", "jam"}, {"beer", "chips", "milk"},
]
def support(items):
"""Share of baskets that contain every item in the list."""
return sum(set(items) <= basket for basket in baskets) / len(baskets)
def confidence(if_items, then_items):
return support(if_items + then_items) / support(if_items)
def lift(if_items, then_items):
return confidence(if_items, then_items) / support(then_items)
print("support:", ", ".join(f"{item} {support([item]):.1f}" for item in ["bread", "butter", "milk", "beer", "chips", "jam"]))
print(f"\n{'rule':<18}{'support':>8}{'confidence':>11}{'lift':>6}")
for a, b in [("butter", "bread"), ("bread", "butter"), ("beer", "chips"), ("jam", "bread"), ("bread", "milk")]:
print(f"{a + ' -> ' + b:<18}{support([a, b]):8.2f}{confidence([a], [b]):11.2f}{lift([a], [b]):6.2f}")support: bread 0.6, butter 0.4, milk 0.7, beer 0.3, chips 0.4, jam 0.2 rule support confidence lift butter -> bread 0.40 1.00 1.67 bread -> butter 0.40 0.67 1.67 beer -> chips 0.30 1.00 2.50 jam -> bread 0.20 1.00 1.67 bread -> milk 0.40 0.67 0.95
set(items) <= basket asks whether every item is in the basket. The numbers match the hand calculations, and beer → chips is the strongest rule: every beer basket has chips, and chips are 2.5 times as likely there as in an average basket.
The Apriori principle
To find all strong rules, you first need the frequent itemsets.
Checking every possible itemset is hopeless: n products make 2ⁿ − 1 itemsets, so 20 products make over a million, and a supermarket's 30,000 products make more than there are atoms in the universe. One simple fact saves the day:
The Apriori principle
Every part of a frequent itemset is frequent.
So if an itemset is NOT frequent, no bigger itemset that contains it can be.
If chips + salsa is in fewer than 5% of baskets,
then beer + chips + salsa is too, so it never needs to be counted.The Apriori algorithm uses this level by level: count single items and keep the frequent ones; build pairs only from frequent items and count them; build triples only from pairs that are all frequent; and so on, until no candidates are left. Then it splits each frequent itemset into rules and keeps those with enough confidence.
A small Apriori in plain Python
The program below creates 1,000 baskets for a small shop. Most products are bought independently, but four have a partner they tend to go with: butter with bread, chips with beer, salsa with chips and sugar with coffee. Then it runs Apriori with a minimum support of 5% and keeps rules with a confidence of at least 50%:
from itertools import combinations
import numpy as np
# ---- 1,000 baskets from a small shop (seeded, so everyone gets the same data) ----
rng = np.random.RandomState(0)
popular = {"milk": 0.55, "bread": 0.40, "eggs": 0.25, "coffee": 0.20, "beer": 0.15}
partners = {"butter": ("bread", 0.5, 0.05), # item: (partner, chance with it, chance without it)
"chips": ("beer", 0.6, 0.1), "salsa": ("chips", 0.5, 0.03), "sugar": ("coffee", 0.4, 0.05)}
baskets = []
for _ in range(1000):
basket = {item for item, p in popular.items() if rng.rand() < p}
for item, (partner, p_with, p_without) in partners.items():
if rng.rand() < (p_with if partner in basket else p_without):
basket.add(item)
baskets.append(frozenset(basket))
def support(itemset):
return sum(itemset <= basket for basket in baskets) / len(baskets)
# ---- Apriori: find frequent itemsets one size at a time ----
items = sorted(set().union(*baskets))
candidates = [frozenset([item]) for item in items]
frequent, size = {}, 1
while candidates:
counted = {c: support(c) for c in candidates}
kept = {c: s for c, s in counted.items() if s >= 0.05} # minimum support: 5% of baskets
possible = len(list(combinations(items, size)))
print(f"size {size}: {len(candidates):2d} of {possible:3d} possible itemsets counted, {len(kept):2d} frequent")
frequent.update(kept)
size += 1
# Join frequent itemsets into bigger ones, and keep only those whose every
# smaller subset is frequent (the Apriori principle)
joined = {a | b for a in kept for b in kept if len(a | b) == size}
candidates = sorted((c for c in joined if all(frozenset(sub) in kept for sub in combinations(c, size - 1))),
key=sorted)
# ---- Rules: split each frequent itemset into an IF part and one THEN item ----
rules = []
for itemset, s in frequent.items():
if len(itemset) < 2:
continue
for then in sorted(itemset):
if_part = itemset - {then}
confidence = s / frequent[if_part]
if confidence >= 0.5: # minimum confidence: 50%
lift = confidence / frequent[frozenset([then])]
rules.append((lift, confidence, s, " + ".join(sorted(if_part)) + " -> " + then))
rules.sort(reverse=True)
print(f"\n{len(rules)} rules, the strongest and weakest by lift:")
for lift, confidence, s, rule in rules[:6] + rules[-3:]:
print(f" {rule:<24} support {s:.2f} confidence {confidence:.2f} lift {lift:.2f}")size 1: 9 of 9 possible itemsets counted, 9 frequent size 2: 36 of 36 possible itemsets counted, 20 frequent size 3: 18 of 84 possible itemsets counted, 6 frequent 23 rules, the strongest and weakest by lift: milk + salsa -> chips support 0.05 confidence 0.78 lift 4.13 salsa -> chips support 0.09 confidence 0.75 lift 3.93 beer + milk -> chips support 0.05 confidence 0.64 lift 3.38 beer -> chips support 0.09 confidence 0.62 lift 3.26 sugar -> coffee support 0.08 confidence 0.62 lift 2.75 bread + eggs -> butter support 0.07 confidence 0.60 lift 2.40 salsa -> milk support 0.07 confidence 0.55 lift 1.01 eggs -> milk support 0.14 confidence 0.55 lift 1.00 coffee -> milk support 0.12 confidence 0.54 lift 0.99
The search. All 9 products and all 36 pairs had to be counted, but only 18 of the 84 possible triples: the other 66 contained a pair that wasn't frequent, so the Apriori principle ruled them out without counting. On real data with thousands of products, that pruning is what makes the search possible at all.
The rules. The partners built into the data come out on top: salsa → chips, beer → chips and sugar → coffee, with lifts from 2.75 to 3.93. Three of the top six are those patterns with an extra product along for the ride: milk + salsa → chips is really salsa → chips, beer + milk → chips is really beer → chips, and bread + eggs → butter is really bread → butter (lift 2.13, just outside the top six). The data was made with no link between eggs and butter, so the higher lift of the longer rule is chance. Prefer the shorter rule unless the longer one is clearly and reliably stronger.
Reading rules: three pitfalls
Lift below 1. Look at the weakest rules above: coffee → milk is right 54% of the time, which sounds useful, but milk is in about 55% of all baskets anyway. Its lift of 0.99 says coffee buyers are no more likely to buy milk than anyone else. Change rules[:6] + rules[-3:] to rules to see all 23: 12 of them end in milk, with lifts from 0.99 to 1.13. Rules into popular products always have decent confidence, so judge rules by lift, not confidence alone.
Rare items. In the 10-basket shop, jam → bread has a confidence of 1.0, but jam was bought only twice. One more jam basket without bread would drop it to 0.67. Rules built on a handful of baskets are mostly noise, so set a minimum support and look at how many baskets stand behind each rule.
Spurious rules. Check enough pairs and some will look strong by pure chance. The next program makes 1,000 baskets in which 40 products are each bought independently by about 5% of shoppers, so by construction there are no real patterns. It finds the "best" pairs in the first 500 baskets (month 1), then checks them on the other 500 (month 2):
from itertools import combinations
import numpy as np
# 1,000 baskets, 40 products, each bought by about 5% of shoppers INDEPENDENTLY:
# by construction, there are no real patterns at all
rng = np.random.RandomState(0)
bought = rng.rand(1000, 40) < 0.05
month1, month2 = bought[:500], bought[500:]
def lift(data, i, j):
both = (data[:, i] & data[:, j]).mean()
return both / (data[:, i].mean() * data[:, j].mean())
pairs = list(combinations(range(40), 2))
best = sorted(pairs, key=lambda pair: lift(month1, *pair), reverse=True)[:5]
print(f"{len(pairs)} pairs checked in month 1. The 5 with the highest lift:")
for i, j in best:
together = (month1[:, i] & month1[:, j]).sum()
print(f" product {i:2d} + product {j:2d}: together in {together} baskets, "
f"lift {lift(month1, i, j):.1f} in month 1, {lift(month2, i, j):.1f} in month 2")780 pairs checked in month 1. The 5 with the highest lift: product 6 + product 35: together in 5 baskets, lift 5.4 in month 1, 1.0 in month 2 product 5 + product 18: together in 5 baskets, lift 4.2 in month 1, 1.5 in month 2 product 16 + product 27: together in 7 baskets, lift 3.9 in month 1, 0.0 in month 2 product 15 + product 31: together in 3 baskets, lift 3.8 in month 1, 0.7 in month 2 product 6 + product 19: together in 4 baskets, lift 3.8 in month 1, 1.1 in month 2
Pure noise produced lifts of 3.8 to 5.4, each resting on 3 to 7 baskets. In month 2 none of them held up: their lifts ranged from 0.0 to 1.5, scattered around the 1 that independent products give. Three habits protect you: require enough baskets behind each rule, check rules on new data before acting on them, and remember that a rule shows what is bought together, not why. Moving salsa next to the chips may or may not sell more salsa; a test in a few shops will tell you.
The mlxtend library
For real data, the mlxtend library has fast, tested versions of Apriori and rule generation, built on pandas. It isn't available in this site's browser or in the course's checks, so this code is shown but not run. On your own computer, install it with pip install mlxtend:
# Not run here: needs pandas and mlxtend (pip install mlxtend)
import pandas as pd
from mlxtend.frequent_patterns import apriori, association_rules
from mlxtend.preprocessing import TransactionEncoder
baskets = [["bread", "butter", "milk"], ["bread", "butter"], ["bread", "milk"],
["beer", "chips", "milk"], ["bread", "butter", "jam", "milk"], ["milk", "chips"],
["bread", "butter", "milk"], ["beer", "chips"], ["bread", "jam"], ["beer", "chips", "milk"]]
encoder = TransactionEncoder() # one True/False column per product
onehot = pd.DataFrame(encoder.fit(baskets).transform(baskets), columns=encoder.columns_)
itemsets = apriori(onehot, min_support=0.2, use_colnames=True)
rules = association_rules(itemsets, metric="confidence", min_threshold=0.6)
print(rules[["antecedents", "consequents", "support", "confidence", "lift"]].sort_values("lift", ascending=False))TransactionEncoderturns the baskets into a table with one True/False column per product, the formataprioriexpects.apriorireturns every frequent itemset with its support;fpgrowth, from the same module, finds the same itemsets faster on large data.association_rulesbuilds the rules and keeps those abovemin_thresholdfor the chosenmetric. Its antecedents are the IF parts and its consequents the THEN parts, and it adds extra measures such as leverage and conviction next to support, confidence and lift.
Common mistakes
Practice
Work out support, confidence and lift for two rules in a café's baskets. One of them is worth acting on and one is not: which?
baskets = [
{"tea", "biscuits"}, {"tea", "milk"}, {"coffee", "milk"}, {"tea", "biscuits", "milk"},
{"coffee", "biscuits"}, {"tea", "biscuits"}, {"coffee", "milk", "sugar"}, {"tea", "lemon"},
{"coffee", "milk"}, {"tea", "biscuits", "lemon"},
]
# For each rule IF -> THEN, print support, confidence and lift with two decimals
for if_item, then_item in [("tea", "biscuits"), ("tea", "milk")]:
support, confidence, lift = 0, 0, 0
print(f"{if_item} -> {then_item}: support {support:.2f}, confidence {confidence:.2f}, lift {lift:.2f}")
The rule bread → milk has a confidence of 0.67, and 70% of all baskets contain milk. What does its lift of 0.95 tell you?
Summary
- Market-basket analysis finds products bought together and writes them as rules A → B, with no labels needed.
- Support is how common an itemset is, confidence how often a rule is right, and lift how much more likely B is with A than in any basket (above 1 means together more than chance).
- The Apriori principle says no itemset can be frequent if any part of it isn't, so Apriori builds itemsets level by level and skips the rest.
- Judge rules by lift with enough support, beware rare items and rules found by chance, and check rules on new data before acting.
- On real data, use mlxtend:
TransactionEncoder,aprioriorfpgrowth, thenassociation_rules.
Next: Project: Customer Segmentation.
Finished reading? Tick it off to track your progress.