# Chapter 1: What Is Learning?

> Features, labels, and what it means for a program to learn from examples. Opening question: How can a program get better at a task without anyone telling it the rules?

From *The Book of Machine Learning*, a free interactive machine learning textbook. Interactive version, with figures to use: https://thebookofml.com/what-is-learning/

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.

| Student | Hours studied | Exam score | Passed? |
|---|---|---|---|
| A | 1 | 48 | no |
| B | 4 | 66 | yes |
| C | 6 | 71 | yes |
| D | 9 | 91 | yes |
| … | … | … | … |

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

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

**Note:** Real datasets have many features. A house has a size, an age, a location and a number of rooms. One feature is enough to see every idea in this chapter.

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

- The income — Income is known in advance and used to make the prediction, so it is a feature.
- Whether the loan was repaid **(correct)** — The label is the answer you want to predict. Income and age are the features used to predict it.
- The applicant — One applicant is one example, a whole row. The label is a single column of that row.

## Learning a rule from examples

Now fill the gap. Our rule is:

> Predict **pass** if hours studied is at least $t$.

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

In the figure, you are the training procedure.

> **Interactive figure: Find the cut-off.** 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.
> (Use it at https://thebookofml.com/what-is-learning/)

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 test set.
- Doing well on new examples is called being able to generalize, and it is the only kind of doing well that counts.

**Check your understanding:** A model gets 100% of its training examples right and 60% of new examples right. What should you conclude?

- It is an excellent model, since 100% is perfect — The 100% is on examples it was fitted to. That says little about how it handles anything new.
- Expect about 60% in real use **(correct)** — Performance on unseen examples is the honest estimate. The gap means the model has partly memorised its training data.
- The new examples must be wrong — New examples that disagree with the model are information, not errors. They are the real test.

## 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.

| Kind | You predict | Example with our students |
|---|---|---|
| Regression | a number | What score will this student get? |
| Classification | a category | Will this student pass or fail? |
| Finding structure | nothing; there are no labels | Do the students fall into natural groups? |

Predicting a number is called regression. Predicting a category is called classification. Both need labelled examples to learn from, so both are forms of supervised learning: 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.

**Common mistake: Marking your own homework**

The most common mistake in machine learning is to measure a model on the same examples it learned from and report that number. It is always flattering and often meaningless. Before you train anything, set some examples aside and do not look at them. The score on those examples is the one to believe, and the one to tell other people.

## 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.

```python
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**.

## What you should now be able to do

- 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

### Exercise (think)

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.

### Exercise (by 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.

### Exercise (think)

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.

### Exercise (think)

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.

### Exercise (with 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](https://thebookofml.com/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

- H. Kinsley and D. Kukieła, *Neural Networks from Scratch in Python*, chapter 1, [nnfs.io](https://nnfs.io).
- Google, *Machine Learning Crash Course*, [developers.google.com/machine-learning/crash-course](https://developers.google.com/machine-learning/crash-course).
- S. Yee and T. Chu, [A Visual Introduction to Machine Learning](https://r2d3.us/visual-intro-to-machine-learning-part-1/), R2D3.

## Next

The threshold rule could only say pass or fail. The next chapter keeps the same twelve students and predicts the score itself, using the simplest model that has adjustable numbers: a straight line.
