Overview
A shop has thousands of baskets and wants to know which products go together. Counting every possible combination of items is impossible, because the number of combinations doubles with every extra item. Apriori uses one simple fact to avoid most of that counting: if a set of items is rare, every larger set that contains it is at least as rare. So it starts with single items, keeps the common ones, and only ever builds bigger sets out of smaller sets that were already common. The common sets are then split into if-then rules, each with numbers that say how reliable it is.
A short history
Rakesh Agrawal and Ramakrishnan Srikant published Apriori in 1994 at IBM Almaden, following earlier work by Agrawal, Imielinski and Swami in 1993 that defined association rules for supermarket basket data. Its key observation is that every subset of a frequent itemset must itself be frequent, which lets the search discard most candidates early. It made mining large transaction databases practical and remains the standard teaching algorithm for the task.
How it works
- Count each single item and keep those that appear in at least a share
min_supportof the transactions. - Join the frequent sets of size into candidate sets of size .
- Drop any candidate that has an infrequent subset, without counting it. This is the pruning step that gives the method its name.
- Count the remaining candidates in the transactions and keep the frequent ones. Repeat until no new set is found or
max_lengthis reached. - Split each frequent set into an antecedent (the if part) and a consequent (the then part) in every possible way.
- Keep the rules whose confidence is at least
min_confidence, and report support, confidence and lift for each.
Watch out for
- A very low
min_supportmakes the number of candidate sets grow very fast, so the run takes too long or runs out of memory. FP-Growth is the usual alternative then. - High confidence alone can mislead: if almost every basket contains milk, any rule that ends in milk has high confidence. Check that lift is clearly above 1.
- A rule describes co-occurrence, not cause. Buying beer with diapers does not show that one purchase leads to the other.
- The
supportmethod returns 0.0 for a set that is not frequent, even if it does appear in a few transactions, because only frequent sets are stored.
Use cases
When to use it
Market basket analysis and any question about items that occur together, on transaction data with a modest number of distinct items.
In industry
- Grocery and retail
- Market basket analysis: finding products that are often bought together, to plan shelf placement, bundles and promotions.
- E-commerce
- Simple 'frequently bought together' suggestions computed from the items that share an order.
- Healthcare
- Finding diagnoses, symptoms or prescriptions that tend to occur together in patient records, as a starting point for review by clinicians.
Choosing it: what must hold
- Data in the form of transactions, each a set of items, with no need for quantities or order.
- A minimum support threshold high enough that the number of frequent itemsets stays manageable.
- A goal of readable rules for people, not a ranked prediction for each user.
When to choose something else
| If | Use instead |
|---|---|
| The dataset is very large or the support threshold must be low | FP-Growth, which avoids generating candidate sets |
| You need personalised recommendations for each user | A two-tower retrieval model or matrix factorization |
| The order of events matters | Sequential pattern mining or a sequence model such as a GRU |
Math foundations
Support
The share of transactions that contain every item of . A set is called frequent when its support is at least
min_support.The Apriori property
Every transaction that contains also contains . So if is infrequent, every superset of it is too and need not be counted.
Confidence of a rule
Among the transactions that contain , the share that also contain . It estimates the conditional probability of given .
Lift
How much more often and occur together than they would if they were independent. A lift of 1 means no association, above 1 a positive one.
Symbols
- the list of all transactions
- one transaction, a set of items
- itemsets
- antecedent of a rule, the if part
- consequent of a rule, the then part
- the itemset holding all items of A and of C
Worked by hand
Five baskets: {bread, milk}, {bread, diapers, beer}, {milk, diapers, beer}, {bread, milk, diapers, beer}, {bread, milk, diapers}. Beer is in 3, diapers in 4, and both together in 3.
Every basket with beer also has diapers, but only three in four baskets with diapers have beer. The rule is not symmetric. A lift of 1.25 says the pair occurs 25 percent more often than chance would give.
Visual example
Loading the example.
Try this
- Raise min_support to 0.8: beer drops out, and every set that holds beer is then never counted.
- Open diapers + beer and compare the two rules: one has confidence 1, the reverse 0.75.
- Take diapers out of basket 2 and watch which sets stop being frequent.
Code sample
from impl import Apriori
from config import AprioriConfig
baskets = [["bread", "milk"], ["bread", "diapers", "beer"], ["milk", "diapers", "beer"],
["bread", "milk", "diapers", "beer"], ["bread", "milk", "diapers"]]
model = Apriori(AprioriConfig(min_support=0.6, min_confidence=0.7)).fit(baskets)
print(model.support(["diapers", "beer"])) # 0.6
print(model.rules()[0]) # beer -> diapers, confidence 1.0
print(model.predict(["beer"])) # [('diapers', 1.0)]Read the implementation (111 lines)
"""Apriori: frequent itemset mining and association rules.
Level-wise search: frequent itemsets of size k are joined into candidates of size k + 1, candidates with an
infrequent subset are pruned (every subset of a frequent itemset is frequent), and the rest are counted.
Transactions are stored as a boolean matrix, so counting a candidate is one vectorised AND over its columns.
"""
from __future__ import annotations
from itertools import combinations
import numpy as np
try:
from .config import AprioriConfig
except ImportError: # run from the template's own folder
from config import AprioriConfig
class Apriori:
"""Mine frequent itemsets with `fit`, read rules with `rules`, recommend items with `predict`."""
def __init__(self, config: AprioriConfig | None = None) -> None:
self.config = config or AprioriConfig()
self.items_: list = [] # sorted distinct items
self.frequent_itemsets_: dict[frozenset, float] = {} # itemset -> support (fraction of transactions)
self.rules_: list[dict] = []
self.n_transactions_ = 0
def fit(self, transactions: list) -> "Apriori":
"""Find every itemset whose support is at least `min_support`, then derive the rules.
transactions: a list of iterables of hashable items, one per transaction (duplicates are ignored).
"""
cfg = self.config
baskets = [set(t) for t in transactions]
if not baskets:
raise ValueError("transactions is empty")
self.n_transactions_ = n = len(baskets)
self.items_ = sorted({i for b in baskets for i in b}, key=repr)
col = {item: j for j, item in enumerate(self.items_)}
M = np.zeros((n, len(self.items_)), dtype=bool) # M[t, j]: transaction t holds item j
for t, b in enumerate(baskets):
M[t, [col[i] for i in b]] = True
support = M.mean(axis=0)
level = {(j,): float(support[j]) for j in range(M.shape[1]) if support[j] >= cfg.min_support}
found = dict(level)
k = 1
while level and (cfg.max_length is None or k < cfg.max_length):
prev = sorted(level)
candidates = set()
for a in range(len(prev)):
for b in range(a + 1, len(prev)):
if prev[a][:-1] != prev[b][:-1]: # sorted, so later ones cannot share the prefix either
break
cand = prev[a] + (prev[b][-1],)
if all(sub in level for sub in combinations(cand, k)):
candidates.add(cand)
level = {}
for cand in candidates:
s = float(M[:, cand].all(axis=1).mean())
if s >= cfg.min_support:
level[cand] = s
found.update(level)
k += 1
self.frequent_itemsets_ = {frozenset(self.items_[j] for j in key): s for key, s in found.items()}
self.rules_ = self._make_rules()
return self
def _make_rules(self) -> list[dict]:
"""Split each frequent itemset into antecedent -> consequent and keep rules above `min_confidence`."""
rules = []
sup = self.frequent_itemsets_
for itemset, s in sup.items():
if len(itemset) < 2:
continue
members = sorted(itemset, key=repr)
for r in range(1, len(members)):
for ante in combinations(members, r):
a = frozenset(ante)
c = itemset - a
confidence = s / sup[a]
if confidence >= self.config.min_confidence:
rules.append({"antecedent": a, "consequent": c, "support": s, "confidence": confidence,
"lift": confidence / sup[c]})
rules.sort(key=lambda r: (-r["confidence"], -r["lift"], -r["support"], repr(sorted(r["antecedent"], key=repr))))
return rules
def rules(self) -> list[dict]:
"""Rules as dicts with antecedent, consequent, support, confidence and lift, best confidence first."""
return list(self.rules_)
def support(self, itemset) -> float:
"""Support of a frequent itemset; 0.0 when the itemset is not frequent."""
return self.frequent_itemsets_.get(frozenset(itemset), 0.0)
def predict(self, basket, top_k: int | None = None) -> list[tuple]:
"""Recommend items for a basket.
Every rule whose antecedent is inside `basket` votes for the items of its consequent that the basket
lacks; an item is scored by the best confidence among its rules.
Returns [(item, confidence), ...] sorted by confidence, at most `top_k` entries.
"""
basket = set(basket)
best: dict = {}
for rule in self.rules_:
if rule["antecedent"] <= basket:
for item in rule["consequent"] - basket:
best[item] = max(best.get(item, 0.0), rule["confidence"])
ranked = sorted(best.items(), key=lambda kv: (-kv[1], repr(kv[0])))
return ranked if top_k is None else ranked[:top_k]- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 6, run with
python3 -m unittest -v
Practice
Fit Apriori on the five baskets above with min_support=0.6 and min_confidence=0.7, and read rules(). Then lower min_support to 0.4 and count how many more itemsets appear in frequent_itemsets_. Finally call predict(["bread"]) and explain each recommendation from the rules.
Check on learning
- With 100 distinct items there are more than possible itemsets. Why can Apriori still finish on such data, and under what condition would it not?
A way to think about it
Think about how many sets survive each level when most single items are rare, and what happens to that number as
min_supportapproaches zero. - A rule has confidence 0.9 and lift 0.95. Would you act on it? What does that pair of numbers tell you?
A way to think about it
Use the lift formula to work out the support of the consequent. Then ask what you would predict for a basket if you ignored the antecedent.
- Why is the rule beer to diapers not the same as diapers to beer, although both come from the same itemset?
A way to think about it
Look at what sits in the denominator of the confidence in each direction. Which of support, confidence and lift are symmetric?
- Suppose you double the dataset by copying every transaction. Which of the reported numbers change?
A way to think about it
All three measures are ratios of counts. Check what happens to each numerator and denominator.