Which parcels will be late?
A delivery firm sends 20,000 parcels a day. Some arrive late, and customers ring the support line.
The manager asks: can we warn customers before a parcel is late? Nobody can write down every reason a parcel is late.
But the firm has a year of past deliveries. Each one says where it went and whether it was late. A computer can learn from those.
By the end of this lesson
Note
I can explain how a model learns from examples.
Key words
| Word | What it means | Example |
|---|---|---|
| Machine learning | finding a rule from examples, not writing it by hand | |
| Model | the rule a computer learns | |
| Example | one past case with its known answer | |
| Feature | a fact the model uses to decide | distance_km |
| Label | the answer for an example | late |
| Prediction | the model’s answer for a new case |
The cells students fill in are left blank in this preview.
A model is a rule found from examples
In ordinary programming, a person writes the rule. "If the parcel goes over 30 km, warn the customer."
In machine learning, you give the computer many examples with their answers. It finds the rule that fits them best. That rule is the model.
Then you use the model on new parcels. Its answer is a prediction.
Features go in, a label comes out
Each example is a row of facts. The facts the model uses are features: distance, the day, the weight.
The answer you already know is the label: late or on time.
The model learns how the features link to the label. Later it sees only features, and guesses the label.
Past parcels, as examples
| Distance (km) | Day | Weight (kg) | Late? (label) |
|---|---|---|---|
| 5 | Monday | 1 | No |
| 12 | Tuesday | 3 | No |
| 20 | Friday | 2 | No |
| 35 | Friday | 8 | Yes |
| 40 | Monday | 4 | Yes |
| 60 | Saturday | 2 | Yes |
The cells students fill in are left blank in this preview.
A common mistake
Warning
Many people think a model understands why parcels are late. It does not. It only finds a pattern in the examples it was given. If the examples are few or wrong, the rule it learns is wrong too.
Learning means trying rules and keeping the best
How does the computer find the rule? One simple way is to try many rules.
Try "late if over 10 km", then "over 30 km", then "over 50 km". For each one, count how many past parcels it gets right. Keep the best.
This search for the best rule is called training. Real models try millions of rules, but the idea is the same.
Train a tiny model
# Past parcels: distance in km, and whether each one arrived late.
distances = [5, 12, 20, 35, 40, 60]
late = [False, False, False, True, True, True]
# Try three rules: "late if the distance is over this number".
for threshold in [10, 30, 50]:
correct = 0
for i in range(len(distances)):
guess = distances[i] > threshold
if guess == late[i]:
correct = correct + 1
print("Over", threshold, "km means late:", correct, "of 6 right")
# Add 25 to the list of thresholds, then press Run.
# Does 25 do better or worse than 30?