Simple Algorithm
Machine Learning · Initialization · 16 min

What Is Machine Learning?

Learning from examples instead of writing rules.

Try to write exact rules that tell a handwritten 4 from a 9, and you will still be at it next month. A machine learning system gets there from examples: thousands of digits, each labeled with the right answer. In this lesson you will train three models yourself, push them until they break, and meet the question at the heart of the field: will a pattern learned from past examples hold up on the next one?

What you’ll learn

  • Explain what it means for a program to learn, using a task, a measure of performance and experience.
  • Name the four ingredients of almost every learning method: data, a model family, a loss and an optimizer.
  • Tell training error from test error, and recognize underfitting and overfitting when you see them.
  • Sort problems into supervised (regression or classification), unsupervised, self-supervised and reinforcement learning.
  • Describe what learning from data cannot do: repair unrepresentative data, or turn a correlation into a cause.

Rules nobody wrote

In ordinary programming a person writes the rules and the computer follows them. That works for payroll and for sorting a list. It fails for reading handwriting: "a 9 has a closed loop on top and a 4 does not" is broken by the first person who closes the top of their 4.

Machine learning turns the job around. You supply examples together with the right answers, and a learning algorithm produces the rules. What comes out is a model: a program that maps a new input to a prediction.

AspectTraditional programmingMachine learning
A person suppliesthe rulesexamples, usually with the right answers
The computer producesanswersthe rules (a model), and then answers
Works best whenthe rules are known and stable: tax law, sorting, accountingthe rules are hard to state but examples are plentiful: speech, images, fraud
Breaks whenthe world is too messy to describethe examples are few, wrong or unlike the cases that matter

Below, each dot is an example described by two measurements (its position) and a label (its color). A decision tree learns rules of the form "if this measurement is below some threshold, go left; otherwise go right", and it picks every measurement and threshold itself, from the data.

What counts as learning?

Tom Mitchell's textbook gives a definition you can test: a program learns from experience EE with respect to a task TT and a performance measure PP if its performance at TT, as measured by PP, improves with EE.

The definition forces you to say what the task is, what the program gets to see, and how you will keep score. Those three choices decide most of what follows.

SystemTask TTExperience EEPerformance PP
Spam filterlabel each incoming email spam or notemails that people marked as spam or notfraction of new emails labeled correctly
Digit readername the digit in a small grayscale imagetens of thousands of labeled imagesaccuracy on images it has not seen
Checkers playerwin at checkersgames played, including against itselffraction of games won
Price estimatorpredict the sale price of a housepast sales with their final pricesaverage size of the error
Check your understanding

Which of these systems learns, in Mitchell's sense?

  1. A calculator that always adds correctly
  2. A thermostat that turns on the heating whenever the room drops below 20 °C
  3. A phone keyboard whose word suggestions get more accurate the more you type
  4. A program that sorts any list perfectly
Show the answer

C. A phone keyboard whose word suggestions get more accurate the more you type

Only the keyboard's performance at its task (suggesting your next word, scored by how often you accept the suggestion) improves with experience (what you type). The other three may work perfectly, but nothing they see ever changes how they behave.

The four ingredients

Almost every method in this course, from a straight line to a large neural network, combines four ingredients:

  1. Data. Each example is described by features, numbers such as pixel brightness or floor area, collected into a feature vector. In most problems it also has a label: the right answer. The examples you learn from form the training set.
  2. A model family. The set of functions the learner may choose from: straight lines, trees of depth at most 3, networks of a given size. Each member is one candidate rule, a hypothesis.
  3. A loss. A loss function scores how wrong one prediction is. Averaged over the training set, it says how well a candidate fits.
  4. An optimizer. A procedure that searches the family for the member with the smallest average loss. Running it is what "training" means.
training loss=1n∑i=1n(y^i−yi)2\text{training loss} = \frac{1}{n}\sum_{i=1}^{n}\big(\hat y_i - y_i\big)^2
The most common loss for numeric predictions: the squared error between each prediction y^i\hat y_i and the true value yiy_i, averaged over the nn training examples (the symbol ∑\sum means "add up the terms for i=1i=1 to nn"). Squaring makes every miss count positively and punishes big misses much more than small ones.
Predict before you look

A model predicts the prices of three houses as 3, 5 and 7 (in hundreds of thousands of dollars). The true prices are 4, 5 and 9. What is its average squared error?

Show the answer

1.67

The errors are 3−4=−13-4=-1, 5−5=05-5=0 and 7−9=−27-9=-2. Their squares are 11, 00 and 44, and the average is 5/3≈1.675/3\approx1.67. The single miss of 2 contributes four times as much as the miss of 1: that is what squaring does.

Now try a model family with a single knob. k-nearest neighbors classifies a new point by a vote among the kk training points closest to it. Its "training" is unusually lazy: it just stores the examples, and all the work happens when you ask for a prediction. The number kk is chosen by you, not by the optimizer: it is a hyperparameter.

Fitting is easy, generalizing is hard

A model that has memorized its training set fits it perfectly and may still be useless. What you want is generalization: low error on new examples from the same source. So you set aside a test set before training, never let the learner see it, and judge the final model there.

Below, the training points come from a smooth wave plus random noise. A polynomial of degree 1 is a straight line; each extra degree lets the curve bend once more.

Think first The true wave, the curve the data came from, scores a test error of about 0.036 here, not zero. Why can't even the perfect curve get every point right?

Because each point is the wave plus random noise, and the noise is not a function of the input: two examples with the same xx can have different yy. No model can predict it. This floor is called the irreducible error, or the Bayes error. The Descent lesson The Learning Problem derives the best possible predictor, and the Convergence lesson Risk, Bayes Optimality & Excess Risk measures how far learned models fall short of it.

Many ways to learn

The four ingredients stay the same across machine learning. What changes most is the data: what it tells the learner, and what it leaves out.

SettingThe data gives youTypical questionExample
Supervised: regressioninputs with numeric answersHow much?a house's price from its size and location
Supervised: classificationinputs with category answersWhich one?spam or not; which digit
Unsupervisedinputs onlyWhat structure is here?groups of shoppers with similar habits
Semi-superviseda few labeled inputs, many unlabeledCan the unlabeled ones help?classifying web pages when only a few were labeled by hand
Self-supervisedinputs whose hidden parts serve as answersWhat is missing, or what comes next?predicting a masked word in a sentence
Reinforcementrewards for actions the learner choosesWhat should I do?learning a game from its score
The Descent lesson Supervised, Unsupervised & Beyond maps these settings in detail. Reinforcement learning gets a full topic of its own in the Artificial Intelligence course.

What learning cannot do

A model knows its training data and nothing else. Three consequences follow, and every practitioner learns them the hard way.

  1. It needs representative data. A model trained only on photos taken in daylight has never seen night, and its errors at night can be anything at all. When the data a model meets in use differ from its training data, that is distribution shift.
  2. It finds correlations, not causes. Ice-cream sales and drownings rise together, because summer drives both. A model can predict one from the other quite well, yet banning ice cream would save no swimmers.
  3. It optimizes what you measure. A recommender trained to maximize clicks learns whatever earns clicks, wanted or not. If the labels or the loss encode the wrong goal, a better optimizer only gets you there faster.
Check your understanding

A model trained on medical records finds that people who carry a lighter are more likely to develop lung cancer, and it uses that feature to predict cancer well. What should you conclude?

  1. Taking lighters away from people will reduce lung cancer
  2. The feature is meaningless and must be removed
  3. The model must be overfitting
  4. Carrying a lighter and lung cancer share a cause, smoking, so the feature can help prediction but says nothing about what to change
Show the answer

D. Carrying a lighter and lung cancer share a cause, smoking, so the feature can help prediction but says nothing about what to change

Smoking makes people more likely both to carry a lighter and to get lung cancer: it is a confounder. The correlation is real, so it can help predict for as long as it holds in the population where the model is used. It cannot tell you the effect of an intervention; that needs causal inference, covered in the topic Machine Learning in the Real World.

Your route from here

Every model in this course, from a fitted line to a deep network, is built from the pieces you have just used: features and labels, a family of candidate models, a loss, an optimizer, and an honest test on data the model has never seen. The Descent lessons of this topic make each piece precise.

Descent lessonWhat you will do there
The Learning ProblemState the setup exactly (an unknown data distribution, hypotheses, losses, risk and empirical risk minimization), derive the best possible predictor, and see why a model family that is too rich memorizes.
Data: Examples, Features & SplitsTurn raw records into feature vectors, split data into training, validation and test sets without fooling yourself, and work out how big a test set must be.
Supervised, Unsupervised & BeyondMap the learning settings, from labels to clusters to rewards, including semi-supervised, active and online learning.
The Math ToolkitCollect the vectors, matrices, derivatives and probability that the rest of the course runs on.

Key takeaways

  • Machine learning produces programs from examples: a learning algorithm turns data into a model, instead of a person writing the rules.
  • A program learns when its performance at a task, measured by a chosen yardstick, improves with experience: Mitchell's TT, PP and EE.
  • Nearly every method combines four ingredients: data (features, usually with labels), a model family, a loss and an optimizer.
  • The goal is generalization. Training error measures fit; error on a held-out test set measures what matters. Too simple underfits, too flexible overfits.
  • Learning settings differ in what the data provides: answers (supervised), structure only (unsupervised), answers hidden in the data (self-supervised) or rewards (reinforcement).
  • A model inherits the limits of its data and objective: it needs representative examples, and it learns correlations, not causes.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A navigation app predicts travel times, and its predictions improve as it records more completed trips. In Mitchell's terms, what is the performance measure PP?

  1. How close the predicted travel times are to the actual ones
  2. The recorded trips
  3. Predicting travel times
  4. The number of people using the app
Show the answer

A. How close the predicted travel times are to the actual ones

The task TT is predicting travel times, the experience EE is the recorded trips, and PP scores how well the task is done, for example the average error in minutes.

Question 2

Why judge a trained model on a test set it never saw, instead of on its training set?

  1. Training error is always exactly zero, so it carries no information
  2. Test examples are chosen to be harder than training examples
  3. The model was fitted to the training examples, so its error there is an optimistic guide to its error on new ones
  4. The test set is always larger than the training set
Show the answer

C. The model was fitted to the training examples, so its error there is an optimistic guide to its error on new ones

Training picks the model that does best on those very examples, so training error flatters it, sometimes hugely (the degree-12 curve had zero training error and a test error near 72). Examples the model never saw give an honest estimate of how it will do on new data.

Question 3

A model reaches 71% accuracy on its training set and 70% on its test set, while people get 95% on the same task. What is the most likely problem?

  1. Overfitting: it has memorized the training set
  2. Nothing: equal training and test accuracy means it works well
  3. The test set is too small
  4. Underfitting: the model family is too simple, or the features too weak, to capture the pattern
Show the answer

D. Underfitting: the model family is too simple, or the features too weak, to capture the pattern

Both scores are low and nearly equal, so the model is not even fitting the data it learned from. A richer family (a higher degree, a deeper tree, a smaller kk) or more informative features should help.

Question 4

A music service has the listening histories of millions of users, with no labels of any kind, and wants to discover groups of users with similar tastes. Which setting is this?

  1. Supervised classification
  2. Unsupervised learning
  3. Reinforcement learning
  4. Regression
Show the answer

B. Unsupervised learning

There are inputs but no answers to learn from: the groups are not defined in advance, so the learner has to find structure in the data itself. That is unsupervised learning; this particular task is called clustering.

Question 5

A model that sorts recycling from camera images was trained on photos taken under bright lights at one plant. Installed at a new plant with dim lighting, its accuracy drops sharply. What went wrong?

  1. The training data did not represent the conditions in which the model is used
  2. The model was underfitting its training data
  3. The training set was too large
  4. Image models cannot generalize
Show the answer

A. The training data did not represent the conditions in which the model is used

The model only ever saw brightly lit images, so dim images lie outside its experience: a distribution shift. Training on images from varied lighting, or from the new plant, is the fix.

Go deeper

Further reading

  • T. M. Mitchell, Machine Learning (McGraw-Hill, 1997), chapter 1.
  • G. James, D. Witten, T. Hastie & R. Tibshirani, An Introduction to Statistical Learning, 2nd ed. (Springer, 2021), chapters 1–2.