Chapter 1 // Learning from Data

What Is Learning?

How can a program get better at a task without anyone telling it the rules?

Reading time
12 min
Data

Most programs are a list of rules that a person wrote down. To work out a customer’s bill, add up the prices and apply the tax. Someone knew the rule, so someone could type it in.

Some tasks are not like that. Nobody can write down the rule for recognising a friend’s face, or for telling a real email from spam. We do these things easily and cannot say how. Machine learning is what we use for tasks like these: instead of writing the rule, we show the computer examples and let it find the rule itself.

This chapter introduces the handful of ideas that every later chapter depends on. There is very little mathematics in it.

Rules you cannot write down

Try to write a rule for this question: will this student pass the exam?

A first attempt might be “they pass if they studied a lot”. That is not something a computer can run. How much is a lot? Four hours? Six? Does it depend on the exam? To make the rule precise you need a number, and you do not know the number.

But suppose you have records from last year: how long each student studied, and whether they passed. Now the number can be found. Look through the records, and pick the cut-off that agrees with what really happened.

That is the whole idea. A learning program needs three things:

  1. Examples of the task, with the right answers.
  2. A rule with a gap in it: a number, or many numbers, left blank.
  3. A way to fill the gap so that the rule agrees with the examples.

Examples, features and labels

Here is the data used throughout the first part of this book. Twelve students each recorded how long they studied and what they scored. The pass mark was 65.

StudentHours studiedExam scorePassed?
A148no
B466yes
C671yes
D991yes
…………

The whole table is a . Each row, one student, is an .

The columns play two different roles. Hours studied is something we know in advance and want to predict from. That is a . Passed? is the answer we want to predict. That is the label, and a dataset that includes the answers is called labelled.

Checkpoint

A bank wants to predict whether a loan will be repaid, using each applicant's income and age. What is the label?

Learning a rule from examples

Now fill the gap. Our rule is:

Predict pass if hours studied is at least tt.

The number tt is blank. A rule with adjustable numbers in it is called a , and each adjustable number is a . This model has one. Choosing its value so that the rule fits the examples is called .

In the figure, you are the training procedure.

Figure

Find the cut-off

pass mark 65predict pass →4 hours, score 66, passed5 hours, score 68, passed5.5 hours, score 75, passed6 hours, score 71, passed7 hours, score 82, passed8 hours, score 83, passed9 hours, score 91, passed1 hours, score 48, failed1.5 hours, score 53, failed2 hours, score 50, failed3 hours, score 60, failed3.5 hours, score 57, failed
  • Passed (filled)
  • Failed (hollow, below the pass mark)
  • Your rule
Your rule
pass if hours ≥ 6.50
Right on the 12 known
8 of 12
Right on 6 new
hidden
6.50
Filled dots passed, hollow dots failed. The orange line is your rule: everyone to its right is predicted to pass. Try it: slide the threshold until the rule is right about all twelve students. Leave the test button alone for now.

Somewhere between 3.5 and 4 hours the rule gets all twelve right. Notice what you did: you tried a value, counted how many students the rule got right, and moved the value to make that count go up. A learning algorithm does exactly this, only with a better strategy than sliding by hand. The next two chapters are about those strategies.

The real test is new data

A rule that is right about last year’s students is not worth much on its own. Last year is over. What we want is a rule that will be right about the next student, whose result nobody knows yet.

Go back to the figure and press Test on new students. Six more students appear, who were kept aside and played no part in choosing your threshold.

Your rule does well on them, but not perfectly. One student passed after only three hours. Another failed after four and a half. Nothing was wrong with your threshold. These two simply do not follow the pattern, because hours of study is not the only thing that decides an exam.

This is the most important idea in the chapter:

  • A model is fitted on one set of examples.
  • It is judged on different examples that it has never seen. Those are called the .
  • Doing well on new examples is called being able to , and it is the only kind of doing well that counts.
Checkpoint

A model gets 100% of its training examples right and 60% of new examples right. What should you conclude?

Three kinds of problem

Almost every task in this book is one of three kinds. Telling them apart is the first step in solving any problem.

KindYou predictExample with our students
Regressiona numberWhat score will this student get?
Classificationa categoryWill this student pass or fail?
Finding structurenothing; there are no labelsDo the students fall into natural groups?

Predicting a number is called . Predicting a category is called . Both need labelled examples to learn from, so both are forms of : the labels supervise the model by showing it the right answers.

The third kind has no labels at all. The program is given only the features and asked what patterns it can find. That is called unsupervised learning, and it has its own part of the book.

The figure above was classification. The next chapter takes the same students and does regression: predicting the score itself.

In code

Here is the figure as a program. It tries every sensible threshold and keeps the one that gets the most known students right, then checks that rule on the new students.

import numpy as np

hours  = np.array([1, 1.5, 2, 3, 3.5, 4, 5, 5.5, 6, 7, 8, 9])
passed = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1], dtype=bool)

def accuracy(t, hours, passed):
    return np.mean((hours >= t) == passed)      # share of students the rule gets right

# Training: try each threshold, keep the best.
candidates = np.arange(0, 10.25, 0.25)
best_t = max(candidates, key=lambda t: accuracy(t, hours, passed))
print(best_t, accuracy(best_t, hours, passed))  # 3.75  1.0

# Testing: six students the rule has never seen.
new_hours  = np.array([0.5, 2.5, 3, 4.5, 6.5, 8.5])
new_passed = np.array([0, 0, 1, 0, 1, 1], dtype=bool)
print(accuracy(best_t, new_hours, new_passed))  # 0.667

Perfect on the twelve it learned from, four out of six on the new ones. Every model in this book is built and judged in these same two stages.

Key Takeaways

  • Machine learning is for tasks where nobody can write down the rule, but examples are available.
  • A dataset is a table of examples. Features are what you predict from; the label is what you predict.
  • A model is a rule with adjustable numbers. Training means choosing those numbers to fit the examples.
  • A model is only as good as its results on new data it has never seen.
  • Predicting a number is regression; predicting a category is classification.
You can now
  • Tell whether a task suits machine learning or is better solved with rules written by hand.
  • Point to the examples, the features and the label in a dataset.
  • Say whether a problem is regression or classification.
  • Explain why a model must be tested on examples it has not seen.

Exercises

Try each one before opening its solution. Getting stuck for a few minutes is where most of the learning happens.

Exercisethink

For each task, name some features, name the label, and say whether it is regression or classification.

  1. Estimating the price a house will sell for.
  2. Deciding whether an email is spam.
  3. Forecasting tomorrow’s highest temperature.
  4. Recognising which of three species a flower belongs to.
Hint

Ask what you would know before the answer (features) and what the answer is (label). A number means regression.

Solution
  1. Features: floor area, number of bedrooms, location, age. Label: the sale price. A number, so regression.
  2. Features: the words in the email, the sender, whether it has links. Label: spam or not. A category, so classification.
  3. Features: today’s temperature, pressure, wind, the time of year. Label: tomorrow’s highest temperature. Regression.
  4. Features: petal length, petal width, colour. Label: the species. Three categories, so classification.

Your features may differ. What matters is that they are things you would know before the answer, and that they plausibly carry information about it.

Exerciseby hand

Six students studied for 1, 2, 3, 4, 5 and 6 hours. Their results were fail, fail, pass, fail, pass, pass. Using a rule of the form “pass if hours are at least t”, which threshold makes the fewest mistakes? Can any threshold be right about all six?

Hint

There are only seven places to put the threshold. Count the mistakes for each.

Solution

Try each gap in turn. A threshold between 2 and 3 predicts a pass for the students with 3, 4, 5 and 6 hours, and is wrong only about the student with 4 hours. A threshold between 4 and 5 predicts a pass for 5 and 6 hours, and is wrong only about the student with 3 hours. Both make one mistake. Every other threshold makes two or more.

No threshold is perfect, because a pass at 3 hours comes before a fail at 4 hours. A single cut-off can never put those two students on the correct sides. Real data usually looks like this, and a good model is one that makes few mistakes, not none.

Exercisethink

A model is right about 100% of the examples it was trained on and 60% of a set of new examples. What has probably happened, and which number describes how good the model is?

Hint

Which of the two numbers was measured on data the model had never seen?

Solution

The model has fitted its training examples very closely, including details that are particular to those examples and do not hold in general. It has partly memorised them.

The number that describes the model is 60%, because that is how it behaves on data it has not seen, which is the only situation it will ever be used in. The chapter on generalization is about this gap and how to close it.

Exercisethink

Give one task where writing the rules by hand is the better choice, and say why.

Hint

Think of a task where someone has already written the exact rule down.

Solution

Any task where the rule is known, short and exact. Working out the tax owed on an income, sorting a list of names, or checking that a password has at least eight characters. Someone has already written the rule down, a program that follows it is always right, and it needs no examples. Learning the rule from data would be slower, need thousands of examples, and still make occasional mistakes.

Machine learning earns its place when the rule exists but nobody can state it, as with recognising a face or judging whether a message is spam.

Exercisewith the figure

In the figure “Find the cut-off”, put the threshold at 2 hours and count the mistakes. Move it to 6 hours and count again. Which kind of mistake does each setting make? Where between them do the mistakes disappear?

Hint

A threshold that is too low passes students who failed. Think about what one that is too high does.

Solution

At 2 hours the rule says “pass” to nearly everyone, so its mistakes are students who failed but were predicted to pass. At 6 hours it says “fail” to nearly everyone, so its mistakes are students who passed but were predicted to fail.

Between 3.5 and 4 hours both kinds of mistake are gone and the rule is right about all twelve. Sliding the threshold trades one kind of mistake for the other, an idea that returns in the chapter on measuring classifiers.

Going further

Where the examples come from

Everything a model knows comes from its examples. If last year’s records only include students from one school, the rule may fail at another. If the labels contain mistakes, the model learns the mistakes. Collecting good examples is often harder than the learning itself, and the chapter on preparing data comes back to this.

A fourth kind of problem

Some programs learn by trial and error instead of from a table: they act, receive a reward or a penalty, and adjust. This is called reinforcement learning, and it is how programs learn to play games. It is outside the scope of this book.

References and further reading

Last updated Spotted a mistake? Suggest an editWhat changed

In this chapter
  1. Top of the chapter
  2. 1.1Rules you cannot write down
  3. 1.2Examples, features and labels
  4. 1.3Learning a rule from examples
  5. 1.4The real test is new data
  6. 1.5Three kinds of problem
  7. 1.6In code
  8. Exercises
Search

    The Book of Machine Learning
    Search
    Reading settings
    Text size
    Colours

    Saved in this browser only.

    Keyboard shortcuts
    /
    Search the book
    ← →
    Previous and next chapter
    g
    Glossary
    c
    Table of contents
    e
    Jump to the exercises
    t
    Reading settings
    ?
    Show this list
    Esc
    Close a window or pop-in