A4.1.1 Types of machine learning and where they are used
SL + HLCommand term: Describe1. Five ways a machine can learn
Choose a type of machine learning and try its mini-lab. Each one learns in a different way.
2. Which type of machine learning?
Match each real-world application to the type of machine learning that fits it best. Score: 0 /
In this lab you practise supervised, unsupervised and reinforcement learning side by side, in one short program. 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.1.1: three ways a machine can learn
# Run it, read the output, then change the settings below and run it again.
import random
GROUPS = 2 # unsupervised learning: how many groups of readers to look for
DAYS = 300 # reinforcement learning: how many days the agent experiments
EPSILON = 0.1 # reinforcement learning: share of days it tries a random display
random.seed(1)
# ---------- 1. SUPERVISED: learn from labelled examples ----------
# features: (pages, has_pictures) -> label given by a librarian
books = [((320, 0), "novel"), ((410, 0), "novel"), ((280, 0), "novel"),
((36, 1), "picture book"), ((24, 1), "picture book"), ((48, 1), "picture book"),
((150, 1), "comic"), ((120, 1), "comic"), ((180, 1), "comic")]
def average(points):
return tuple(sum(p[i] for p in points) / len(points) for i in range(len(points[0])))
centres = {}
for label in sorted(set(lab for _, lab in books)):
centres[label] = average([f for f, lab in books if lab == label])
def classify(features):
# nearest centre; pages are divided by 100 so both features count
def dist(c):
return ((features[0] - c[0]) / 100) ** 2 + (features[1] - c[1]) ** 2
return min(centres, key=lambda lab: dist(centres[lab]))
print("1. SUPERVISED LEARNING (labelled examples)")
for new_book in [(350, 0), (30, 1), (140, 1)]:
print(f" {new_book[0]} pages, pictures={new_book[1]} -> {classify(new_book)}")
# ---------- 2. UNSUPERVISED: find groups in unlabelled data ----------
# (age, loans per month) for ten readers - nobody has labelled them
readers = [(9, 8), (10, 10), (11, 7), (8, 9), (35, 2), (41, 3), (38, 1), (45, 2), (16, 12), (15, 11)]
centres_u = random.sample(readers, GROUPS)
for _ in range(10): # k-means: assign, then move the centres
groups = [[] for _ in range(GROUPS)]
for r in readers:
nearest = min(range(GROUPS), key=lambda g: (r[0] - centres_u[g][0]) ** 2 + (r[1] - centres_u[g][1]) ** 2)
groups[nearest].append(r)
centres_u = [average(g) if g else centres_u[i] for i, g in enumerate(groups)]
print("\n2. UNSUPERVISED LEARNING (no labels)")
for i, g in enumerate(groups):
c = centres_u[i]
print(f" group {i + 1}: {len(g)} readers, average age {c[0]:.0f}, {c[1]:.1f} loans a month")
# ---------- 3. REINFORCEMENT: learn by trial, error and reward ----------
# Which window display makes the most people borrow a book? The agent does not know these:
true_chance = {"new arrivals": 0.20, "staff picks": 0.50, "film tie-ins": 0.35}
tries = {d: 0 for d in true_chance}
wins = {d: 0 for d in true_chance}
total = 0
for day in range(DAYS):
if random.random() < EPSILON or day < len(true_chance):
display = random.choice(list(true_chance)) # explore
else:
display = max(true_chance, key=lambda d: wins[d] / max(tries[d], 1)) # exploit
reward = 1 if random.random() < true_chance[display] else 0 # did someone borrow?
tries[display] += 1
wins[display] += reward
total += reward
print(f"\n3. REINFORCEMENT LEARNING ({DAYS} days)")
for d in true_chance:
est = wins[d] / tries[d] if tries[d] else 0
print(f" {d:13} shown {tries[d]:3} days, estimated success {est:.2f}")
print(f" total loans from the window: {total}")
3. Expected output
The program uses a fixed random seed, so with the same settings you should see exactly this output.
1. SUPERVISED LEARNING (labelled examples) 350 pages, pictures=0 -> novel 30 pages, pictures=1 -> picture book 140 pages, pictures=1 -> comic 2. UNSUPERVISED LEARNING (no labels) group 1: 4 readers, average age 40, 2.0 loans a month group 2: 6 readers, average age 12, 9.5 loans a month 3. REINFORCEMENT LEARNING (300 days) new arrivals shown 81 days, estimated success 0.10 staff picks shown 204 days, estimated success 0.50 film tie-ins shown 15 days, estimated success 0.47 total loans from the window: 117
4. Read the output
Answer each question from your own output before you open the answer.
Which part of the program was given the right answers (labels) while learning?
books comes with a label chosen by a librarian, and the model learns the average features of each label.In part 2, nobody told the program what the groups were. How did it decide?
In part 3, which display did the agent learn to prefer, and how?
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 GROUPS = 2 → GROUPS = 3
Set GROUPS = 3. What new group appears?
Check your prediction
A third group of two teenagers (about 16, borrowing 11.5 books a month) splits away from the children. Unsupervised learning finds whatever structure exists, and the number of groups is a choice you make.
Output with this change:
1. SUPERVISED LEARNING (labelled examples) 350 pages, pictures=0 -> novel 30 pages, pictures=1 -> picture book 140 pages, pictures=1 -> comic 2. UNSUPERVISED LEARNING (no labels) group 1: 4 readers, average age 10, 8.5 loans a month group 2: 2 readers, average age 16, 11.5 loans a month group 3: 4 readers, average age 40, 2.0 loans a month 3. REINFORCEMENT LEARNING (300 days) new arrivals shown 29 days, estimated success 0.14 staff picks shown 257 days, estimated success 0.50 film tie-ins shown 14 days, estimated success 0.43 total loans from the window: 138
Task 2. Change EPSILON = 0.1 → EPSILON = 0.0
Set EPSILON = 0.0 (never explore). Predict the total loans, then run it.
Check your prediction
The agent locks onto whichever display happened to work first (new arrivals, shown 298 days) and never discovers that staff picks are better. Total loans fall from 117 to 63. Without exploration, reinforcement learning can get stuck.
Output with this change:
1. SUPERVISED LEARNING (labelled examples) 350 pages, pictures=0 -> novel 30 pages, pictures=1 -> picture book 140 pages, pictures=1 -> comic 2. UNSUPERVISED LEARNING (no labels) group 1: 4 readers, average age 40, 2.0 loans a month group 2: 6 readers, average age 12, 9.5 loans a month 3. REINFORCEMENT LEARNING (300 days) new arrivals shown 298 days, estimated success 0.21 staff picks shown 2 days, estimated success 0.00 film tie-ins shown 0 days, estimated success 0.00 total loans from the window: 63
Task 3. Change DAYS = 300 → DAYS = 30
Set DAYS = 30. Is 30 days of experience enough?
Check your prediction
No. After 30 days the agent has barely tried two displays and still prefers the worst one. Reinforcement learning needs many trials.
Output with this change:
1. SUPERVISED LEARNING (labelled examples) 350 pages, pictures=0 -> novel 30 pages, pictures=1 -> picture book 140 pages, pictures=1 -> comic 2. UNSUPERVISED LEARNING (no labels) group 1: 4 readers, average age 40, 2.0 loans a month group 2: 6 readers, average age 12, 9.5 loans a month 3. REINFORCEMENT LEARNING (30 days) new arrivals shown 28 days, estimated success 0.14 staff picks shown 2 days, estimated success 0.00 film tie-ins shown 0 days, estimated success 0.00 total loans from the window: 4
6. Extended activity: Add a fourth way: deep learning or transfer learning (research task)
A longer project for homework or a double lesson. Save it as a new file so you keep the original.
- Research what deep learning and transfer learning are, and add a comment block to the program explaining which ShelfWise problem each could solve (for example, reading book covers from photos).
- Add a 4th window display with your own hidden success chance, run the reinforcement section, and record how many days it takes the agent to discover it if it is the best.
- Add five more labelled books to part 1, including one that is hard to classify (a 200-page illustrated novel). Does the nearest-centre model get it right? Why or why not?
- Write a one-page comparison table: type of learning, what data it needs, how it learns, a ShelfWise example and one real-world example (market basket analysis, medical imaging, sentiment analysis, robot navigation).
Success criteria
- Your table correctly matches each real-world application to a type of learning.
- You can explain why the reinforcement agent needs exploration.
- Your new hard-to-classify book is discussed with evidence from the output.
Learning objectives
By the end of this page you should be able to:
- Describe what machine learning is and how it differs from explicitly programmed rules.
- Describe supervised and unsupervised learning.
- Describe reinforcement learning, deep learning and transfer learning.
- Distinguish between the approaches by the data they use and how they learn.
- Identify the approach used in real-world applications such as market basket analysis, medical imaging and sentiment analysis.
What is machine learning?
Machine learning (ML) is a branch of artificial intelligence in which computers learn patterns from data instead of being given step-by-step rules by a programmer. A model is trained on data, then used to make predictions or decisions about new data it has never seen.
The five approaches
| Type | How it learns | Data needed | Typical tasks | Real-world applications |
|---|---|---|---|---|
| Supervised learning | Learns from labelled examples (input + correct answer), then predicts labels for new inputs | Labelled data (often expensive to label) | Classification (which category?), regression (what number?) | Spam filters, sentiment analysis of reviews, house-price prediction, disease diagnosis from symptoms |
| Unsupervised learning (UL) | Finds hidden patterns or groups in data that has no labels | Unlabelled data (cheap and plentiful) | Clustering, association rules, anomaly detection | Market basket analysis ("people who buy bread also buy butter"), customer segmentation, fraud detection |
| Reinforcement learning (RL) | An agent learns by trial and error in an environment, receiving rewards or penalties for its actions | No dataset: experience from interacting with the environment | Sequential decision-making, control | Robotics navigation, game-playing AI, self-driving decisions, traffic-light timing |
| Deep learning (DL) | Uses artificial neural networks with many layers; each layer learns more complex features automatically | Very large datasets and powerful hardware (GPUs) | Image, speech and language tasks | Object detection and classification, natural language processing (translation, chatbots), medical imaging, voice assistants |
| Transfer learning (TL) | Re-uses a model already trained on a large dataset for one task, and fine-tunes it for a new, related task | Only a small dataset for the new task | Adapting big models to specialist tasks | Medical imaging with few scans, recognising rare species, customising a language model for a company |
These categories overlap: deep learning is a technique that can be used for supervised, unsupervised or reinforcement learning, and transfer learning is usually applied to deep learning models.
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. Distinguish between supervised and unsupervised learning. [2]
2. Describe how reinforcement learning could be used to train a robot to navigate a warehouse. [3]
3. A supermarket wants to discover which products are often bought together. Identify the most suitable type of machine learning and justify your answer. [3]
4. A hospital has only 300 labelled X-ray images of a rare disease. Explain why transfer learning would be suitable. [3]
5. Describe the characteristics of deep learning and give one real-world application. [3]