Build a Market Basket Analysis Engine with Association Rule Mining
classical-ml recommendation-systems model-evaluation View full code for this problem
ML Problem & Solution
Market Basket Analysis with Association Rules
41,882 rules, 689 worth serving: lift finds patterns, leverage finds money.
A national grocery chain wants a “frequently bought together” module on the product page and a second one in the cart. The data is there: 8.4 million baskets over 90 days, 119 million line items, 62,411 active SKUs, a median basket of 11 items. The merchandising team also wants the same output to inform planogram and promotion decisions, which means every recommendation has to come with a reason a human can read and veto.
The textbook answer is association rule mining: find every pair or triple of items that co-occur more often than chance, rank them by confidence, serve the top six. Run that and you get 41,882 rules, and the top of the confidence ranking is a wall of bananas. Bananas appear in 31% of all baskets, so “buy tortilla chips, then buy bananas” arrives with a confidence of 0.42 and looks like the strongest signal in the dataset. It is not a signal at all. Recommending bananas to a shopper who was going to buy bananas anyway moves no revenue, and we measured exactly that: a confidence-ranked rule set shipped to 2.1 million sessions moved attach rate from 18.4% to 18.5%, which is inside the noise.
The second thing that goes wrong is scale, and it goes wrong in a way that looks like an infrastructure problem and is actually a modelling one. At the SKU level with a minimum support of 0.0005, the candidate space is 62,411 choose 2, which is 1.9 billion pairs before you even consider triples. Apriori, which walks that space by levels, ran for 14 hours and then exhausted 64 GB of RAM. The instinct is to raise the support threshold until it fits, but support and usefulness are in tension: the rules a merchandiser actually wants (barbecue sauce with hardwood charcoal, prenatal vitamins with caffeine-free tea) live at supports between 0.0002 and 0.002, which is exactly the band you delete to make the job finish.
The third failure is the one that survives all the way to production. Once the obvious metric problems are fixed and lift is used instead of confidence, the highest-lift rules turn out to be pairs like “plain Greek yogurt 500g with plain Greek yogurt 1kg”. Lift is maximised by rare, tightly coupled pairs, and the tightest couplings in a grocery catalogue are substitutes and pack-size variants of the same product, not complements. A recommendation module that suggests the 1kg tub to someone holding the 500g tub is either useless or actively cannibalising the sale in the cart.
The analogy that keeps this straight: a rule engine reading receipts is like a tourist inferring friendship from who shares a taxi. People who share a taxi at 2am are often genuinely connected. People who share a taxi from the airport are just going the same way, and the ones most likely to share are the ones who already arrived together.
Formally: given 8.4 million transactions over 62,411 items, find a rule set A -> B that maximises incremental attach rate in an online test, subject to a minimum support of 0.0005, at most 6 recommendation slots, a 40 ms p99 lookup, weekly refresh, and every served rule being explainable to a merchandiser in one sentence.
Framing the Problem
This is unsupervised pattern mining, and the framing trap is treating it as prediction. There is no label, no train/test split in the supervised sense, and no loss function being minimised. What exists instead is a family of interestingness measures, and choosing among them is the entire modelling decision. A rule mining project that spends its time on thresholds and none on which measure to rank by has skipped the only part that matters.
The output is a set of rules, each a pair (antecedent itemset, consequent itemset) with a handful of statistics attached. The “target” is defined only at evaluation time, in two layers. Offline, for a rule A -> B mined on days 1 to 60, the target is whether baskets in days 61 to 90 that contain A also contain B. Online, the target is incremental attach rate: the difference in units per basket between an arm that sees the rule set and a holdout that does not. The offline layer exists to filter; only the online layer decides.
Constraints, in the order they bind:
- Interpretability is a hard requirement, not a nice-to-have. The same rule set feeds a human planogram review. This is the constraint that keeps us on rule mining instead of embeddings, which score better and cannot be vetoed line by line.
- Serving latency p99 under 40 ms, which is easy: the rule set is small enough to precompute into a lookup table keyed by anchor item.
- Mining budget under 30 minutes on one 16 core machine, weekly.
- Catalogue churn: roughly 4% of SKUs turn over monthly, so any rule referencing a delisted item has to be dropped at serve time rather than at mine time.
- No cold start help available. A rule about an item with no transaction history cannot exist, so new products are out of scope for this system by construction.
The success metric is incremental attach rate from an A/B test. The guardrail metrics are revenue per basket, which must not regress (a module that swaps a high-margin item for a low-margin one can raise attach rate and lower revenue), and rule coverage, the share of sessions where at least one rule fires, which needs to stay above 60% or the module renders empty and the page looks broken.
Confidence is `P(B | A)`, which is maximised by making `B` a popular item. Lift is `P(B | A) / P(B)`, which corrects for that and is then maximised by making `B` rare. Leverage, `P(A and B) - P(A)P(B)`, is the one denominated in money: the number of *extra* co-occurrences above chance, in absolute basket counts. No single measure is sufficient, which is the real lesson. Lift is the right floor and the wrong sort key; leverage is the right sort key and a useless floor, because on its own it favours whichever pair is simply biggest.
Out of scope: sequence-aware rules (what gets bought next week rather than in the same basket), per-store rule sets, and price elasticity. Those are separate systems and each one doubles the evaluation burden.
Data and Features
The source is a line-item table: 119 million rows of (basket_id, sku, quantity, unit_price, store_id, ts) over 90 days. The feature engineering in market basket analysis is almost entirely two decisions: what counts as an item, and what counts as a basket.
What counts as an item is the decision that makes or breaks the whole project. Mining at raw SKU level gives 62,411 items, a 1.9 billion pair candidate space, and rules so specific they are useless (“Chobani strawberry 150g with Chobani blueberry 150g”). Rolling up to the chain’s 1,180 product subcategories gives a tractable candidate space and rules a merchandiser recognises (“Greek yogurt with granola”). We mine at subcategory level and then resolve each recommended subcategory back to a specific SKU at serve time using in-stock and margin rules, which keeps the pattern mining statistically stable and pushes the merchandising choice to where it belongs.
| Granularity | Items | Candidate pairs | Frequent itemsets at support 0.0005 | Verdict |
|---|---|---|---|---|
| Raw SKU | 62,411 | 1.9e9 | out of memory at 64 GB | unusable |
| Product group | 8,942 | 4.0e7 | 121,447 | rules too specific to act on |
| Subcategory | 1,180 | 6.9e5 | 18,447 | what we ship |
| Department | 74 | 2.7e3 | 812 | everything co-occurs, lift near 1 |
What counts as a basket is subtler. One physical shopping trip can produce several rows in the transaction system: a split payment, a partial cancellation and rescan, an online order shipped in two parcels. Treating those as separate baskets inflates support for items that commonly get rescanned (produce, anything weighed) and deflates cross-department rules. We collapse to one basket per (customer_id, store_id, calendar day) for in-store and per order for online.
# Basket encoding: line items to a sparse boolean basket x item matrix.
# Dense would be 8.4e6 x 1180 bools = 9.9 GB. Sparse with 119e6 nonzeros is ~1 GB.
import numpy as np
import pandas as pd
from scipy.sparse import csr_matrix
def build_basket_matrix(lines: pd.DataFrame, item_col: str = "subcategory_id"):
"""One row per basket, one boolean column per item. Quantity is discarded.
Association rules are defined over set membership, so buying 6 yogurts is
the same event as buying 1. Keeping quantity here is a common and quiet
mistake: it makes support depend on pack behaviour rather than on choice.
"""
baskets = lines["basket_id"].astype("category")
items = lines[item_col].astype("category")
pairs = pd.DataFrame({"b": baskets.cat.codes, "i": items.cat.codes}).drop_duplicates()
matrix = csr_matrix(
(np.ones(len(pairs), dtype=bool), (pairs["b"], pairs["i"])),
shape=(len(baskets.cat.categories), len(items.cat.categories)),
)
return matrix, list(items.cat.categories), list(baskets.cat.categories)
Encoding quantity instead of membership. Support, confidence and lift are all defined on set membership, so a basket with 6 yogurts must contribute exactly what a basket with 1 yogurt contributes. Passing counts through makes every metric a function of pack size and weighing behaviour, and the rules that surface are the ones for items people buy in bulk rather than the ones people buy together.
The leakage specific to this problem
Rule mining has no labels, which makes practitioners assume it cannot leak. It leaks in three ways, and the third one is the expensive one.
First, the ordinary kind: mining and evaluating on the same baskets. A rule’s confidence measured on the baskets it was mined from is a training-set statistic, and it is optimistic by construction because the threshold search selected for it. Mine on days 1 to 60, evaluate on days 61 to 90.
Second, promotion contamination. If charcoal and barbecue sauce were on a linked BOGO promotion for two weeks inside the mining window, they will co-occur far above chance and produce a beautiful rule that describes a promotion rather than a shopping habit. The rule dies the day the promotion ends. We join the promotion calendar and exclude basket-days where both sides of a candidate rule were on a linked offer, which removed 1,431 of the 41,882 raw rules, including 9 of the top 50 by lift.
Third, seasonality masquerading as affinity. Mine a January window and you get “cold remedy with tissues” at lift 4.2. That rule is real in January and worthless in July. The forward-window evaluation catches this only if the forward window is in a different season, which is the argument for evaluating on a rolling forward window all year rather than once.
# Time split plus promotion exclusion. Both are leakage controls, not tuning.
def split_baskets(lines: pd.DataFrame, mine_days: int = 60):
"""Mine on the first mine_days, evaluate on the rest. Never the same baskets."""
cutoff = lines["ts"].min() + pd.Timedelta(days=mine_days)
return lines[lines["ts"] < cutoff].copy(), lines[lines["ts"] >= cutoff].copy()
def drop_promo_contaminated(lines: pd.DataFrame, promos: pd.DataFrame) -> pd.DataFrame:
"""Remove line items covered by a linked multi-item offer during the window.
A linked offer manufactures co-occurrence. Leaving it in produces rules that
describe last month's promotion calendar and expire when it does.
"""
linked = promos.loc[promos["offer_type"] == "linked_multi_item",
["subcategory_id", "start_ts", "end_ts"]]
merged = lines.merge(linked, on="subcategory_id", how="left")
covered = (merged["ts"] >= merged["start_ts"]) & (merged["ts"] <= merged["end_ts"])
return merged.loc[~covered.fillna(False), lines.columns].copy()
The granularity choice does more for rule quality than any threshold. Moving from SKU to subcategory took mining from out-of-memory to 4 minutes, and it raised mean forward-window precision from 0.11 to 0.24, because a subcategory has 53 times more transactions behind each support estimate. Most "my rules are noisy" problems are really "my items are too specific" problems.
The Naive Baseline
Two baselines, because the interesting one is the second.
Popularity. Show every shopper the six most-purchased subcategories. It needs no mining at all, and it is the baseline that recommendation systems most often fail to beat. Offline hit rate at 6 slots is 0.081. In a four week A/B test on 2.1 million sessions per arm it moved attach rate from 18.4% to 18.8%, a real but small +0.4 points.
Confidence-ranked rules. Mine with a minimum support of 0.0005, generate every rule with confidence above 0.1, sort by confidence, take the top six per anchor item. This is the textbook recipe.
# The textbook baseline: FP-Growth, then rank by confidence. Offline it looks great.
from mlxtend.frequent_patterns import association_rules, fpgrowth
frequent = fpgrowth(basket_df, min_support=0.0005, use_colnames=True, max_len=3)
rules = association_rules(frequent, metric="confidence", min_threshold=0.1)
top = rules.sort_values("confidence", ascending=False).head(10)
print(top[["antecedents", "consequents", "support", "confidence", "lift"]])
Offline, confidence ranking beats popularity convincingly: hit rate at 6 slots of 0.149, nearly double. Online it did nothing worth having. Attach rate went from 18.4% to 18.5%, and at 2.1 million sessions per arm the standard error on that difference is about 0.04 points, so +0.1 is statistically significant and commercially worthless: revenue per basket did not move at all, and the no-mining popularity baseline delivered four times the attach lift. This is worth dwelling on, because a p-value would have waved this launch through. The gate that rejects it is a minimum effect size, not a significance test.
The reason is visible in the rules themselves. Here are the top five by confidence, with the consequent’s own baseline support alongside:
| Rule | Confidence | Consequent base support | Lift |
|---|---|---|---|
| tortilla chips -> bananas | 0.42 | 0.31 | 1.355 |
| pasta sauce -> bananas | 0.40 | 0.31 | 1.290 |
| breakfast cereal -> whole milk | 0.39 | 0.28 | 1.393 |
| ground coffee -> bananas | 0.38 | 0.31 | 1.226 |
| paper towels -> bananas | 0.37 | 0.31 | 1.194 |
Every one of them is a rule about how popular bananas and milk are. Confidence of 0.42 against a base rate of 0.31 means the antecedent moved the probability by 11 points, and we then spent a recommendation slot on an item the shopper had a 31% chance of buying unprompted. The offline hit rate metric rewarded exactly this, because a hit is counted whenever the shopper buys the item, not whenever the module caused it. That gap between “predicted correctly” and “changed the outcome” is the whole problem with this baseline, and it is not fixable by tuning the support threshold.
The Solution
Three changes, in order of how much they mattered: mine with FP-Growth so the useful support band is reachable at all, rank by leverage rather than confidence or lift, then apply actionability filters that encode what a recommendation slot is actually for.
Mining: FP-Growth over Apriori
Apriori is breadth-first over itemset size. To find frequent triples it generates every candidate triple from the frequent pairs and scans the whole transaction set again to count them. That is one full pass per level, and the candidate count explodes before the pruning helps.
FP-Growth reads the data exactly twice. The first pass counts single-item frequencies. The second builds an FP-tree, a prefix tree of the transactions with items ordered by descending frequency, so baskets that share a common prefix share tree nodes. Mining then walks the tree recursively, extracting patterns from conditional sub-trees without ever regenerating candidates or rescanning the input.
The analogy: Apriori re-reads the whole pile of receipts once for every combination size it is testing. FP-Growth reads the pile twice, files the receipts into a single shared tree of shopping prefixes, and then answers every question from the tree.
| Algorithm | Items | Wall clock | Peak memory | Outcome |
|---|---|---|---|---|
| Apriori | 62,411 SKUs | killed at 14 h | 64 GB exhausted | no result |
| Apriori | 1,180 subcategories | 41 min 20 s | 9.4 GB | same rules as FP-Growth |
| FP-Growth | 1,180 subcategories | 4 min 12 s | 11.2 GB | what we ship |
| FP-Growth | 62,411 SKUs | 38 min 05 s | 47 GB | works, rules too specific |
FP-Growth uses slightly more memory at this size because the tree is held in RAM, and it is roughly 10 times faster. The important line is the first one: the choice of algorithm is what makes the support band between 0.0002 and 0.002 reachable, and that band is where the rules a merchandiser wants actually live.
# The mining step. max_len=3 because 4-item rules are unservable in 6 slots
# and roughly triple the rule count.
import pandas as pd
from mlxtend.frequent_patterns import association_rules, fpgrowth
def mine_rules(basket_df: pd.DataFrame, min_support: float = 0.0005,
min_confidence: float = 0.1, max_len: int = 3) -> pd.DataFrame:
"""Frequent itemsets then rules, with every interestingness measure attached."""
frequent = fpgrowth(basket_df, min_support=min_support,
use_colnames=True, max_len=max_len)
rules = association_rules(frequent, metric="confidence",
min_threshold=min_confidence)
# Leverage in absolute basket counts: what a merchandiser can reason about.
rules["excess_baskets"] = rules["leverage"] * len(basket_df)
return rules.sort_values("leverage", ascending=False).reset_index(drop=True)
Ranking: why leverage
The four measures on the same rule, so the difference is concrete. Take charcoal -> barbecue sauce on our data: P(charcoal) = 0.008, P(sauce) = 0.041, P(both) = 0.0021.
- Support = 0.0021. How often the pair happens. Says nothing about whether it is surprising.
- Confidence =
P(both) / P(charcoal)= 0.26. Maximised by a popular consequent, which is how bananas won. - Lift =
0.26 / 0.041= 6.4. Corrects for consequent popularity, and is then maximised by a rare consequent, because dividing by a tinyP(B)makes the ratio explode. This is why pack-size variants dominate a lift ranking. - Leverage =
P(both) - P(charcoal)P(sauce)=0.0021 - 0.000328= 0.001772. Multiply by 8.4 million baskets and it is 14,885 co-occurrences above chance. That is a quantity in units of baskets, which is what makes two rules comparable in terms a merchandiser can act on.
Conviction, (1 - P(B)) / (1 - confidence), is the fifth one worth knowing: it measures how much the rule would have to be wrong to be independent, and unlike lift it is asymmetric, which matters because A -> B and B -> A are different recommendations.
Now the part that is easy to get wrong, and that we got wrong first. Leverage on its own does not remove the bananas. Run the numbers on tortilla chips -> bananas: P(chips) = 0.052, P(bananas) = 0.31, P(both) = 0.0218, so leverage is 0.0218 - 0.0161 = 0.0057, which is 48,048 excess baskets. That is more than three times the charcoal rule’s 14,885. Leverage is a difference of probabilities, so it grows with the size of both sides, and the biggest pairs in the catalogue win it outright.
What removes the bananas is the lift floor. Chips to bananas has a lift of 1.355, so a min_lift of 1.5 deletes it before any ranking happens. The division of labour is the actual design:
| Measure | Role | Why not the other role |
|---|---|---|
| Confidence | neither | Maximised by a popular consequent. Useless as floor and as sort key. |
| Lift | the floor | As a sort key it promotes rare, tightly coupled pairs, which in a grocery catalogue means substitutes and pack-size variants. |
| Leverage | the sort key | As a floor it is dominated by sheer size, so on its own it keeps every high-support pair including the ones lift just rejected. |
| Conviction | secondary filter | Asymmetric, so it catches one-directional rules that lift scores symmetrically. |
So: filter on lift to keep only rules that are surprising, then sort the survivors by leverage to prefer the ones with the most baskets behind them. Neither half works alone. There is no loss function here, so this pair of choices plays the role a loss function plays in supervised learning: it defines what “good” means, and every downstream number inherits it. Choosing confidence is choosing to be graded on predicting purchases the shopper would have made anyway.
Filtering: encoding what a slot is for
Metric filters alone take 41,882 rules to 2,304. They do not remove the substitutes problem, because a pack-size variant has excellent lift, excellent leverage and excellent confidence. That needs filters that encode merchandising logic:
# Actionability filters. This is where domain knowledge enters the pipeline.
def filter_actionable(rules: pd.DataFrame, taxonomy: dict,
max_consequent_support: float = 0.15,
min_lift: float = 1.5,
min_leverage: float = 0.0002) -> pd.DataFrame:
"""Keep rules that are surprising, substantial, and worth a slot."""
keep = (rules["lift"] >= min_lift) & (rules["leverage"] >= min_leverage)
# A consequent in more than 15% of baskets cannot be incremental: the
# shopper was probably buying it anyway. This is the bananas filter.
keep &= rules["consequent support"] < max_consequent_support
# Same-parent-category pairs are substitutes or pack sizes, not complements.
def different_category(row) -> bool:
parents_a = {taxonomy[i] for i in row["antecedents"]}
parents_b = {taxonomy[i] for i in row["consequents"]}
return parents_a.isdisjoint(parents_b)
keep &= rules.apply(different_category, axis=1)
# Imbalance ratio: a rule that only works in one direction is fragile.
both = rules["support"]
imbalance = (rules["antecedent support"] - rules["consequent support"]).abs() / (
rules["antecedent support"] + rules["consequent support"] - both)
keep &= imbalance < 0.85
return rules.loc[keep].sort_values("leverage", ascending=False).reset_index(drop=True)
The funnel, with what each stage removes:
| Stage | Rules remaining | What it removed |
|---|---|---|
| Frequent itemsets, support 0.0005, max_len 3 | 18,447 itemsets | nothing yet |
| Rules with confidence above 0.1 | 41,882 | rules too weak to be worth generating |
| Promotion contamination excluded | 40,451 | 1,431 rules describing the promo calendar |
| Lift above 1.5 and leverage above 0.0002 | 2,304 | unsurprising rules: the lift floor is what deletes the bananas, at lift 1.355 |
| Consequent support below 0.15 | 1,867 | remaining near-ubiquitous consequents |
| Different parent category | 812 | substitutes and pack-size variants |
| Imbalance ratio below 0.85 | 689 | one-directional, fragile rules |
Hyperparameters that matter, with the values we shipped: min_support = 0.0005 (about 4,200 baskets, the smallest support whose lift is stable under bootstrap), max_len = 3 (4-item rules cannot be served in 6 slots and roughly triple the rule count), min_lift = 1.5, min_leverage = 0.0002 (about 1,680 excess baskets, the point below which the A/B effect became unmeasurable), and max_consequent_support = 0.15.
The single decision that mattered most was splitting the job between two measures: lift as the floor, leverage as the sort key. Every attempt to pick one measure and use it for both failed in a different direction, and the failures are not symmetric. Confidence ranking gave +0.1 attach points, lift ranking surfaced pack-size substitutes, leverage as a floor kept the bananas it was supposed to remove. Lift floor plus leverage sort gave +1.9, from the same mining run over the same 8.4 million baskets.
Evaluation and Metrics
Three layers, and each one exists because the layer above it lies.
Forward-window rule precision. For a rule mined on days 1 to 60, look at days 61 to 90: of the baskets containing the antecedent, what share contain the consequent? Compare that to the mined confidence. The gap is the overfitting:
# Forward-window precision: the honest version of confidence.
def forward_precision(rules: pd.DataFrame, future_matrix, item_index: dict) -> pd.DataFrame:
"""Re-measure every rule on baskets it was not mined from."""
out = []
for _, rule in rules.iterrows():
a_cols = [item_index[i] for i in rule["antecedents"]]
b_cols = [item_index[i] for i in rule["consequents"]]
has_a = future_matrix[:, a_cols].toarray().all(axis=1)
has_b = future_matrix[:, b_cols].toarray().all(axis=1)
n_a = int(has_a.sum())
out.append({
"antecedents": rule["antecedents"],
"consequents": rule["consequents"],
"mined_confidence": rule["confidence"],
"forward_precision": float((has_a & has_b).sum() / n_a) if n_a else 0.0,
"forward_support_baskets": n_a,
})
return pd.DataFrame(out)
Across the 689 served rules, mean mined confidence is 0.31 and mean forward precision is 0.24, so the mined numbers are 23% optimistic. That shrinkage is not a bug to fix, it is the cost of having chosen thresholds on the mining window, and knowing its size is what lets us set expectations before the A/B test.
Lift stability under bootstrap. Resample the mining baskets 20 times and recompute each rule’s lift. Rules above support 0.001 have a lift coefficient of variation of 8%. Rules between 0.0002 and 0.0005 have a CV of 41%, which means their lift is essentially a draw from a wide distribution and any threshold applied to it is arbitrary. This is what set the minimum support, not a round number.
The A/B test, which is the only layer that decides. Four weeks, 2.1 million sessions per arm, four arms:
| Arm | Offline hit rate at 6 | Mean forward precision | Rules served | Attach rate | Revenue per basket |
|---|---|---|---|---|---|
| Control, no module | n/a | n/a | 0 | 18.4% | baseline |
| Top-6 popularity | 0.081 | n/a | 0 | 18.8% (+0.4) | +0.1% |
| Confidence-ranked rules | 0.149 | 0.28 | 4,000 | 18.5% (+0.1) | 0.0% |
| Lift floor plus leverage sort | 0.112 | 0.24 | 689 | 20.3% (+1.9) | +0.6% |
Every one of those differences is statistically significant at 2.1 million sessions per arm, which is precisely why significance is not the launch gate. We hold anything below +0.5 attach points, so the popularity arm and the confidence arm are both rejected for being real and too small to be worth a module on the page.
The row ordering is the lesson. The arm with the best offline hit rate produced no online effect, and the arm we shipped has a lower offline hit rate and lower forward precision than the arm that failed. Offline hit rate counts a success whenever the shopper buys the recommended item, including when they would have bought it regardless. It is not a measure of the module’s contribution, and on this problem it is anti-correlated with the thing we care about.
Even the winning arm is not uniformly good. Breaking the +1.9 points down by rule, 274 of the 689 rules had no measurable incremental effect at all, and 31 had a negative point estimate, consistent with cannibalisation inside the cart. The aggregate win came from roughly 380 rules.
The signal that catches silent decay is **forward precision of the live rule set, recomputed daily on yesterday's baskets**, alongside rule coverage. Attach rate is too noisy day to day to catch a slow rot, and it is confounded by every other change to the page. Forward precision is measured per rule, needs no experiment, and drops immediately when a rule's underlying pattern stops holding, which is what happens every time a promotion ends or a supplier changes.
Common Pitfalls and Failure Modes
| Pitfall | Why It Happens | How to Detect | How to Fix |
|---|---|---|---|
| Ranking by confidence | It is the intuitive “how often is the rule right” number and the textbook default | Top rules all share a handful of popular consequents; here every one was bananas or milk | Rank by leverage; filter on consequent support below 0.15 |
| High-lift substitutes | Lift is maximised by rare, tightly coupled consequents, and pack-size variants are the tightest couplings in the catalogue | Antecedent and consequent share a parent category | Drop same-parent-category rules outright |
| Promotion contamination | A linked offer manufactures co-occurrence inside the mining window | Rule lift collapses the week after a promo ends | Join the promotion calendar and exclude linked-offer basket-days before mining |
| Quantity encoded instead of membership | The line-item table has a quantity column and it looks like information | Support correlates with typical pack size across items | Deduplicate to set membership per basket |
| Rare-rule instability | Support below roughly 0.0005 gives lift estimates with 40% coefficient of variation | Bootstrap the mining baskets and compute per-rule lift CV | Set the support floor from the bootstrap, not from a round number |
| Aggregating over heterogeneous stores | A rule can hold in every store and reverse in aggregate, or the reverse | Mine two store clusters separately and compare rule sign | Segment by store format before mining, or add store cluster to the basket key |
| Offline metric optimisation | Hit rate at k is easy to compute and available without an experiment | Offline metric improves while A/B effect does not move | Treat offline metrics as filters only; gate every launch on an incremental test |
Simpson’s paradox in the store-aggregation row deserves its own note, because it is the one that produces a confidently wrong rule. We found “premium olive oil with fresh pasta” at lift 2.3 chain-wide. Split by store format, the rule held at lift 1.4 in urban stores and 1.3 in suburban ones, and the chain-wide 2.3 was mostly an artifact of urban stores having both higher premium oil penetration and higher fresh pasta penetration. The pattern was real but roughly half as strong as the aggregate number claimed, and a promotion sized off 2.3 would have overbought.
The mistake almost everyone makes first is believing a high-lift rule is an actionable one. Lift answers "is this co-occurrence surprising", which is a question about the data. A recommendation slot asks "will showing this change what the shopper does", which is a question about causation, and no interestingness measure computed from transaction logs can answer it. The only instrument that can is an experiment, which is why 274 of our 689 rules turned out to do nothing despite passing every offline filter.
Every pitfall above except the last one is a mistake about what a metric means, not a mistake in the code. Rule mining is unusually exposed to this because it produces plausible-looking output no matter what you feed it: there is no loss curve to diverge, no validation score to collapse, and no exception to catch. The output of a badly specified rule miner is 41,882 confident, well-formatted, useless rules.
Scaling and Productionizing
The mining job is a weekly batch, and the serving side is almost free, which makes this one of the rare models where production is simpler than the notebook.
Serving is a dictionary. 689 rules keyed by antecedent itemset is 40 KB of JSON. It loads into process memory, needs no feature store, no model server and no network hop, and the p99 lookup is 0.3 ms against a 40 ms budget. What the serving layer does need is a filter chain at request time: drop rules whose consequent is out of stock at that store, whose consequent is already in the cart, or whose SKU has been delisted since the last mine. That last filter is why rules are stored at subcategory level and resolved to SKUs on the fly, and it handles the 4% monthly catalogue churn without a remine.
Mining scales by transaction count, which is the easy axis. The FP-tree size depends on the number of distinct items and the depth of shared prefixes, not on the number of baskets, so doubling the baskets roughly doubles the second pass and leaves peak memory almost unchanged:
Line items 119e6 rows, (basket_id, sku) as int32 = 952 MB
Basket matrix 8.4e6 x 1,180 sparse bool, 92e6 nnz = 1.1 GB
FP-tree 1,180 items, 8.4e6 baskets = 11.2 GB peak
FP-Growth mining min_support 0.0005, max_len 3 = 4 min 12 s, 16 cores
Rule generation 18,447 itemsets to 41,882 rules = 38 s
Filters plus bootstrap 20 resamples for lift stability = 6 min 40 s
Served artifact 689 rules as JSON = 40 KB
Serving lookup dict hit plus stock filter = 0.3 ms p99
Weekly job total = 12 min 10 s
At 10 times the baskets the FP-tree stops fitting comfortably and the answer is Spark’s FPGrowth, which partitions the mining by conditional pattern base. The rule set it produces is identical; only the execution changes. The threshold where that becomes worth the operational cost, in our experience, is around 80 million baskets.
Refresh cadence is set by pattern decay, not by the calendar. We remine weekly, and the measurement that justified weekly rather than monthly is the decay of forward precision: the mean forward precision of a rule set is 0.24 in its first week of service, 0.22 in the second, 0.19 in the third and 0.16 in the fourth. A monthly cadence would spend its last week serving rules a third worse than at launch.
The monitoring signal for silent degradation is the pair (daily forward precision of the live rule set, rule coverage). Forward precision catches patterns that stop holding. Coverage catches the quieter failure: a taxonomy change or a delisting wave can make half the rule set unservable, the module renders empty, and attach rate drifts down with no error anywhere in the logs. Coverage below 60% pages someone; forward precision below 0.18 triggers an early remine.
The famous "beer and diapers" story comes from a 1992 Osco Drug analysis via Teradata, and the detail usually left out is that the rule was never deployed: the correlation was real and there was no profitable action to take on it, which is precisely the gap between lift and leverage. When Amazon built recommendations at catalogue scale they did not use association rules at all. Linden, Smith and York's 2003 IEEE Internet Computing paper describes item-to-item collaborative filtering, which precomputes an item similarity matrix from co-occurrence and scales with catalogue size rather than with the combinatorics of itemsets. Association rule mining survives where Amazon's approach does not help: when a human has to read the pattern, agree with it, and put it in a planogram.
Alternative Approaches
| Approach | Forward precision at 6 | Training and serving cost | Interpretability | Best fit |
|---|---|---|---|---|
| Association rules, FP-Growth plus leverage | 0.24 | 12 min weekly, 40 KB artifact, 0.3 ms | Excellent: every rule is one readable sentence with a basket count | Output feeds human merchandising decisions, and slots need a vetoable reason |
| Item-to-item collaborative filtering | 0.27 | 22 min weekly, 8 MB similarity matrix, 0.6 ms | Good: “shoppers who bought X also bought Y”, no threshold to explain | Product page recommendations at catalogue scale with no human review step |
| Matrix factorisation, ALS 64 factors | 0.29 | 1 h 10 min weekly, 31 MB, 2.1 ms | Poor: latent factors have no merchandising meaning | Personalised recommendations where the user history matters more than the basket |
| Item2vec embeddings, 128 dims | 0.31 | 2 h 40 min weekly, 62 MB, 3.4 ms | Poor: nearest neighbours only, no stated reason | Maximum accuracy, no interpretability requirement, engineering capacity to maintain it |
| Supervised re-ranker over rule and embedding features | 0.34 | 3 h weekly plus a labelled click log, 18 ms | Moderate via feature attribution | Mature setup with reliable click logs and an existing candidate generator |
What we would actually ship, and did, is two systems rather than the top row alone. Item2vec for the product page module, association rules for the cart module and for the merchandising workflow. The product page has no human in the loop and rewards raw accuracy, so the 7 point forward precision advantage is worth taking. The cart module and the planogram review both require a stated reason, and “these two appear together in 14,885 more baskets than chance would predict” is a sentence a category manager can act on, while “the embedding cosine is 0.81” is not.
We would drop the rules entirely if the merchandising workflow went away, and we would go rules-only if the team could not maintain an embedding pipeline, which is a real constraint more often than accuracy tables suggest. The supervised re-ranker is the right long-term answer and the wrong first build: it needs a click log that only exists after something has been shipped.
Key Takeaways
- No single interestingness measure does the job. Lift is the floor and leverage is the sort key, because each is maximised by the wrong thing when used alone: confidence by a popular consequent, lift by a rare one, leverage by sheer size. Lift floor plus leverage sort gave +1.9 attach points against confidence ranking’s +0.1.
- Leverage does not remove the bananas.
tortilla chips -> bananashas 48,048 excess baskets against the charcoal rule’s 14,885, so a leverage floor keeps it. The lift floor of 1.5 is what deletes it, at lift 1.355. - Item granularity beats every threshold. Rolling SKUs up to subcategories took mining from out-of-memory to 4 minutes and more than doubled mean forward precision, because each support estimate had 53 times more data behind it.
- FP-Growth is what makes the useful support band reachable. Two passes and a prefix tree instead of one pass per itemset size: 4 minutes against 41, and the difference decides whether rules at support 0.0005 exist at all.
- There is no loss function, so the interestingness measure is the model. Choosing it is not a tuning detail; every downstream number inherits the definition of “good” it encodes.
- Rule mining leaks in ways that have nothing to do with labels. Promotion calendars manufacture co-occurrence, seasonality masquerades as affinity, and mining-window confidence was 23% optimistic against a forward window.
- Offline metrics were anti-correlated with the online result. The arm with the best hit rate at 6 did nothing, and the arm we shipped scored lower offline. Hit rate counts purchases, not contributions.
- Most rules do nothing, and that is fine. 274 of 689 rules had no measurable effect and 31 were slightly negative; the +1.9 points came from about 380. Expect a long tail of inert rules rather than a uniformly good rule set.
The counter-intuitive lesson is that the best offline number we had was actively misleading, and we would have shipped the wrong system twice if we had trusted it. Confidence ranking doubled hit rate at 6 and moved nothing. The configuration that won had a worse hit rate and worse forward precision, because both of those metrics reward predicting what a shopper does, while a recommendation slot is only worth anything when it changes what a shopper does. Association rule mining is very good at finding patterns and structurally incapable of telling you which patterns are worth acting on, and no amount of better mining fixes that: only an experiment does.
Frequently Asked Questions
Q: Why not use Apriori, since it finds the same rules? A: It does find the same rules, and at subcategory level it takes 41 minutes against FP-Growth’s 4. The decision is not about those 37 minutes, it is about which support thresholds are reachable at all. At SKU level Apriori exhausted 64 GB and never finished, so the entire question of whether SKU-level rules are useful could not be answered with it. Apriori is worth keeping for teaching, because the level-wise candidate generation makes the downward-closure property obvious, and worth avoiding in production.
Q: Why not skip rules and use embeddings, which score better? A: We use both, for different surfaces. Item2vec scored 0.31 forward precision against the rules’ 0.24, and on the product page, where nothing is reviewed by a human, that advantage is worth taking. The cart module and the planogram workflow need a stated reason per recommendation that a category manager can veto, and “14,885 co-occurrences above chance” is that reason while a cosine similarity is not. The interpretability requirement is doing real work here, not standing in for a preference.
Q: How do I pick the minimum support threshold? A: Bootstrap it rather than guessing. Resample the mining baskets 20 times, recompute each rule’s lift, and look at the coefficient of variation by support band. Ours was 8% above support 0.001 and 41% between 0.0002 and 0.0005, so 0.0005 is where lift stops being a stable estimate and starts being a draw from a wide distribution. Any threshold below the point where your metric is stable is a threshold on noise. The same logic set the 15% cap on consequent support: we binned rules by consequent support and the per-rule A/B effect went flat above roughly that point, because incremental effect is bounded by how often the shopper was not already going to buy the item. Both are chain-specific numbers worth re-deriving on your own data.
Q: The confidence-ranked arm was statistically significant. Why not ship it? A: Because significance answers “is the effect real”, not “is it worth having”. At 2.1 million sessions per arm the standard error on an attach-rate difference is about 0.04 points, so a +0.1 point effect clears a p-value test easily. It also delivered zero revenue per basket and less than a quarter of what a no-mining popularity baseline delivered. Decide the minimum effect worth shipping before you look at the result, and gate on that as well as on the p-value: at large sample sizes, everything is significant.
Q: What is the difference between lift and leverage in one sentence? A: Lift is a ratio, so it tells you how surprising the co-occurrence is and treats a rule affecting 50 baskets the same as one affecting 50,000; leverage is a difference, so multiplied by basket count it tells you how many extra co-purchases the pattern represents, which is the quantity a recommendation slot is competing for.
Q: What breaks first in production? A: Rule coverage, usually after a taxonomy change. Someone reorganises the product hierarchy, the subcategory ids in the served rule set no longer resolve, coverage falls, the module renders empty, and attach rate drifts down with no error in any log. Monitor the share of sessions where at least one rule fires and alert on it, because this failure is completely silent from the model’s point of view.
Interview Questions
Q: A rule has confidence 0.85. Should you act on it? Expected depth: Ask for the consequent’s base support before answering anything else. If the consequent appears in 80% of baskets, confidence 0.85 is barely above independence and lift is about 1.06. Walk through support, confidence, lift and leverage and state what each is maximised by: confidence by a popular consequent, lift by a rare one, leverage by neither. Then make the stronger point, that none of them measure incremental effect, and that the answer depends on an experiment rather than on any statistic computable from the log.
Q: Explain why FP-Growth is faster than Apriori, and when it is not. Expected depth: Apriori is level-wise: it generates candidate k-itemsets from frequent (k-1)-itemsets and rescans the transactions to count them, so it pays one full pass per level and suffers from candidate explosion. FP-Growth makes two passes, builds a frequency-ordered prefix tree so shared basket prefixes share nodes, and mines conditional sub-trees recursively with no candidate generation. FP-Growth loses when the tree does not compress, which happens with many distinct items and little prefix sharing, since the tree then approaches the size of the raw data in memory. Mention the downward-closure property as what both rely on for pruning.
Q: You mine rules in December and attach rate drops in February. Diagnose it. Expected depth: Seasonality first: December rules encode holiday co-purchase patterns that do not hold in February, which is a distribution shift rather than a bug. Then promotion contamination, if linked offers were running in the mining window. Then catalogue churn breaking rule resolution and dropping coverage. The diagnostic is per-rule forward precision on recent baskets plus coverage, both of which distinguish these without an experiment. The fix is a rolling remine and a forward-precision alarm, not a threshold change.
Q: How would you evaluate an association rule system before shipping it? Expected depth: Three layers with clear roles. Forward-window precision, mined on one period and measured on the next, to quantify the optimism of the mined statistics. Bootstrap stability of lift to set the support floor. An online incremental test as the only launch gate. Be explicit that hit rate at k is not a measure of contribution because it counts purchases the shopper would have made regardless, and mention that on this problem offline hit rate was anti-correlated with the online result.
Q: Your top rule is “500g Greek yogurt implies 1kg Greek yogurt” with lift 9.1. What is wrong? Expected depth: The rule describes substitutes or pack-size variants, not complements, so the recommendation is either redundant or cannibalises the item already in the cart. Explain why lift surfaces these: it divides by the consequent’s base rate, so rare and tightly coupled pairs dominate, and within-product variants are the most tightly coupled pairs in a grocery catalogue. The fix is a taxonomy-aware filter dropping same-parent-category rules, and the broader point is that interestingness measures are blind to the difference between a substitute and a complement, which has to be supplied as domain knowledge.
View full code for this problem