ML fundamentals1 / 22

Lesson 1 · Learning from data

Learning from examples

The problem

You run a pizza shop. A customer on the phone asks, "How long will it take?" You want a good answer every time.

In the Vectors lesson you guessed a rule from three deliveries: 4 minutes per km, plus 6 minutes per traffic level. It was a weighted sum, and it fitted all three exactly.

DeliveryDistance (km)Traffic levelMinutes
A208
B5126
C3224

Those three were made up to fit. Real deliveries are messy. Lights turn red, and customers take a while to answer the door. With hundreds of real deliveries, no rule fits every one, and guessing by eye stops working.

So we let the computer find the rule. That's what machine learning does: it learns a rule from examples. This lesson shows the four parts every learning method has: examples, a model, a score and a way to improve.

Examples with answers

Here are ten real deliveries from the shop's records. All ten were in light traffic (level 1), so for now only the distance changes.

A collection of examples like this is a dataset. Each row is one example. Each example has:

  • features: the numbers you know before the trip starts, like distance and traffic level.
  • a label: the answer you want to predict, here the minutes the trip took. It's also called the target.

Step through the table. Each row becomes one dot.

#kmtrafficminutes
11.1115.3
23.2121.6
31.5118.9
44.2130.1
53.7122.3
65.7133.2
71.8119.9
82.8120.9
90.6110.8
101.9119.2
0123456010203040distance (km)minutes
Row 0 of 10

Press play or step forward to plot the rows one at a time.

The table becomes a picture. Each delivery is one dot: its distance across and its minutes up. The label is the dot's height.

Things to notice:

  • Each row is one dot. The feature sets how far across it sits, and the label sets its height.
  • The dots rise from left to right. Longer trips take longer, but not by exactly the same amount each time.
  • No straight line passes through all ten dots.

Learning from examples that come with their answers is called supervised learning. The labels supervise: they tell the method what it should have predicted.

When the label is a number, like minutes, the task is regression. When the label is a category, like "late" or "on time", the task is classification. Lesson 4 covers that.

Predict first

Which of these is supervised learning?

DigressionThree kinds of learning, and where each lives in the bookLearning from answers, from no answers, and from a score. · 2 min

Machine learning splits into three main kinds, by what the data gives you.

  • Supervised learning: examples with answers. Predict delivery times, or whether a delivery will be late. This course spends most of its time here.
  • Unsupervised learning: examples with no answers. Find groups of similar customers, or the main directions the data varies in. This is unsupervised learning, which this course covers near the end.
  • Reinforcement learning: an agent acts, and gets a score (a reward) for how well it did. Nobody tells it the right action. A delivery robot that learns routes from trip times would work this way. The Reinforcement learning course covers it.

The lines blur in practice. Large language models start with a supervised task: predict the next word, where the text itself gives the answer. Then they are tuned with rewards.

A model: a rule with knobs

The dots rise roughly along a straight line. So guess a rule of this shape:

minutes=w×km+b\text{minutes} = w \times \text{km} + b

Here ww is the minutes each km adds. bb is the minutes that don't depend on distance, like the handover and the walk to the door.

A rule like this, which turns an example's features into a prediction, is a model. It's a function: km goes in, predicted minutes come out.

The numbers ww and bb are the model's parameters. They're the knobs. The shape of the rule (a straight line) is fixed, and the parameters choose which line.

Worked example

Two predictions with w = 4 and b = 11

  1. Delivery 2 was 3.2 km. The model predicts 4×3.2+11=23.84 \times 3.2 + 11 = 23.8 minutes. It took 21.6, so the model was 2.2 minutes too slow.

DigressionWhy 'model' and 'parameters'?A function and its knobs, under ML's names. · 1 min

In maths you'd call f(x)=wx+bf(x) = wx + b a function with two constants. ML calls the same thing a model with two parameters. The new names stress two things.

A model is a simplified picture of the world. "Time grows in a straight line with distance" isn't the whole truth about deliveries, but it's useful.

Parameters are the constants that the data chooses. You choose the model's shape. Learning chooses its parameters.

Scoring a model: the loss

To improve a model, you need to know how wrong it is. And you need that as one number, so you can tell whether a change made things better or worse.

Start with each delivery's miss: the minutes it took, minus the minutes the model predicted. A positive miss means the delivery took longer than predicted.

Predict first

A line misses one delivery by +5 minutes and another by −5 minutes. What is the average miss?

So square each miss, then average. A rule that turns a model's mistakes into one number like this is a loss function, or the loss for short. Smaller is better. This particular loss is called the mean squared error, and the next lesson looks at it closely.

Worked example

The loss of minutes = 4 × km on deliveries A, B and C

  1. Predict: A is 4×2=84 \times 2 = 8, B is 4×5=204 \times 5 = 20 and C is 4×3=124 \times 3 = 12 minutes. (This model ignores traffic, and has b=0b = 0.)

The maths

Write yiy_i for the label of example ii (the minutes it took), and y^i\hat y_i ("y hat") for the model's prediction. With nn examples, the loss is

L=1n∑i=1n(yi−y^i)2.L = \frac{1}{n} \sum_{i=1}^{n} (y_i - \hat y_i)^2 .

Read it as: for each example, take the miss yi−y^iy_i - \hat y_i, square it, add them all up and divide by nn. In the figure below, each miss is a vertical stick from a dot to the line.

Now try it. Drag the two handles to move the line, and watch the loss.

0123456010203040distance (km)minutes

Line: minutes = 2.00 × km + 10.0

Biggest miss: delivery 6, 11.8 minutes

Loss (average squared miss): 46.9

Fit a line by hand. Each delivery's miss is a vertical stick; the thickest one is the biggest. The loss turns all ten sticks into one number.

Things to notice:

  • One number scores the whole line. A line that's close to most dots but far from one can still score badly, because squaring makes big misses count a lot.
  • You can push the loss down by hand. Try 4×km+114 \times \text{km} + 11: its loss is 3.81.
  • There's a floor. "Show the best line" reveals the line with the smallest loss, 3.64. No line reaches 0, because no line passes through every dot.

Training: the learning loop

You have now done training: adjusting a model's parameters, using examples, so the loss gets smaller. Every method in this course trains the same way, in a loop:

  1. Predict: run the model on the examples.
  2. Score: compare the predictions with the labels to get the loss.
  3. Adjust: change the parameters so the loss goes down.
  4. Repeat until the loss stops going down.

Here is the loop on deliveries A, B and C, with a model that has one knob: minutes=w×km\text{minutes} = w \times \text{km}. The rule for adjusting is the simplest one there is. Try w+1w + 1 and w−1w - 1, keep whichever has the lower loss, and stop when neither helps.

  1. Data
  2. Model (w = 2)
  3. Predictions
  4. Loss
  5. Adjust w
0123456010203040distance (km)minutesABC
 kmminpred.missmiss²
A284··
B52610··
C3246··
average·
Step 0 of 14

The model with w = 2 predicts w × km for each delivery.

Loss so far: none yet

The learning loop, one stage at a time. Only w changes. The data and the loss rule stay the same on every turn.

Worked example

Training w from 2

  1. Start at w=2w = 2. The predictions are 4, 10 and 6 minutes, and the misses are 4, 16 and 18. The loss is (16+256+324)/3=198.7(16 + 256 + 324) / 3 = 198.7.

The true best ww is about 5.7, between the whole numbers the loop tried. A smaller nudge would get closer, but would need more turns.

Nudging one knob at a time works for two knobs. It doesn't work for a model with a million knobs, which is normal for neural networks. Two better ways to adjust are coming:

  • For straight-line models, least squares finds the best parameters in one step, with no loop at all (next lesson).
  • For everything else, gradient descent uses the slope of the loss to move every knob at once (Lesson 3). It moves them in the direction that lowers the loss fastest.

Putting it together

Here is every part of this lesson, in the pizza shop:

PartIn the pizza shop
Dataset10 past deliveries
Featuresdistance in km
Labelminutes taken
Modelminutes=w×km+b\text{minutes} = w \times \text{km} + b
Parametersww and bb
Lossthe average squared miss
Trainingmove ww and bb until the loss is as small as you can get it

When you dragged the line in the fit-by-hand figure, you were the training method. Once the loss is small, the shop uses the trained model on new orders: a 5 km trip gets 3.9×5+10.9≈303.9 \times 5 + 10.9 \approx 30 minutes.

One part is still missing. Delivery C shows that traffic matters, and this model can't see it. The next lesson, linear regression, uses several features at once and finds the best weights exactly.

Common misconceptions

"The model is the table of past deliveries." The model is the rule, w×km+bw \times \text{km} + b. The table is only used to choose ww and bb. The point is to predict deliveries that aren't in the table.

"Training changes the data, or the loss." Only the parameters change. The examples and the loss rule stay fixed for the whole loop.

"The goal is a loss of 0." Real data has noise. On the ten deliveries, the best line still has a loss of 3.64. A model that scored 0 would be following the noise, and would do worse on new orders. That problem is called overfitting.

"Supervised means a person watches the training." It means every example comes with its answer, the label. The training itself runs on its own.

Recap

  • A dataset is a collection of examples. Each example has features (what you know beforehand) and, in supervised learning, a label (the answer).
  • Predicting a number is regression. Predicting a category is classification.
  • A model is a rule that turns features into a prediction. Its parameters are the numbers that pick which rule.
  • A loss function turns all the model's mistakes into one number. The average squared miss is the most common one for numbers.
  • Training is a loop: predict, score with the loss, adjust the parameters, repeat. Only the parameters change.
  • No code in this lesson. The next lesson fits the same model with scikit-learn and PyTorch.