Sign in

Apriori

Apriori algorithm for association rule mining

Finds sets of items that often appear together in transactions, then turns them into rules such as: people who buy X also buy Y.

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

  1. Count each single item and keep those that appear in at least a share min_support of the transactions.
  2. Join the frequent sets of size kk into candidate sets of size k+1k + 1.
  3. Drop any candidate that has an infrequent subset, without counting it. This is the pruning step that gives the method its name.
  4. Count the remaining candidates in the transactions and keep the frequent ones. Repeat until no new set is found or max_length is reached.
  5. Split each frequent set into an antecedent (the if part) and a consequent (the then part) in every possible way.
  6. 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_support makes 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 support method 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

IfUse instead
The dataset is very large or the support threshold must be lowFP-Growth, which avoids generating candidate sets
You need personalised recommendations for each userA two-tower retrieval model or matrix factorization
The order of events mattersSequential pattern mining or a sequence model such as a GRU

Math foundations

  1. Support

    supp⁡(X)=∣{ t∈T:X⊆t }∣∣T∣\operatorname{supp}(X) = \frac{\big|\{\, t \in T : X \subseteq t \,\}\big|}{|T|}

    The share of transactions that contain every item of XX. A set is called frequent when its support is at least min_support.

  2. The Apriori property

    X⊆Y  ⟹  supp⁡(X)≥supp⁡(Y)X \subseteq Y \;\Longrightarrow\; \operatorname{supp}(X) \ge \operatorname{supp}(Y)

    Every transaction that contains YY also contains XX. So if XX is infrequent, every superset of it is too and need not be counted.

  3. Confidence of a rule

    conf⁡(A⇒C)=supp⁡(A∪C)supp⁡(A)\operatorname{conf}(A \Rightarrow C) = \frac{\operatorname{supp}(A \cup C)}{\operatorname{supp}(A)}

    Among the transactions that contain AA, the share that also contain CC. It estimates the conditional probability of CC given AA.

  4. Lift

    lift⁡(A⇒C)=conf⁡(A⇒C)supp⁡(C)=supp⁡(A∪C)supp⁡(A) supp⁡(C)\operatorname{lift}(A \Rightarrow C) = \frac{\operatorname{conf}(A \Rightarrow C)}{\operatorname{supp}(C)} = \frac{\operatorname{supp}(A \cup C)}{\operatorname{supp}(A)\,\operatorname{supp}(C)}

    How much more often AA and CC occur together than they would if they were independent. A lift of 1 means no association, above 1 a positive one.

Symbols

TT
the list of all transactions
tt
one transaction, a set of items
X,YX, Y
itemsets
AA
antecedent of a rule, the if part
CC
consequent of a rule, the then part
A∪CA \cup C
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.

supp⁡({beer})=35=0.6,supp⁡({diapers})=45=0.8\operatorname{supp}(\{\text{beer}\}) = \tfrac{3}{5} = 0.6, \qquad \operatorname{supp}(\{\text{diapers}\}) = \tfrac{4}{5} = 0.8
supp⁡({beer,diapers})=35=0.6\operatorname{supp}(\{\text{beer}, \text{diapers}\}) = \tfrac{3}{5} = 0.6
conf⁡(beer⇒diapers)=0.60.6=1.0\operatorname{conf}(\text{beer} \Rightarrow \text{diapers}) = \frac{0.6}{0.6} = 1.0
conf⁡(diapers⇒beer)=0.60.8=0.75\operatorname{conf}(\text{diapers} \Rightarrow \text{beer}) = \frac{0.6}{0.8} = 0.75
lift⁡(beer⇒diapers)=1.00.8=1.25\operatorname{lift}(\text{beer} \Rightarrow \text{diapers}) = \frac{1.0}{0.8} = 1.25

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

  1. With 100 distinct items there are more than 103010^{30} 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_support approaches zero.

  2. 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.

  3. 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?

  4. 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.