Build an app that sorts an input (text, answers, a photo, a pose or a sound) into groups and responds usefully. One short lesson trains a model in the Pattern Trainer and runs it in Python; then three open projects: A uses rules you write, B a model you train, C joins the two. The apps run on your own computer, from the Pattern Detector starters.
Each lesson works two ways. Students can work through the online tutorial at their own pace (it checks their answers and saves their progress in their browser), or you can teach it to the whole class from the slides, then send students into the tutorial for the Modify and Make steps.
Every lesson guide has plain-language notes, the answers to every check, a solution for every task, and slides and a worksheet for Waypoints Prepare. These guide pages are not linked from student pages, but they are not secret either: keep printed Teacher editions for answers you do not want students to find.
Course resources: Open course presentation in Prepare · Opening and closing slides (Markdown)
These projects are written to be adopted or adapted. Nothing here belongs to one school's programme, task sheet or marking scheme: use the parts you want and change the rest.
What a pattern detector is. An app that takes an input (text someone types, answers to a few questions, a photo, a pose, a sound), sorts it into groups, and responds in a way that helps a real person. There are two ways to build the sorting part: rules you write (project A) or a model you train from examples (project B). Project C lets a trained model feed your rules. Students meet the trade-off first-hand: rules are easy to explain and fix but cannot cover every case; a trained model copes with messy inputs but can be sure and wrong, and cannot say why.
Where it sits, and the first lesson. After Apps with Gradio, beside Machine learning with Gradio (either first): this is the easier way into machine learning, because the Pattern Trainer does the training and the starters hide the numbers, so students need only Gradio apps, functions, if/elif and dictionaries. Machine learning with Gradio shows how a model works inside. The one lesson, Train a model, then use it in Python (about 40 minutes): a tiny two-class model trained in the Pattern Trainer, tested on the site's board, then the same my_model.json run in the Python starter. Install the starters before it (below). Brief A can come before or after it; B and C build on it.
How the apps run. The apps are Python with Gradio and run on the student's own laptop, starting from the Pattern Detector starters. Setup is once per laptop (a virtual environment and pip install -r requirements.txt; about 0.5 GB). Try it on a school laptop before the lesson: project A's starters need only Gradio (and numpy for the colour and sound starters), so they are the quickest to test. No camera or microphone is needed for A; the photo and sound starters also accept uploaded files.
Adapting a project. Each project's guide below lists what to change. The pattern is the same for all of them:
# ADAPT: lines, a short IDEAS list).Using the badge. Badges and ticks live in the student's browser. Ask students to press Show your teacher and show you the card (milestones ticked, help used, their own words on the hardest part). It is a self-assessed record, not a marked result.
Strategies for getting unstuck: Say what it should do, Test a small piece, Read the error, Trace it. A student who is stuck can try one before asking for a hint. The optional course How you learn best introduces them, and a few lesson decks have a short teach, show or nudge slide for one. (Each lesson page links to the cards from its first hint.)
Whole-course cheat sheet: Open to print (every command, grouped by unit: a handout for the final challenge)
Train a model in the Pattern Trainer, then use the same file in a Python app.
Cheat sheet: Open to print (A4, with a picture of what each command draws) · Open in Print · Markdown
Self-paced briefs students can pick up (after the lesson named on each, where one is named). Students tick their own milestones and claim a badge; the page lights the skills their code uses. Badges stay in the student's browser: ask them to press Show your teacher. Open the projects page
Build a Python app that sorts an input into groups using rules you write yourself, then responds in a way that helps someone.
Some problems can be described exactly: does the message contain this phrase? Is the soil drier than this? For those, rules are quick and predictable, and you can always say why the app answered as it did. When it is wrong, you can find the rule and fix it.
Before you start, write one sentence: who is it for, and what will it help them do?
What to hand in
.py file and any data files (your dictionary or lists).Check your app before you hand it in
Milestones:
# Rules in plain English (written first, before any code):
# 1. Nothing typed -> ask for a password.
# 2. On the list of common passwords -> Weak, whatever its length.
# 3. Shorter than the minimum length -> Weak, say how many more characters.if len(password) < min_length:
return "Weak", f"{len(password)} characters. Aim for at least {min_length} ({min_length - len(password)} more)."("abc1234", False, "Weak"), # 7 characters: one under the boundary
("abc12345", False, "Strong"), # exactly 8: on the boundaryWhat this project is. The rules-based half of a pair (project B trains a model instead; project C joins them). Students sort an input into groups with rules they write, respond usefully, and then test and reflect honestly. The learning is in the testing and the reflection as much as in the app: at the boundary of a rule, with an empty input, and with the case no rule covers.
Running it. Each student works on their own laptop from a starter (links on the project page). Do the one-off setup before the lesson, or as a first step, and run an unchanged starter on a school laptop beforehand. Project A needs no camera or microphone; the photo and sound starters also accept uploaded files.
What to change when you adapt it
# ADAPT: lines, a short ideas list).uses: in projects.yml if you want other skills.reveal: false (or remove reveal:) to turn "Show one way" off.Marking points to look for (replace with your own criteria):
Usual mistakes, and a question to ask.
< where <= was meant). Ask: "What happens at exactly 8?"Ways it could look. Students see two screenshots of finished apps that work quite differently (a study method picker, a working checker): output only, never code, so they show the standard without giving one answer to copy. Replace them with your own screenshots if you like (a PNG in content/code/pattern-detector/projects/, listed under benchmark:).
The example below is one complete rules app (a password checker with a strict-mode setting, a list of common passwords, an honest "not sure" and a small testing record). It is for you, to calibrate marking. Students who unlock "Show one way" see only a short piece of it for the milestone they are on. If a student chooses a password checker, expect to see something different from this one.
A filled-in testing record (the example password checker; yours will look different):
| I typed | Strict | I expected | The app said | Notes |
|---|---|---|---|---|
| (nothing) | off | ask for a password | Type a password first. | ok |
| PASSWORD | off | Weak | Weak: "the most guessed password" | capitals still caught |
| abc1234 | off | Weak | Weak: 7 characters, 1 more | one under the boundary |
| abc12345 | off | Strong | Strong | exactly 8: on the boundary |
| abcdefgh | off | OK | OK: only one kind of character | ok |
| !!!!!!!! | off | Not sure | Not sure: no rule fits | honest, no guess |
| abc12345 | on | Weak | Weak: 8 characters, 4 more | strict mode moves the boundary |
| Passw0rd! | off | Weak (I guessed) | Strong | surprise: a common pattern, but my rules cannot see it. Goes in the reflection. |
A sample reflection (strong): "My rules only check length, kinds of characters and a short list of common passwords, so 'Passw0rd!' is rated Strong even though guessers try it early. To catch it I would need to know every common pattern, such as swapping a letter for a number, and that list has no end. A model trained on many real leaked passwords could learn that pattern, though I could not say why it rated one weak. If my app is wrong, a student might trust a weak password. They would not know, because the app says Strong with confidence."
What a weaker reflection looks like: "My app could be improved by adding more rules." Ask: which input, and how many rules would that take?
# Rules in plain English (written first, before any code):
# 1. Nothing typed -> ask for a password.
# 2. On the list of common passwords -> Weak, whatever its length.
# 3. Shorter than the minimum length -> Weak, say how many more characters.
# 4. Long enough, letters and numbers -> Strong.
# 5. Long enough, only one kind -> OK, suggest mixing.
# 6. None of these fit -> say so, don't guess.
import gradio as gr
# The numbers the rules use, together at the top
MIN_LENGTH = 8
STRICT_LENGTH = 12
COMMON = {
"password": "the most guessed password in the world",
"123456": "a counting sequence",
"qwerty": "the first letters on a keyboard",
"letmein": "a phrase everyone tries",
}
def check(password, strict):
password = (password or "").strip()
min_length = STRICT_LENGTH if strict else MIN_LENGTH
if not password:
return "Type a password first.", ""
if password.lower() in COMMON:
return "Weak", f"That is {COMMON[password.lower()]}. Guessers try these first."
if len(password) < min_length:
return "Weak", f"{len(password)} characters. Aim for at least {min_length} ({min_length - len(password)} more)."
has_letter = any(ch.isalpha() for ch in password)
has_digit = any(ch.isdigit() for ch in password)
if has_letter and has_digit:
return "Strong", "Long enough, with letters and numbers."
elif has_letter or has_digit:
return "OK", "Long enough, but only one kind of character. Mix in letters and numbers."
else:
return "Not sure", "None of my rules fits a password with no letters or numbers, so I won't guess."
# Testing record: what I typed, strict mode, the first word I expect
TESTS = [
("", False, "Type"),
("PASSWORD", False, "Weak"), # capitals, same rule
("abc1234", False, "Weak"), # 7 characters: one under the boundary
("abc12345", False, "Strong"), # exactly 8: on the boundary
("abcdefgh", False, "OK"),
("!!!!!!!!", False, "Not"),
("abc12345", True, "Weak"), # strict mode moves the boundary to 12
]
for given, strict, expected in TESTS:
result = check(given, strict)[0]
print("ok " if result.startswith(expected) else "FAIL", repr(given), "->", result)
gr.Interface(
fn=check,
inputs=[gr.Textbox(label="Password to check"), gr.Checkbox(label="Strict mode (12 or more characters)")],
outputs=[gr.Textbox(label="Rating"), gr.Textbox(label="Why")],
).launch(show_error=True)
Build a Python app that recognises your own groups of pictures, body poses or sounds, using a model you train yourself, then responds in a way that helps someone.
Some things are easy for people to recognise but almost impossible to describe as rules. Every breed of dog, every angle and every kind of light would need its own rule. Instead you show the computer lots of examples of each group (a class), it finds its own patterns, and then it uses them on things it has never seen. Its confidence in an answer, a number from 0 to 1 (0.8 means 80% sure), is not the same as being right.
Before you start, write one sentence: who is it for, and what will it tell or do for them?
What to hand in
.py file and your model file.Check your app before you hand it in
Good habits. Only record yourself, or people who have said yes. Check what is behind you before you record. Your pictures and sounds stay on your computer. The model file holds only your class names and trained numbers, but a saved project file also holds tiny copies of your photos (in Sounds mode, just sound scores), so do not share it if it shows people.
Milestones:
# Plan (written before training):
# User: someone hard of hearing, at home.
# Job: tell them about sounds they would want to know about.
# Classes: Baby crying, Dog barking, Fire crackling, Nothing urgent# I tried I expected It said How sure
# a sneeze Nothing urgent Baby crying 0.61 (now "Not sure")
# a rooster Nothing urgent Dog barking 0.998 (fooled, and sure)
# a chainsaw, first model Nothing urgent Fire crackling 1.00 (fixed by adding chainsaws)ADVICE = {
"Baby crying": "The baby is crying. Go and check on them.",
"Dog barking": "The dog is barking. Someone may be at the door.",
"Fire crackling": "Something is crackling like a fire. Check the kitchen and the heaters now.",
"Nothing urgent": "Nothing to worry about.",
}if score < cutoff:
# Not sure is passed on, not dropped: a missed alert costs more than a false one.
return "Not sure", f"I heard something, maybe {label} ({score:.0%}). Have a look to be safe."
return label, ADVICE[label]What this project is. The trained half of a pair (project A uses rules; project C joins them). Students train a model from their own examples, build an app around it, and then test whether it can be trusted. The learning is in the testing and the reflection as much as in the app: new people, new places and things outside every class, and a cut-off picked from evidence rather than a guess.
Running it. Students train in the browser-based Pattern Trainer, download one small model file, and run a starter on their own laptop. Do the one-off setup before the lesson, or as a first step, and run an unchanged starter with its sample model on a school laptop beforehand.
Check before class (these vary by school; two minutes on one student-account laptop):
For your IT team. The Pattern Trainer is a static page: it runs in the student's browser with no backend, database or accounts. Its libraries (TensorFlow.js, MediaPipe) and model files are in the trainer's repository and served from the same site, and its own code makes no fetch, XMLHttpRequest, WebSocket or beacon calls and uses no browser storage (checked against waypoints-tools at commit 8c7ec47, 27 Oct 2026; the vendored libraries were not audited). The camera or microphone is requested through the normal browser prompt, only when a student picks that mode. The only file output is the model file, or a saved project, that the student chooses to download. The starters run on the student's laptop and need Python, pip access for one install, and the model files in their own repository. Your IT team will make its own call; the trainer's privacy page says the same in plain words. To see it yourself: load the trainer, switch off Wi-Fi, and train a model, or watch the Network tab in the browser's developer tools while you add examples.
What to change when you adapt it
uses: in projects.yml if you want other skills.reveal: false (or remove reveal:) to turn "Show one way" off.Safety and consent. Students record themselves or people who have said yes. Remind them to check what is behind them. Pictures and sounds stay on the student's computer; the model file has only class names and trained numbers; a saved project file in the trainer also holds tiny copies of photos, so it should not be shared if it shows people. Decide before the unit what students may keep and where.
Marking points to look for (replace with your own criteria):
Usual mistakes, and a question to ask.
Ways it could look. Students see two screenshots of finished apps (a home sound alert, and a door knock listener from the starters' sample sound model): output only, never code, so they show the standard without giving one answer to copy. Replace them with your own screenshots if you like (a PNG in content/code/pattern-detector/projects/, listed under benchmark:).
The example below is one complete trained app: a home sound alert for someone hard of hearing, with advice for each class, a "not sure" answer that still tells the user to look, a cut-off slider and a few made-up tests of its wording. Its model was trained in the Pattern Trainer's Sounds mode, as a student would (Upload sounds, Train model, Download), on ESC-10 clips: 32 to 33 five-second clips per class from folds 1 to 4 (Nothing urgent is rain, waves and a clock), tested on fold 5, which the model never heard. To run it, take my_home_sounds_model.json from the examples folder, put it in the starters folder beside pattern_model.py, and run the example like a starter. Students who unlock "Show one way" see only a short piece of it for the milestone they are on.
A filled-in testing record (the example app on ESC-10 fold 5, cut-off 0.85; yours will look different). The first model was tested, fooled, changed and tested again, as milestone 2 asks:
| I tried | I expected | First model said | After the change | How sure (after) | Notes |
|---|---|---|---|---|---|
| 8 babies crying | Baby crying | 7 right, 1 Dog barking | same | 1.00 (wrong one 0.73) | the wrong one is now "Not sure" |
| 8 dogs barking | Dog barking | 8 right | same | 0.997 or more | ok |
| 8 fires crackling | Fire crackling | 7 right, 1 Nothing urgent | same | 1.00 | a missed fire, and sure: no cut-off catches it |
| 24 rain, waves, clocks | Nothing urgent | 23 right, 1 rain as Fire (0.99) | 23 right, rain as Fire (0.65) | 0.87 or more | the rain is now "Not sure" |
| 8 chainsaws (never trained) | Nothing urgent | 6 as Fire crackling (0.997 to 1.00) | 8 Nothing urgent | 1.00 | false fire alarms; fixed by adding chainsaws |
| 8 sneezes (never trained) | Nothing urgent | 6 as Baby crying (0.99 to 1.00), 2 Nothing urgent | 6 Nothing urgent, 2 Baby crying | 0.61 and 1.00 | one now "Not sure", one still fooled |
| 8 roosters (never trained) | Nothing urgent | 8 Nothing urgent | 8 as Dog barking (0.79 to 1.00) | the change broke something that worked | |
| 8 helicopters (never trained) | Nothing urgent | 6 Nothing urgent, 2 Fire (0.51 and 1.00) | 7 Nothing urgent, 1 Fire (1.00) |
What changed: 11 chainsaw and 11 sneeze clips (from folds 1 to 4) were added to Nothing urgent and the model retrained. The chainsaws and most sneezes are fixed, but now every rooster is called Dog barking: adding examples to one class moved where the model draws its lines, and sounds it never heard landed somewhere new. The cut-off (0.85) turns the four shaky wrong answers into "not sure"; the confident ones (a fire called Nothing urgent, a sneeze, the roosters) need more examples, not a cut-off.
A sample reflection (strong): "The model was sure a chainsaw was a fire, 100% sure. I had trained Nothing urgent on rain, waves and a clock, so it only knew quiet sounds as 'nothing', and anything loud and rough sounded like fire to it. I added chainsaws and sneezes to Nothing urgent and the chainsaws were fixed, but then it called every rooster a dog barking, which had worked before. So I learned that fixing one mistake can make another, and I have to retest everything after every change. My cut-off is 0.85 because the shaky wrong answers were all under 0.80. A simple rule would do better at loudness: 'tell me about anything louder than talking' can be measured exactly. If my app is wrong, a deaf person might not go to a crying baby or a real fire, so 'not sure' still tells them to look, and I say it does not replace a smoke alarm."
What a weaker reflection looks like: "My app works well and the confidence was high." Ask: on which input did you not expect it to work, and what happened?
# EXAMPLE (teachers): a home sound alert, built from audio_pattern_trainer.py.
# Its model (my_home_sounds_model.json) was trained in the Pattern Trainer's
# Sounds mode on clips from ESC-10 (CC BY 3.0, Karol Piczak). Yours will look different.
#
# Who it is for: someone who is hard of hearing, at home.
# What it does: listens to a short recording and says whether it heard a baby
# crying, a dog barking or a fire crackling, and what to do about it. Anything
# it is not sure about is passed on as "not sure", never dropped.
#
# Plan (written before training):
# User: someone hard of hearing, at home.
# Job: tell them about sounds they would want to know about.
# Classes: Baby crying, Dog barking, Fire crackling, Nothing urgent
# (rain, waves, a clock: sounds that need no action)
#
# Cut-off, chosen from the testing record (see the teacher notes): the four
# shaky wrong answers scored 0.61 to 0.79, and all but one right answer scored
# 0.87 or more, so 0.85 catches the shaky ones for the cost of one right answer
# (0.76). Some wrong answers are still 0.95 or more sure, which no cut-off catches.
import os
import gradio as gr
from pattern_model import PatternModel
MODEL_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "my_home_sounds_model.json")
model = PatternModel.load(MODEL_FILE)
DEFAULT_CUTOFF = 0.85
# What to say for each class (the names come from the model file)
ADVICE = {
"Baby crying": "The baby is crying. Go and check on them.",
"Dog barking": "The dog is barking. Someone may be at the door.",
"Fire crackling": "Something is crackling like a fire. Check the kitchen and the heaters now.",
"Nothing urgent": "Nothing to worry about.",
}
def reply(label, score, cutoff):
"""Turn the model's answer into words for the user."""
if label is None:
return "Nothing heard", "That recording was empty. Try again."
if score < cutoff:
# Not sure is passed on, not dropped: a missed alert costs more than a false one.
return "Not sure", f"I heard something, maybe {label} ({score:.0%}). Have a look to be safe."
return label, ADVICE[label]
def listen(sound, cutoff):
if sound is None:
return "Record or upload a sound first.", ""
label, score = model.top(sound)
headline, advice = reply(label, score, cutoff)
return headline, advice
# Made-up answers, to test the wording and the cut-off without a microphone
TESTS = [
(None, 0.0, "Nothing heard"),
("Baby crying", 0.99, "Baby crying"),
("Dog barking", 0.84, "Not sure"), # just under the cut-off
("Dog barking", 0.85, "Dog barking"), # exactly on it
("Nothing urgent", 0.97, "Nothing urgent"),
]
for label, score, expected in TESTS:
got = reply(label, score, DEFAULT_CUTOFF)[0]
assert got == expected, (label, score, got)
gr.Interface(
fn=listen,
inputs=[
gr.Audio(sources=["microphone", "upload"], type="numpy", label="Record a few seconds, or upload a sound:"),
gr.Slider(0.5, 0.95, value=DEFAULT_CUTOFF, step=0.05, label="How sure should I be before I say what it is?"),
],
outputs=[gr.Textbox(label="What I heard"), gr.Textbox(label="What to do")],
title="Home sound alert",
description="For someone who is hard of hearing: sounds at home you would want to know about.",
flagging_mode="never",
).launch(show_error=True)
# Testing record (cut-off 0.85; the full table is in the teacher notes):
# I tried I expected It said How sure
# a sneeze Nothing urgent Baby crying 0.61 (now "Not sure")
# a rooster Nothing urgent Dog barking 0.998 (fooled, and sure)
# a chainsaw, first model Nothing urgent Fire crackling 1.00 (fixed by adding chainsaws)
Build a Python app where a trained model recognises something, and rules you write decide what to do about it.
Each part does the job it is best at. The model handles the messy, real-world input, such as a photo, a pose or a sound. The rules handle the parts you can describe exactly: counting, scoring, looking things up, and deciding what to do when the model is not sure.
Before you start: you have built one rules-based app (project A) and one trained app (project B).
The parts fit together like this:
input → trained model → label + how sure → your rules → response
Your rules should use how sure the model is, not only its label. What does your app do when it is not sure?
Before you start, write one sentence: who is it for, and what will it tell or do for them?
What to hand in
.py file, your model file and any data files.Check your app before you hand it in
Good habits. Only record yourself, or people who have said yes. Check what is behind you before you record. Your pictures and sounds stay on your computer.
Milestones:
# Pipeline:
# photo -> MODEL (Rock/Paper/Scissors + how sure) -> RULES (cut-off, who wins, score) -> result
# MODEL: telling a hand shape apart in a photo is too messy for rules.
# RULES: who beats whom, keeping score and when the game ends are exact.assert run([("Rock", 0.95, "Scissors")]) == ({"you": 1, "computer": 0}, "You win the round")
assert run([("Rock", 0.95, "Paper")]) == ({"you": 0, "computer": 1}, "I win the round")
assert run([("Rock", 0.95, "Rock")]) == (NEW_GAME, "Draw")
assert run([("Paper", 0.65, "Rock")]) == (NEW_GAME, "Show it again") # unsure: not playedlabel, confidence = model.top(image) # the MODEL part
computer = random.choice(list(BEATS))
score, headline, detail = play(score, label, confidence, computer, int(target)) # the RULES partif label is None or confidence < CUTOFF:
return score, "Show it again", f"I'm not sure that was {label} ({confidence:.0%}), so that throw doesn't count."What this project is. The joined-up half of the set. Project A used rules and project B used a trained model; here a model feeds rules. The learning is in the joins: what the rules do with the model's label and confidence, and what happens when the model is unsure or confidently wrong. A strong project cannot work with either part taken away.
Running it. Same as project B: students train in the browser-based Pattern Trainer, download a model file, and run a starter on their own laptop, adding rules of their own. Run an unchanged starter with its sample model on a school laptop beforehand. The "Check before class" and "For your IT team" notes in project B apply here too.
When to offer it. After students have built one app of each kind, since the pipeline diagram only makes sense when they have met both a rule and a trained model. If a class has done only A or only B, offer it as an extension.
What to change when you adapt it
choice_rules.py, sound_rules.py, measure.py); students may also write their own from scratch.gr.State as in the example. Offer a worked example in class if students have not met it, or pick ideas that avoid it.uses: in projects.yml if you want other skills.reveal: false (or remove reveal:) to turn "Show one way" off.Marking points to look for (replace with your own criteria):
Usual mistakes, and a question to ask.
Two models in a row: detect, then judge (a stretch idea, with a worked example). Several models make sense when each looks at something different or answers a separate question: two senses (a sound and a picture), separate questions (which sign and which hand: 4 + 2 classes, not 8 combinations), a gate before a specialist, or a closer look for the second step. Splitting one question about one photo into a chain rarely helps at this scale (both models read the same 1,280 numbers, and their mistakes multiply).
The worked example, combined-banana-checker.py, is the strongest case: a ready-made model and the student's own model, each doing what the other can't. MediaPipe's Object Detector (EfficientDet-Lite0, Apache 2.0; it ships with the same MediaPipe the trainer and starters use, and knows COCO's 80 everyday things, banana, apple and orange among them) finds each banana and its box; the app cuts each one out; a ripeness model trained in the Pattern Trainer on BananaID (single bananas on a plain background; Mutrofin, Fatichah, Yuniarti and Setiawan, Mendeley Data, CC BY 4.0) judges it; rules apply two cut-offs (is it a banana: 0.30; how sure of the ripeness: 0.60), count and advise. Students cannot train a detector (it took thousands of photos with boxes drawn on them), but they can train the part that is theirs. The point is knowing where it fails, not a perfect app.
Testing record (28 Oct 2026; 62 photos from COCO val2017 with an open per-photo licence, 27 of them with bananas; ripeness of the cut-outs judged by eye, as a student would):
| Part | What I tried | What happened |
|---|---|---|
| Ripeness model alone | 120 BananaID photos of bananas it never saw (same plain background) | 82 right. Overripe 27 of 30, Ripe 27 of 30, Unripe 21 of 30, Half ripe 7 of 30: the in-between stage is hardest |
| Detector alone, cut-off 0.30 | 27 photos with bananas, 35 without | found a banana in 15 of the 27; no false bananas |
| Detector alone, cut-off 0.20 | the same | found one in 21 of the 27, but called 4 apples and oranges bananas |
| The join at 0.20 | an apple in a bowl | the detector said banana (0.24), and my model said "Unripe" at 0.97: it judged an apple's ripeness as a banana's, sure of itself |
| Missed bananas | bowls in kitchens, small or half hidden bananas | 6 photos with no detection at all, so my model never saw those bananas and the app said "no bananas" |
| Counting | a bunch of 13 bananas | one box around the bunch: counted as 1 banana |
| The whole app | 27 cut-outs it kept | green bananas: all Unripe or "not sure" (right). Yellow bananas alone on a table: mostly right. Yellow bunches and close-ups: 10 called Overripe at 0.86 to 1.00, wrong by eye |
| Confidence | median confidence on BananaID test photos vs kitchen cut-outs | 0.95 vs 0.94: the model was just as sure on photos unlike its training ones |
The last two rows are the lesson: the ripeness model learned from single bananas on a plain grey background, and a cut-out from a bunch or a kitchen photo looks nothing like that (shadows between bananas may read as the brown patches of an overripe one; we can't see inside the model to be sure). Confidence did not warn us, so only testing on the real photos showed it. Fixes a student might try and test: train on cut-outs from the app's own photos, a cut-off from this testing record, or telling the user "one box may be a whole bunch". Model, data and every result: the examples folder.
Ways it could look. Students see two screenshots of finished apps where the model feeds the rules in different ways (rock paper scissors, where rules play the round and keep score, and a secret knock door that checks the last three sounds against a pattern): output only, never code. Replace them with your own screenshots if you like (a PNG in content/code/pattern-detector/projects/, listed under benchmark:).
The example below is one complete combined app: rock paper scissors against the computer, first to 2. The model reads the throw; the rules skip a throw under the cut-off ("show it again"), decide the round, keep score with gr.State, end the game and start a new one, and are tested on their own with made-up readings before they are joined to the model. Its model was trained in the Pattern Trainer as a student would (Upload photos, Train model, Download) on 60 pictures per class from the Rock Paper Scissors dataset's training set, and tested on its separate test set (30 per class, different hands, never seen). To run it, take my_rps_model.json from the examples folder, put it in the starters folder beside pattern_model.py, and run the example like a starter. The dataset's hands are computer-generated, so try your own hand on the webcam too: expect it to do worse, which is "train on theirs, test on yours" first-hand. Students who unlock "Show one way" see only a short piece of it for the milestone they are on.
A filled-in testing record (the example app on the dataset's test set, cut-off 0.70, first to 2; yours will look different):
Rules on their own (made-up readings)
| Throw (how sure) and the computer's | I expected | The rules said |
|---|---|---|
| Rock (0.95) v Scissors | you win the round, 1-0 | "You win the round", 1-0 |
| Rock (0.95) v Paper | I win the round, 0-1 | "I win the round", 0-1 |
| Rock (0.95) v Rock | draw, 0-0 | "Draw", 0-0 |
| Paper (0.65) v Rock | not played | "Show it again", 0-0 |
| Paper (0.70) v Rock | played, exactly on the cut-off | "You win the round", 1-0 |
| two wins, first to 2 | game over, new game | "You win the game!", back to 0-0 |
Model on its own (90 test pictures it never saw)
| Class | Right | What went wrong | How sure |
|---|---|---|---|
| Rock | 30 of 30 | 0.79 or more | |
| Scissors | 30 of 30 | 0.87 or more | |
| Paper | 20 of 30 | 10 called Rock | wrong ones 0.54 to 0.97; right ones as low as 0.40 |
Choosing the cut-off. From 0.70 up to 0.85, the cut-off catches the same 5 of the 10 wrong answers; 0.70 asks again least often (12 of the 80 right answers). Asking again costs little in a game, losing a round you won does not. 5 wrong answers were 0.85 or more sure: a cut-off can't catch those.
The whole app, in games
| Game | Throws (what the model read, how sure) v the computer | The app said | Notes |
|---|---|---|---|
| 1 | rock (Rock 1.00) v Scissors; scissors (Scissors 0.99) v Rock; scissors (Scissors 0.99) v Paper | win, loss, "You win the game!" | ok |
| 2 | rock (Rock 1.00) v Scissors; paper (Rock 0.59) v Rock; paper (Paper 0.93) v Rock | win, "Show it again", "You win the game!" | the unsure throw was not played, so a shaky read cost nothing |
| 3 | rock (Rock 1.00) v Paper; paper (Rock 0.97) v Rock; scissors (Scissors 0.99) v Paper | loss, "Draw", win: 1-1 | the player won that round, but the model was sure and wrong, so it was called a draw |
Game 3 is the point of the project: each part passes on its own, and the whole app still gets a round wrong, because the rules trust a confident wrong answer. Students may fix it in different ways (show what the model read and add a "That's not my throw" button that replays the round, or ask for the same throw twice), and a fix that lets the person catch the model's mistake is worth marking up.
A sample reflection (strong): "The rules were the easy part and they passed every test. The trouble was the join. In one game my paper was read as rock with 97% confidence, so my round was called a draw when I had won. The cut-off only caught the shaky reads, not that one. I changed the app so it always says what it read ('I read your throw as Rock') and added a 'That's not my throw' button that replays the round, then tested the same game again and got my point back. The model was trained on computer-made hands, and on my own hand it was much less sure, especially for paper, so I would add photos of real hands next. If it is wrong, the player loses a round they won, which is unfair but not dangerous, so I let them overrule it."
What a weaker reflection looks like: "It works well and the model and the rules work together." Ask: which input did you expect to break it, and what happened?
# EXAMPLE (teachers): a combined app. A trained model reads your hand;
# rules play the game. Built from image_pattern_trainer.py, with a model
# (my_rps_model.json) trained in the Pattern Trainer on 60 pictures per class
# from the Rock Paper Scissors dataset (CC BY 4.0, Laurence Moroney; the hands
# are computer-generated). Yours will look different.
#
# Who it is for: anyone who wants a quick game against the computer.
# What it does: you show a throw to the camera, the computer picks one, and the
# rules say who won the round. First to 2 wins. A throw it can't read well
# enough is not played: you show it again.
#
# Pipeline:
# photo -> MODEL (Rock/Paper/Scissors + how sure) -> RULES (cut-off, who wins, score) -> result
# MODEL: telling a hand shape apart in a photo is too messy for rules.
# RULES: who beats whom, keeping score and when the game ends are exact.
#
# Cut-off, chosen from the testing record (see the teacher notes): from 0.70 to
# 0.85 it catches the same 5 of the 10 wrong answers; 0.70 asks you to show it
# again least often (12 of 80 right answers). Asking again costs little in a
# game; losing a round you won does not. 5 wrong answers were 0.85 or more sure.
import os
import random
import gradio as gr
from pattern_model import PatternModel
MODEL_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "my_rps_model.json")
model = PatternModel.load(MODEL_FILE)
CUTOFF = 0.70 # under this, the throw is not played
DEFAULT_TARGET = 2 # rounds to win the game
BEATS = {"Rock": "Scissors", "Paper": "Rock", "Scissors": "Paper"} # each beats the one it names
NEW_GAME = {"you": 0, "computer": 0}
def round_winner(you, computer):
"""RULES: who wins one round."""
if you == computer:
return "draw"
if BEATS[you] == computer:
return "you"
return "computer"
def play(score, label, confidence, computer, target):
"""RULES: one throw. Returns the new score and what to say. An unsure throw is not played."""
if label is None or confidence < CUTOFF:
return score, "Show it again", f"I'm not sure that was {label} ({confidence:.0%}), so that throw doesn't count."
score = dict(score)
winner = round_winner(label, computer)
if winner != "draw":
score[winner] += 1
said = f"I read your throw as {label} ({confidence:.0%}). I threw {computer}."
if score["you"] >= target:
return dict(NEW_GAME), "You win the game!", said + f" Final score {score['you']}-{score['computer']}. New game."
if score["computer"] >= target:
return dict(NEW_GAME), "I win the game!", said + f" Final score {score['you']}-{score['computer']}. New game."
headline = {"you": "You win the round", "computer": "I win the round", "draw": "Draw"}[winner]
return score, headline, said + f" You {score['you']}, me {score['computer']}."
def throw(image, score, target):
if image is None:
return "Show a throw first.", "", score
label, confidence = model.top(image) # the MODEL part
computer = random.choice(list(BEATS))
score, headline, detail = play(score, label, confidence, computer, int(target)) # the RULES part
return headline, detail, score
# The rules tested on their own, with made-up readings and no camera.
# Each throw is (my label, how sure, the computer's throw).
def run(throws, target=DEFAULT_TARGET):
score, said = dict(NEW_GAME), None
for label, confidence, computer in throws:
score, said, _ = play(score, label, confidence, computer, target)
return score, said
assert run([("Rock", 0.95, "Scissors")]) == ({"you": 1, "computer": 0}, "You win the round")
assert run([("Rock", 0.95, "Paper")]) == ({"you": 0, "computer": 1}, "I win the round")
assert run([("Rock", 0.95, "Rock")]) == (NEW_GAME, "Draw")
assert run([("Paper", 0.65, "Rock")]) == (NEW_GAME, "Show it again") # unsure: not played
assert run([("Paper", 0.70, "Rock")]) == ({"you": 1, "computer": 0}, "You win the round") # on the cut-off
assert run([("Rock", 0.9, "Scissors")] * 2) == (NEW_GAME, "You win the game!") # first to 2, then a new game
assert run([("Rock", 0.9, "Scissors")] * 2, target=3) == ({"you": 2, "computer": 0}, "You win the round")
gr.Interface(
fn=throw,
inputs=[
gr.Image(type="pil", sources=["webcam", "upload"], label="Show your throw:",
image_mode="RGBA", webcam_options=gr.WebcamOptions(mirror=False)),
gr.State(dict(NEW_GAME)),
gr.Slider(1, 5, value=DEFAULT_TARGET, step=1, label="Rounds to win the game:"),
],
outputs=[gr.Textbox(label="Result"), gr.Textbox(label="What happened"), gr.State()],
title="Rock paper scissors",
description="Show rock, paper or scissors. First to win the rounds wins the game.",
flagging_mode="never",
).launch(show_error=True)