Home › Theme A › A4 › A4.3 › A4.3.5

A4.3.5 Finding patterns with association rules

HL onlyCommand term: Describe

1. Build a rule: IF … THEN …

A shop has 10 shopping baskets (transactions). Choose an item for IF (the antecedent) and an item for THEN (the consequent). Baskets with the IF item turn blue; baskets with both turn green.

IF the basket contains…
THEN it also contains…

2. The Apriori algorithm: finding all the rules

A real shop has millions of baskets and thousands of products: far too many combinations to check one by one. Apriori finds the frequent itemsets level by level and prunes the rest. Set the thresholds, then click Next.

3. Crime analysis

A city's police department records which incident types occurred in each area-month (12 records). Association rule mining reveals which crimes tend to occur together.

Interpret the results. Score: 0 /

ShelfWise AI · Hands-on lab A4.3.5: Which genres are borrowed together?. When members visit, they often borrow several books. ShelfWise wants to place genres that go together near each other and recommend related books.

In this lab you practise support, confidence and lift, and the Apriori algorithm. Work through the sections in order: run it, read it, change it, then extend it.

1. Set up in PyCharm

  1. Open PyCharm and choose New Project (a pure Python project; any recent Python 3 works). Name it shelfwise_ai.
  2. Right-click the project folder → New → Python File, and give it the file name shown below.
  3. Press Copy code below and paste it into the empty file (or press Download .py and drag the file into the project).
  4. Right-click inside the editor and choose Run (Windows Shift+F10, Mac Ctrl+R). The output appears in the Run window at the bottom.
  5. No extra libraries are needed: the lab uses only Python's built-in modules, so you can see exactly how the algorithm works.

2. Copy and run the program

File: lab_a4_3_5.py
# ShelfWise AI - Lab A4.3.5: which genres are borrowed together?  Association rules and Apriori
from itertools import combinations

MIN_SUPPORT = 0.25      # an itemset must appear in at least 25% of visits
MIN_CONFIDENCE = 0.6    # a rule must be right at least 60% of the time

visits = [
    {"fantasy", "sci-fi", "comics"}, {"fantasy", "sci-fi"}, {"history", "biography"},
    {"fantasy", "comics"}, {"sci-fi", "comics", "fantasy"}, {"cookery", "travel"},
    {"history", "biography", "travel"}, {"fantasy", "sci-fi", "comics"}, {"biography", "history"},
    {"comics", "sci-fi"}, {"travel", "cookery", "history"}, {"fantasy", "sci-fi"},
    {"history", "biography"}, {"fantasy", "poetry"}, {"comics", "fantasy", "sci-fi"},
    {"cookery", "travel"}, {"sci-fi", "fantasy", "history"}, {"biography", "travel"},
    {"comics", "fantasy"}, {"poetry", "history", "biography"},
]
N = len(visits)

def support(itemset):
    return sum(1 for v in visits if itemset <= v) / N

# Apriori: build frequent itemsets level by level; only extend sets that are already frequent
items = sorted(set().union(*visits))
level = [frozenset([i]) for i in items if support({i}) >= MIN_SUPPORT]
frequent = {}
size = 1
while level:
    print(f"Frequent itemsets of size {size}:")
    for s in sorted(level, key=lambda s: -support(s)):
        frequent[s] = support(s)
        print(f"   {', '.join(sorted(s)):32} support {support(s):.2f}")
    size += 1
    candidates = {a | b for a in level for b in level if len(a | b) == size}
    level = [c for c in candidates if support(c) >= MIN_SUPPORT]

print(f"\nRules with confidence >= {MIN_CONFIDENCE}:")
rules = []
for s in frequent:
    if len(s) < 2:
        continue
    for r in range(1, len(s)):
        for left in map(frozenset, combinations(sorted(s), r)):
            right = s - left
            conf = support(s) / support(left)
            lift = conf / support(right)
            if conf >= MIN_CONFIDENCE:
                rules.append((lift, conf, left, right, support(s)))
for lift, conf, left, right, sup in sorted(rules, key=lambda r: (-r[0], -r[1])):
    print(f"   {{{', '.join(sorted(left))}}} -> {{{', '.join(sorted(right))}}}"
          f"   support {sup:.2f}  confidence {conf:.2f}  lift {lift:.2f}")
print("\nlift > 1: borrowed together more often than chance;  lift < 1: less often than chance")

3. Expected output

The program uses a fixed random seed, so with the same settings you should see exactly this output.

Frequent itemsets of size 1:
   fantasy                          support 0.50
   sci-fi                           support 0.40
   comics                           support 0.35
   history                          support 0.35
   biography                        support 0.30
   travel                           support 0.25
Frequent itemsets of size 2:
   fantasy, sci-fi                  support 0.35
   comics, fantasy                  support 0.30
   biography, history               support 0.25
   comics, sci-fi                   support 0.25

Rules with confidence >= 0.6:
   {biography} -> {history}   support 0.25  confidence 0.83  lift 2.38
   {history} -> {biography}   support 0.25  confidence 0.71  lift 2.38
   {sci-fi} -> {comics}   support 0.25  confidence 0.62  lift 1.79
   {comics} -> {sci-fi}   support 0.25  confidence 0.71  lift 1.79
   {sci-fi} -> {fantasy}   support 0.35  confidence 0.87  lift 1.75
   {fantasy} -> {sci-fi}   support 0.35  confidence 0.70  lift 1.75
   {comics} -> {fantasy}   support 0.30  confidence 0.86  lift 1.71
   {fantasy} -> {comics}   support 0.30  confidence 0.60  lift 1.71

lift > 1: borrowed together more often than chance;  lift < 1: less often than chance

4. Read the output

Answer each question from your own output before you open the answer.

What is the support of {fantasy, sci-fi}, and what does it mean?
0.35: 35% of all visits included both fantasy and sci-fi.
{sci-fi} → {fantasy} has confidence 0.87. Explain.
87% of the visits that included sci-fi also included fantasy.
Why do biography and history have the highest lift (2.38)?
They are borrowed together 2.38 times more often than you would expect if they were independent. Lift compares the rule's confidence with how common the right-hand side is anyway.

5. Change it and predict

For each change: write down your prediction first, then edit the setting at the top of the program, run it, and compare. Change the setting back before the next task.

Task 1. Change MIN_SUPPORT = 0.25 → MIN_SUPPORT = 0.20
Set MIN_SUPPORT = 0.20. What new itemset and rules appear?

Check your prediction

The triple {comics, fantasy, sci-fi} (support 0.20) becomes frequent, giving two new rules, e.g. {comics, sci-fi} → {fantasy} with confidence 0.80. Lower support finds more patterns but risks rules based on very few visits.

Output with this change:

Frequent itemsets of size 1:
   fantasy                          support 0.50
   sci-fi                           support 0.40
   comics                           support 0.35
   history                          support 0.35
   biography                        support 0.30
   travel                           support 0.25
Frequent itemsets of size 2:
   fantasy, sci-fi                  support 0.35
   comics, fantasy                  support 0.30
   biography, history               support 0.25
   comics, sci-fi                   support 0.25
Frequent itemsets of size 3:
   comics, fantasy, sci-fi          support 0.20

Rules with confidence >= 0.6:
   {biography} -> {history}   support 0.25  confidence 0.83  lift 2.38
   {history} -> {biography}   support 0.25  confidence 0.71  lift 2.38
   {sci-fi} -> {comics}   support 0.25  confidence 0.62  lift 1.79
   {comics} -> {sci-fi}   support 0.25  confidence 0.71  lift 1.79
   {sci-fi} -> {fantasy}   support 0.35  confidence 0.87  lift 1.75
   {fantasy} -> {sci-fi}   support 0.35  confidence 0.70  lift 1.75
   {comics} -> {fantasy}   support 0.30  confidence 0.86  lift 1.71
   {fantasy} -> {comics}   support 0.30  confidence 0.60  lift 1.71
   {comics, fantasy} -> {sci-fi}   support 0.20  confidence 0.67  lift 1.67
   {comics, sci-fi} -> {fantasy}   support 0.20  confidence 0.80  lift 1.60

lift > 1: borrowed together more often than chance;  lift < 1: less often than chance

Task 2. Change MIN_CONFIDENCE = 0.6 → MIN_CONFIDENCE = 0.8
Set MIN_CONFIDENCE = 0.8. How many rules survive?

Check your prediction

Three: biography → history, sci-fi → fantasy and comics → fantasy. A higher confidence threshold keeps only the most reliable rules.

Output with this change:

Frequent itemsets of size 1:
   fantasy                          support 0.50
   sci-fi                           support 0.40
   comics                           support 0.35
   history                          support 0.35
   biography                        support 0.30
   travel                           support 0.25
Frequent itemsets of size 2:
   fantasy, sci-fi                  support 0.35
   comics, fantasy                  support 0.30
   comics, sci-fi                   support 0.25
   biography, history               support 0.25

Rules with confidence >= 0.8:
   {biography} -> {history}   support 0.25  confidence 0.83  lift 2.38
   {sci-fi} -> {fantasy}   support 0.35  confidence 0.87  lift 1.75
   {comics} -> {fantasy}   support 0.30  confidence 0.86  lift 1.71

lift > 1: borrowed together more often than chance;  lift < 1: less often than chance

6. Extended activity: Mine your own market basket data

A longer project for homework or a double lesson. Save it as a new file so you keep the original.

  1. Write a generator for 500 visits with hidden patterns you choose (e.g. cookery and travel together 30% of the time).
  2. Run Apriori and check that it rediscovers your hidden patterns.
  3. Add a rule with lift below 1 on purpose (two genres rarely borrowed together) and show how to detect it.
  4. Apply the method to the crime-analysis scenario from the syllabus: invent incident data by area (vandalism, theft, noise) and interpret the strongest rule for a police resource-allocation meeting.

Success criteria

  • Your hidden patterns are found with sensible thresholds.
  • You interpret support, confidence and lift in context.
  • You note that association does not mean causation.

Learning objectives

By the end of this page you should be able to:

  1. Describe what an association rule is.
  2. Calculate the support, confidence and lift of a rule.
  3. Describe how the Apriori algorithm finds frequent itemsets.
  4. Interpret association rules in a given scenario.
  5. Describe applications such as market basket analysis and crime analysis.

Association rules

Association rule learning is an unsupervised technique that searches large data sets for items or attributes that frequently occur together. A rule has the form:

{antecedent} → {consequent}   e.g. {bread} → {butter}

meaning "transactions that contain the antecedent often also contain the consequent". The classic application is market basket analysis.

Measuring a rule

MeasureFormulaMeaning
Supporttransactions with X and Y ÷ all transactionsHow common the combination is. Low support means the rule may be a coincidence.
Confidencesupport(X and Y) ÷ support(X)How reliable the rule is: when X occurs, how often Y also occurs.
Liftconfidence ÷ support(Y)How much more likely Y is when X occurs than normally. Lift > 1: positive association; = 1: independent (no real link); < 1: X makes Y less likely.

The Apriori algorithm

  1. Set a minimum support and minimum confidence.
  2. Count single items; keep those meeting minimum support (frequent itemsets).
  3. Combine frequent items into pairs, count, prune; then triples, and so on. Apriori property: if an itemset is infrequent, every larger set containing it is also infrequent, so it never needs to be counted. This saves huge amounts of computation.
  4. Generate rules from the frequent itemsets; keep those meeting minimum confidence; rank them, e.g. by lift.

Interpreting results in a scenario

  • Retail: place associated products together or apart, bundle offers, recommendations ("customers who bought… also bought…").
  • Crime analysis: {vandalism} → {theft} with high confidence and lift suggests areas with vandalism also tend to have theft, so police can plan patrols and allocate resources (predictive policing).
  • Healthcare: symptoms or conditions that occur together; web usage: pages visited together.
  • Rules show co-occurrence, not causation. Vandalism does not necessarily cause theft; both may share another cause. Biased data (e.g. some areas patrolled more, so more crimes recorded there) can produce biased rules (see A4.4).
Exam tip: when interpreting a rule, state all three measures in context: "42% of area-months had both; in 83% of area-months with vandalism, theft also occurred; theft is 1.4 times more likely than usual when vandalism occurs."

Use the 中文 button at the top to show or hide the Chinese terms.

Term中文Meaning

Choose an answer. You get instant feedback.

Score: 0 /

Write your answer first, then reveal the markscheme. These are exam-style practice questions written for this site.

1. In 1,000 supermarket transactions, 200 contain nappies, 150 contain both nappies and wipes, and 300 contain wipes. For the rule {nappies} → {wipes}, calculate the support, confidence and lift. [3]

Support = 150 ÷ 1000 = 0.15 (15%) [1]; confidence = 150 ÷ 200 = 0.75 (75%) [1]; lift = 0.75 ÷ 0.3 = 2.5 [1].

2. Interpret the results from question 1 for the supermarket manager. [3]

15% of all transactions contain both items, so the pattern is common enough to act on [1]; 75% of customers who buy nappies also buy wipes [1]; lift 2.5 means customers buying nappies are 2.5 times more likely than average to buy wipes, a strong positive association, so the manager could place them near each other / offer a bundle [1].

3. Describe how the Apriori algorithm reduces the number of itemsets that must be counted. [3]

It finds frequent itemsets level by level, starting with single items [1]; itemsets below the minimum support are removed (pruned) [1]; since any superset of an infrequent itemset must also be infrequent (Apriori property), larger itemsets containing it are never generated or counted [1].

4. A police department finds the rule {vandalism} → {theft} with confidence 0.83 and lift 1.4. Discuss how the department could use this rule. [4]

Award [1] for each, up to [4]: in 83% of areas/months with vandalism, theft also occurred, and theft is 1.4 times more likely than usual; areas with rising vandalism could receive extra patrols to prevent theft (predictive policing / resource allocation); resources can be targeted more efficiently; however, the rule shows association, not causation; recorded crime data may be biased (e.g. heavily patrolled areas record more crime), leading to over-policing of some communities; the rule should support, not replace, human judgement.

5. Explain why a rule with high confidence may still not be useful. [2]

If the consequent is very common anyway (e.g. bought in most transactions), confidence will be high even without a real link [1]; the lift may be about 1 (or below), showing the items are independent, so the rule gives no useful information (also: low support, so it may be coincidence) [1].