A4.3.5 Finding patterns with association rules
HL onlyCommand term: Describe1. 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.
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 /
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
- Open PyCharm and choose New Project (a pure Python project; any recent Python 3 works). Name it
shelfwise_ai. - Right-click the project folder → New → Python File, and give it the file name shown below.
- Press Copy code below and paste it into the empty file (or press Download .py and drag the file into the project).
- Right-click inside the editor and choose Run (Windows Shift+F10, Mac Ctrl+R). The output appears in the Run window at the bottom.
- 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
# 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?
{sci-fi} → {fantasy} has confidence 0.87. Explain.
Why do biography and history have the highest lift (2.38)?
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 chanceTask 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 chance6. 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.
- Write a generator for 500 visits with hidden patterns you choose (e.g. cookery and travel together 30% of the time).
- Run Apriori and check that it rediscovers your hidden patterns.
- Add a rule with lift below 1 on purpose (two genres rarely borrowed together) and show how to detect it.
- 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:
- Describe what an association rule is.
- Calculate the support, confidence and lift of a rule.
- Describe how the Apriori algorithm finds frequent itemsets.
- Interpret association rules in a given scenario.
- 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
| Measure | Formula | Meaning |
|---|---|---|
| Support | transactions with X and Y ÷ all transactions | How common the combination is. Low support means the rule may be a coincidence. |
| Confidence | support(X and Y) ÷ support(X) | How reliable the rule is: when X occurs, how often Y also occurs. |
| Lift | confidence ÷ 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
- Set a minimum support and minimum confidence.
- Count single items; keep those meeting minimum support (frequent itemsets).
- 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.
- 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).
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]
2. Interpret the results from question 1 for the supermarket manager. [3]
3. Describe how the Apriori algorithm reduces the number of itemsets that must be counted. [3]
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]
5. Explain why a rule with high confidence may still not be useful. [2]