Reading history

Association Rules in Python: Apriori, Support, Confidence and Lift

8 min read 0 views

Learn market basket analysis in Python: compute support, confidence and lift, and write the Apriori algorithm from scratch to find frequent itemsets and rules.

Shops want to know which products are bought together. If people who buy lentils nearly always buy rice, the shop can place them side by side or offer a combo deal. Association rules find these patterns, and Apriori is the classic method for finding them quickly. In this lesson you will compute support, confidence and lift by hand, then write Apriori from scratch in plain Python.

In this lesson you will learn

  • What an association rule like {lentils} → {rice} means
  • How to compute support, confidence and lift
  • Why lift matters more than confidence alone
  • How Apriori prunes the search to stay fast
  • How to write Apriori and generate rules in Python

You should know Python sets and loops. This is unsupervised learning: there are no labels.

Support, Confidence and Lift

A rule A → C reads “if a basket has A, it tends to also have C”. Three numbers describe it:

MeasureFormulaMeaning
Supportbaskets with A and C ÷ all basketsHow common the pair is
Confidencesupport(A and C) ÷ support(A)Of the baskets with A, the share that also have C
Liftconfidence ÷ support(C)How much A raises the chance of C

A lift of 1 means A and C have nothing to do with each other. Above 1, A makes C more likely. Below 1, A makes C less likely.

# Ten shopping baskets from a small grocery shop
baskets = [
    {"rice", "lentils", "onion"},
    {"rice", "lentils"},
    {"bread", "butter", "eggs"},
    {"rice", "onion", "oil"},
    {"bread", "butter"},
    {"rice", "lentils", "oil"},
    {"bread", "eggs"},
    {"rice", "lentils", "onion", "oil"},
    {"tea", "sugar", "bread"},
    {"tea", "sugar"},
]
N = len(baskets)

def support(items):
    """Share of baskets that contain ALL the given items."""
    return sum(items <= b for b in baskets) / N

def rule(a, c):
    s_both = support(a | c)
    confidence = s_both / support(a)       # P(c in basket | a in basket)
    lift = confidence / support(c)         # > 1 means a raises the chance of c
    print(f"{sorted(a)} -> {sorted(c)}: support {s_both:.2f}, "
          f"confidence {confidence:.2f}, lift {lift:.2f}")

rule({"lentils"}, {"rice"})
rule({"rice"}, {"lentils"})
rule({"tea"}, {"sugar"})
rule({"bread"}, {"rice"})

Output

['lentils'] -> ['rice']: support 0.40, confidence 1.00, lift 2.00
['rice'] -> ['lentils']: support 0.40, confidence 0.80, lift 2.00
['tea'] -> ['sugar']: support 0.20, confidence 1.00, lift 5.00
['bread'] -> ['rice']: support 0.00, confidence 0.00, lift 0.00
  • items <= b is Python’s subset test: it is true when every item is in the basket.
  • All 4 baskets with lentils also have rice, so confidence is 1.00. Rice is in half of all baskets, so lentils double the chance of rice: lift 2.00.
  • Rules are not symmetric. Only 4 of the 5 rice baskets have lentils, so rice → lentils has confidence 0.80. Lift is the same both ways.
  • Tea and sugar appear only twice, but always together. Their lift of 5.00 is the strongest link in the shop.
  • Bread and rice never appear together, so every number is 0.

Why confidence alone can fool you

If 90% of all baskets contain rice, then almost any rule “X → rice” will have high confidence. That does not mean X causes rice sales. Lift corrects for this by comparing with how popular rice already is.

The Apriori Algorithm

With 9 products there are 511 possible itemsets. A real shop has thousands of products, so checking every combination is impossible. Apriori uses one simple fact: if an itemset is rare, every bigger set that contains it is also rare. A basket cannot contain rice, lentils and oil more often than it contains lentils and oil.

So Apriori works level by level:

  1. Find single items with enough support.
  2. Join frequent sets to build candidates one item bigger.
  3. Prune any candidate that has a rare piece, without counting it.
  4. Count the rest and keep the frequent ones. Repeat until nothing is left.
{rice}5 baskets{lentils}4 baskets{onion}3 baskets{oil}3 baskets{rice, lentils}4 baskets{rice, onion}3 baskets{rice, oil}3 baskets{lentils, onion}2 baskets{lentils, oil}2 baskets{onion, oil}2 baskets{rice, lentils, onion}2 baskets{rice, lentils, oil}2 baskets{rice, onion, oil}2 baskets{lentils, onion, oil}1 basket: rare{rice, lentils, onion, oil}pruned: never countedA rare piecerules out thebigger set
from itertools import combinations

baskets = [
    {"rice", "lentils", "onion"}, {"rice", "lentils"}, {"bread", "butter", "eggs"},
    {"rice", "onion", "oil"}, {"bread", "butter"}, {"rice", "lentils", "oil"},
    {"bread", "eggs"}, {"rice", "lentils", "onion", "oil"},
    {"tea", "sugar", "bread"}, {"tea", "sugar"},
]
N = len(baskets)
MIN_SUPPORT, MIN_CONFIDENCE = 0.2, 0.7

def support(items):
    return sum(items <= b for b in baskets) / N

# Level 1: single items that are frequent enough
items = sorted(set().union(*baskets))
frequent = {frozenset([i]) for i in items if support({i}) >= MIN_SUPPORT}
all_frequent, size = set(frequent), 1
while frequent:
    size += 1
    # Join: glue frequent sets together to make sets one item bigger
    candidates = {a | b for a in frequent for b in frequent if len(a | b) == size}
    # Prune: every smaller piece must itself be frequent (the Apriori rule)
    candidates = {c for c in candidates
                  if all(frozenset(s) in all_frequent for s in combinations(c, size - 1))}
    frequent = {c for c in candidates if support(c) >= MIN_SUPPORT}
    print(f"size {size}: {len(candidates)} candidates, {len(frequent)} frequent")
    all_frequent |= frequent

print("\nRules with confidence >= 0.7:")
for itemset in sorted(all_frequent, key=lambda s: (len(s), sorted(s))):
    for k in range(1, len(itemset)):
        for a in map(frozenset, combinations(sorted(itemset), k)):
            conf = support(itemset) / support(a)
            if conf >= MIN_CONFIDENCE:
                c = itemset - a
                lift = conf / support(c)
                print(f"  {sorted(a)} -> {sorted(c)}  conf {conf:.2f}  lift {lift:.2f}")

Output

size 2: 36 candidates, 9 frequent
size 3: 4 candidates, 3 frequent
size 4: 0 candidates, 0 frequent

Rules with confidence >= 0.7:
  ['butter'] -> ['bread']  conf 1.00  lift 2.50
  ['eggs'] -> ['bread']  conf 1.00  lift 2.50
  ['lentils'] -> ['rice']  conf 1.00  lift 2.00
  ['rice'] -> ['lentils']  conf 0.80  lift 2.00
  ['oil'] -> ['rice']  conf 1.00  lift 2.00
  ['onion'] -> ['rice']  conf 1.00  lift 2.00
  ['sugar'] -> ['tea']  conf 1.00  lift 5.00
  ['tea'] -> ['sugar']  conf 1.00  lift 5.00
  ['lentils', 'oil'] -> ['rice']  conf 1.00  lift 2.00
  ['lentils', 'onion'] -> ['rice']  conf 1.00  lift 2.00
  ['oil', 'onion'] -> ['rice']  conf 1.00  lift 2.00
  • All 9 single items appear in at least 2 of 10 baskets, so all pass the 0.2 support bar. That gives 36 pairs to test, and 9 are frequent.
  • For size 3, the join and prune steps leave only 4 candidates out of 84 possible triples. Three are frequent. {lentils, onion, oil} appears in just one basket.
  • For size 4, the only candidate is {rice, lentils, onion, oil}. It is pruned without counting, because its piece {lentils, onion, oil} is rare.
  • Rules come from splitting each frequent itemset into an “if” part and a “then” part. We keep those with confidence of at least 0.7.

Using the Rules

Good rules have enough support to matter, high confidence and a lift well above 1. A shop might act on them like this:

  • Placement: put tea and sugar on the same shelf.
  • Bundles: a rice, lentils and onion “khichuri pack”.
  • Recommendations: when butter goes in an online cart, suggest bread.

For large data, the mlxtend package has fast apriori, fpgrowth and association_rules functions that take a one-hot table of baskets.

Common Mistakes

  1. Setting minimum support too low. The number of itemsets explodes, and you get rules based on one or two baskets.
  2. Ranking rules by confidence only. Popular items make confidence high for no reason. Check lift.
  3. Reading rules as cause and effect. A rule shows that items go together, not why.
  4. Counting quantities. Apriori only asks whether an item is in a basket, not how many.

Practice Exercises

Exercise 1. Compute support, confidence and lift for {butter} → {eggs} by hand.

Show answer

Butter and eggs share 1 of 10 baskets, so support is 0.10. Butter is in 2 baskets, so confidence is 0.10 ÷ 0.20 = 0.50. Eggs are in 2 baskets (support 0.20), so lift is 0.50 ÷ 0.20 = 2.50.

Exercise 2. Change ar2.py to print only rules with lift above 2.

Show answer

Add a test after computing lift: if lift > 2: before the print. Only the bread rules (2.50) and the tea and sugar rules (5.00) remain.

Frequently Asked Questions

What is the difference between Apriori and FP-Growth?

Both find the same frequent itemsets. Apriori builds candidates and scans the baskets again at each level. FP-Growth packs the baskets into a tree and needs only two passes, so it is usually faster on big data.

Where is association rule mining used besides shops?

It is used for website pages visited together, symptoms that appear together in medical records, and software features that users turn on together. Any data made of “sets of things” works.

Summary

  • Support says how common a set is; confidence says how reliable a rule is.
  • Lift compares a rule with chance; above 1 means a real link.
  • Apriori prunes any set that has a rare piece.
  • Rules show items that go together, not causes.

Next: Save and Load Machine Learning Models.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *