← Pattern Detector projects

Train a model, then use it in Python

Train a tiny picture model in the Pattern Trainer, download it as my_model.json, see it answer on the board, then load the same file in a Python starter and see a prediction there.

Phones sort your photos into people, pets and food without anyone writing a rule for what a dog looks like. Someone trained a model on examples, then put it inside an app. That second part is what you'll do in these projects.

In these projects your app uses a model you train. The training happens in the Pattern Trainer, a web page; the model then goes into a Python app on your computer as one file, my_model.json. This lesson does that once, with something small, so you know the whole path before you start a project.

How this lesson works: Predict, Run, Investigate, Make
PredictRead the code and say what it will do before you run anything. A wrong guess is fine: it shows you what to look for.

Predict

You train a model on 10 photos of your pencil case and 10 of your water bottle. Then you show it a banana. What will it say?

RunRun it and compare the result with your prediction.

Train and try

  1. Open the Pattern Trainer in a new tab and choose Pictures. Name the first class after something on your desk, then + Add a class for a second thing.
  2. Hold each thing up to the camera and Hold to record about 10 photos per class, moving it a little. Click Train model.
  3. Click Download my_model.json. On the board, click Open your model file and choose it.
  4. Add a few photos the model hasn't seen: each thing somewhere else, and one thing that is neither. Which does it get right? How sure is it about the one that is neither?

The photos stay on your computer: the trainer and the board work inside the browser, and the model file holds only your class names and numbers.

Try it yourselfYour edits are saved in this browser.

Open your model file, add at least 4 photos it has never seen, and see what it says.

Use the board. This ticks when you get there.

InvestigateTrace how each line of code connects to what you see.

Investigate

This is the part of the starter image_pattern_trainer.py that answers. pattern_model.py does the hard part, exactly as the trainer did: centre square, picture to numbers, then your trained numbers.

classify.py
from pattern_model import PatternModel

model = PatternModel.load("my_model.json")
print("Classes in this model:", model.classes)


def classify(image):
    if image is None:
        return "Upload or take a photo first."
    label, score = model.top(image)
    if score < 0.8:
        return f"Might be {label}, but I'm not confident ({score:.2f})."
    else:
        return f"{label} ({score:.2f} confidence)"

Open your my_model.json in a text editor (Notepad or TextEdit) and scroll through it.

model.top(image) gives back two things: the most likely class and how sure the model is, from 0 to 1. Follow them through the if.

The starter never types Cat, Coffee or your own class names.

What is in my_model.json?

model.top(image) gives back ("Pencil case", 0.62). What does the app say?

Where do the class names in the app come from?

MakeBuild something new using what you have learned. Expect a few tries; that is normal.

Run it in Python

  1. Set up the starters on your computer, if your teacher hasn't already.
  2. Put your my_model.json in the starters folder, replacing the sample (Cat vs Coffee).
  3. Run python image_pattern_trainer.py and open the address it prints (usually http://127.0.0.1:7860).
  4. Give it one of the photos you tried on the board. It should give the same class and nearly the same confidence.

Then change the # ADAPT: lines: a message that would help someone, and a threshold that suits your test photos. That is where Brief B starts.

Now you can
Finished the course?Go over it: Pattern Detector projects recapEvery idea in one place, to check you've got it.You reached the endBack to Pattern Detector projects
For teachers

Students train a two-class picture model in the Pattern Trainer, test it on the board on photos it hasn't seen, read the starter's classify function, and run the same my_model.json in the Python starter on their own computer. About 40 minutes.

Open the teacher guide: answers, solutions, slides and a worksheet.

Students will be able to

Before class

The idea: a model is trained on examples in one place (the Pattern Trainer, a web page) and used in another (a Python app), and what travels between them is one small file of class names and numbers. This lesson does that path once, with two things from the student's desk, before any project.

Before class: the starters need installing once per computer (Python 3, then pip install -r requirements.txt, about 0.5 GB, no TensorFlow; setup). Do it before the lesson, or the last step becomes an install lesson. On a student laptop on the school network, check tools.learningwaypoints.com/trainer/ loads (about 35 MB the first time, for the trainer and again for the board) and the camera is allowed. Without a camera, students use Upload photos with photos they have.

Privacy: training happens in the browser and photos never leave the computer (the trainer's Privacy page shows how to check). The board keeps students' test photos in this browser only. my_model.json holds class names and numbers, no photos. Train on things, not people.

Where this sits: the first step of Pattern Detector projects, after Apps with Gradio. It needs Gradio apps, if/else and f-strings; the trainer does the training and pattern_model.py hides numpy. Machine learning with Gradio shows how a model works inside; either can come first.

Running the lesson

  1. Predict: take a show of hands. Most say 'I don't know'.
  2. Train and try: 10 minutes. Ask: what did it say about the thing that was neither, and how sure was it?
  3. Investigate: everyone opens my_model.json in a text editor. Point out there is no photo in it.
  4. Run it in Python: pair students whose install worked with those whose didn't.

The hard part (on purpose)

Moving the downloaded file into the starters folder in place of the sample. Ask students to say out loud which folder the app reads from before they run it.

When students get stuck

Stretch and support

Stretch: Add a third class, Neither, with photos of other things. Does the thing that was neither now get the right answer?

Support: Train in pairs on one laptop; skip the Python step and do it at the start of Brief B.

Where it leads

Next: Brief B (a model you train) builds an app around this model; Brief A (rules you write) can come first. Real world: photo apps, recycling sorters and parcel scanners are a trained model inside an app.

What each step is for