The answersDownload the PDF
Worksheet

8.7 Models as text

Learning · Robot club · about 15 min

BugBotLab
NameClassDate

What this lesson is about

Saving and loading a model with JSON; models trained elsewhere.

Questions 6 marks in all

  1. [1 mark]What does this program print?

    import json
    sample = ([16, 16], "wall-ahead")
    back = json.loads(json.dumps(sample))
    print(back)
    print(back == sample)
  2. [1 mark]What do json.dumps and json.loads do?

    1. Adumps turns data into text; loads turns text back into data
    2. Bdumps deletes a model; loads restores it
    3. Cdumps saves to a file; loads downloads from the internet
    4. DBoth turn text into data
  3. [1 mark]What does this program print?

    import json
    MODEL = '{"kind": "nearest-neighbour", "samples": [{"x": [16, 16], "label": "wall-ahead"}, {"x": [50, 50], "label": "open"}]}'
    model = json.loads(MODEL)
    data = [(s["x"], s["label"]) for s in model["samples"]]
    print(model["kind"], len(data), data[1][1])
  4. [1 mark]Why does the saved model include a kind field?

    1. ASo the program that loads it knows what to do with it
    2. BJSON refuses to save without one
    3. CIt records who made the model
    4. DIt makes the text shorter
  5. [1 mark]How do you get a numpy weights table into a form JSON can write?

    1. AW1.tolist()
    2. Bjson.dumps(W1) works directly
    3. Cstr(W1)
    4. DW1.shape
  6. [1 mark]Which of these can JSON write down as they are?

    Tick every answer that is true.

    1. AA list of numbers
    2. BA dictionary
    3. CNone
    4. DA numpy array
    5. EA tuple, kept as a tuple

The task: a model from text

Load the model in MODEL, classify the current view with it, and print model says: <label>. Do not drive.

# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
import json
MODEL = '{"kind": "nearest-neighbour", "features": "depth grid rows 2 and 3", "samples": [{"x": [54, 52, 51, 51, 51, 51, 52, 54, 54, 52, 51, 51, 51, 51, 52, 54], "label": "open"}, {"x": [16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16], "label": "wall-ahead"}, {"x": [36, 47, 46, 46, 46, 16, 16, 16, 36, 47, 46, 46, 46, 16, 16, 16], "label": "gap-left"}, {"x": [16, 16, 16, 46, 46, 46, 47, 36, 16, 16, 16, 46, 46, 46, 47, 36], "label": "gap-right"}]}'
model = json.loads(MODEL)
print(model['kind'], len(model['samples']), 'samples')

Plan your program here, then type it in and press Run.

QR code
Do it on the robot
www.bugbotlab.com/learn/8-7-models-as-text/
The simulator checks it and tells you when it passes. Nothing to install, no account.

Challenges

  1. Save the trained network from lesson 8.4 as JSON with kind set to network, and write predict(model, view) that works for both kinds.
  2. Add a trained_on field with today's date and print it when the model loads.
  3. Store k in the model and vote among the k nearest samples.