Contents/ Part XIX · Unsupervised Learning/ Chapter 120

Association Rule Mining

"Customers who bought this also bought..." Behind that everyday phrase is an unsupervised search through millions of baskets for items that co-occur far more than chance. We mine grocery transactions with Apriori and FP-Growth, and learn why lift, not confidence, tells a real pattern from a coincidence.

⏱️ ~18 min read
🐍 Notebook included
📊 Chapter 120

There is a retail legend: mine a supermarket's receipts and you find that shoppers who buy diapers disproportionately also buy beer (tired new parents, the story goes). True or not, it captures the goal of association rule mining: discover, with no labels and no target, which items travel together, and how strongly.

An association rule A → B says baskets containing A tend to contain B. Each rule is scored by three numbers: support (how common), confidence (how reliable), and lift (how much stronger than chance). Apriori and FP-Growth find the rules efficiently.
🗂️
The chapter in one line

Mine baskets for "A goes with B" rules: judge each by support (common enough?), confidence (reliable?), and above all lift (stronger than chance?), and use Apriori's pruning trick, or the faster FP-Growth, to find them without checking every combination.

1

Market Baskets and Rules

The input is a pile of transactions, each a set of items bought together. The output is a set of rules of the form antecedent → consequent ("if a basket has chips and soda, it probably has salsa"). This is unsupervised: nothing is being predicted or labeled, we are simply describing structure, which items keep company.

Before mining, receipts (stored as one row per item) are reshaped into a basket matrix: one row per trip, one True/False column per item. Our grocery data becomes a 900-trip by 25-item grid of booleans, the shape every mining algorithm expects.

2

Support, Confidence & Lift

Three metrics turn a co-occurrence into an actionable rule, and getting the difference between them right is the whole game.

Scoring the rule  diapers → beer Support how common is the combo? baskets with diapers AND beer all baskets = 0.11 11% of trips Confidence how reliable is A → B? baskets with diapers AND beer baskets with diapers = 0.74 74% of diaper trips Lift stronger than chance? confidence 0.74 beer's baseline 0.15 ≈ 5 5× more likely than average → real!

Support is popularity, the fraction of baskets holding the whole itemset. It keeps us honest (rare combos are statistically flimsy) and, as we will see, powers the search. Confidence is reliability, given A, how often does B follow? But confidence has a trap: if B is popular, almost any rule "… → B" scores high. Lift fixes that by dividing confidence by B's baseline rate. Lift > 1 is a genuine positive association, = 1 is independence, < 1 means the items repel.

3

Finding Rules: Apriori & FP-Growth

With even a few dozen items there are astronomically many possible itemsets, checking every one is hopeless. Apriori escapes the explosion with one elegant observation, the downward-closure principle: if an itemset is infrequent, every larger set containing it must be infrequent too. So the moment a set falls below minimum support, Apriori prunes it and never looks at any of its supersets.

Apriori prunes the search: skip every superset of an infrequent set 1-item 2-item 3-item A B C D infrequent ✂ A,B A,C B,C *,D pruned unseen A,B,C

Because it explores only the survivors, Apriori scans a tiny corner of the space and still finds every frequent itemset, here, 61 of them above 3% support. FP-Growth reaches the same answer by a different route: it compresses the transactions into a tree and reads patterns off it without repeated scans, so it runs much faster on large catalogs. Same rules, better speed, which is why FP-Growth is the workhorse on real retail data.

4

Real-World Example: Market-Basket Analysis

The original and still biggest use of association rules is market-basket analysis: what to bundle, what to put on adjacent shelves, what to recommend at checkout.

📂 Dataset · association-rule-mining--baskets.xlsx

900 grocery transactions in long format, one row per item per transaction_id (25 distinct items). Pivot to a one-hot basket matrix, then mine.

Ranking the mined rules by lift surfaces the genuine patterns, and rejects the impostors:

RuleConfidenceLiftVerdict
{chips, soda} → salsa0.865.70strong, bundle for game day
diapers → beer0.745.05the legend, reproduced
butter → jam0.804.31real, classic pairing
bananas → bread0.371.10coincidence, bread is just popular

The last row is the lesson. Its 37% confidence looks like something, until you remember bread sits in 33% of all baskets anyway. Buying bananas barely moves the needle, so its lift is ~1: no real link. Rank by lift, filter by support, then act. That is market-basket analysis in one sentence.

5

Association Rules in Machine Learning & AI

The "what goes with what" question reaches far beyond the grocery aisle.

IdeaWhere it is used
Market-basket rulescross-sell, product bundling, store layout, checkout suggestions
Liftseparating real association from popularity in any co-occurrence data
Apriori / FP-Growthweb clickstream, medical co-morbidities, fraud pattern discovery
Item co-occurrencethe classic, transparent core of "customers also bought" recommenders
Frequent-pattern miningtext and log mining, bioinformatics motif discovery
🤖
Why this matters for AI research

Association rules are the original recommender system, and their great virtue is being transparent: a rule is a plain, auditable "if this then that," not a black box. Modern large-scale recommenders have largely moved to matrix factorization and neural embeddings (dimensionality reduction from the Dimensionality Reduction chapter, applied to users and items), which capture subtler taste than raw co-occurrence. But the association-rule mindset endures: lift remains the standard way to ask whether two events are linked or merely both common, a question that surfaces everywhere from A/B analysis to fraud detection to feature discovery. Simple, explainable, and still surprisingly hard to beat for interpretable recommendations.

🐍

Mine baskets in Python

The companion notebook reshapes receipts into a basket matrix, mines frequent itemsets with Apriori, ranks rules by support, confidence, and lift, exposes the popular-consequent trap, and confirms FP-Growth gives identical results faster, each cell explained.

📓 View Notebook (code & outputs) ▶ Open in Colab ⬇ View / Download on GitHub

View opens the rendered notebook instantly. Open in Colab runs it live. To run locally, install numpy, pandas, mlxtend, matplotlib, and openpyxl.

🎓 Key Takeaways

  • Association rules (A → B) describe which items co-occur, unsupervised, no target.
  • Support = how common the itemset is; it keeps rules trustworthy and powers the search.
  • Confidence = P(B given A), but it is inflated when B is popular.
  • Lift = confidence vs B's baseline; > 1 is a real association. Rank by lift.
  • Apriori prunes with downward closure; FP-Growth gets the same rules faster.
6

Practice Challenges

Five short challenges. Try them with mlxtend before checking the solutions.

1

Most frequent item

Build the basket matrix and report the item with the highest support.

Hint: pivot to one-hot, then basket.mean().
2

Frequent itemsets

Run Apriori at min_support = 0.05 and count the frequent itemsets.

Hint: apriori(basket, min_support=0.05, use_colnames=True).
3

Top rule by lift

Mine rules and report the single highest-lift rule.

Hint: association_rules(freq, metric='lift'); sort by lift.
4

Confidence vs lift

Find the lift of bananas → bread and explain why its confidence misleads.

Hint: compare confidence to bread's baseline support.
5

FP-Growth agreement

Confirm FP-Growth returns the same frequent itemsets as Apriori.

Hint: compare the sets of frozenset itemsets.
Check your work

A fully-worked solutions notebook walks through all five challenges, each verified in code. Try them yourself first, then compare.

📓 View Solutions ▶ Open Solutions in Colab ⬇ View / Download on GitHub
7

Quiz: Test Yourself

Eight quick questions on association rules. Answer them, hit Check Answers, and keep refining until you score 100%. Your progress is saved, so you can hop back to the chapter and return anytime.

➡️
Up next

We have grouped, compressed, and linked. The last unsupervised task is spotting what does not fit. Anomaly Detection finds the rare, suspicious points, fraud, faults, and intrusions, with statistical, distance-, and density-based methods, and the isolation forest.