TExcelTAD

What Is Machine Learning?

In the last lesson a person wrote every rule the program followed. That works when the rule is known. Machine learning is for the many problems where we have plenty of examples of the right behaviour but cannot write the rule down.

A definition

Machine learning (ML) is the part of AI that builds programs which improve at a task by learning from data, instead of being explicitly programmed for it.

A classic, more precise formulation (Tom Mitchell, 1997) says a program learns from experience EE with respect to a task TT and a performance measure PP if its performance at TT, measured by PP, improves with experience EE. The three letters are a good checklist for any ML problem:

Question Spam filter House prices
Task What should the program do? decide spam or not for each email estimate the sale price of a house
Performance How do we measure success? share of emails classified correctly, missed spam average error in dollars
Experience What data does it learn from? emails labelled spam / not spam by users past sales with their prices

If you cannot fill in all three rows, the problem is not ready for machine learning yet.

Learning a rule, from scratch

Here is learning in its simplest form. We have 40 learner drivers, the hours each practised, and whether each passed the test. We suspect a rule of the form "pass if hours ≥t\ge t" and let the computer choose the threshold tt that agrees with the most examples.

python · try it yourself
import numpy as np

# Experience E: hours of practice before a driving test, and whether the learner passed (1) or not (0).
rng = np.random.default_rng(1)
hours = rng.uniform(0, 30, size=40).round(1)
passed = (hours + rng.normal(0, 4, size=40) > 14).astype(int)   # the hidden pattern, with noise

def accuracy(threshold, x, y):
    return np.mean((x >= threshold).astype(int) == y)

# Learning = searching for the rule "pass if hours >= t" that fits the examples best.
candidates = np.arange(0, 30.5, 0.5)
scores = [accuracy(t, hours, passed) for t in candidates]
best = candidates[int(np.argmax(scores))]
print("learned threshold t =", best, "hours")
print("training accuracy:", round(max(scores), 3))

# Performance P is measured on new learners the rule has never seen.
new_hours = rng.uniform(0, 30, size=200).round(1)
new_passed = (new_hours + rng.normal(0, 4, size=200) > 14).astype(int)
print("accuracy on 200 new learners:", round(accuracy(best, new_hours, new_passed), 3))
learned threshold t = 13.0 hours
training accuracy: 0.95
accuracy on 200 new learners: 0.89

Three ideas from this tiny program run through the whole field:

  1. A model family. We decided in advance that the rule is a threshold. Learning only chose its value. Every ML method fixes a family of possible rules (lines, trees, neural networks) and searches inside it.
  2. Fitting to examples. The search picked the threshold, 13.0 hours, that made the fewest mistakes on the training examples (95 % right).
  3. Generalisation. What matters is how the rule does on new cases. It scored 0.89 on 200 new learners, lower than on its own training data. A model's score on the data it learned from is almost always too optimistic.

A lab: watching a model learn a boundary

With two input features instead of one, the learned rule becomes a decision boundary: a line or curve that splits the plane into the regions where the model predicts each class. The lab below shows 80 training points of two classes (blue circles and orange squares) and the regions a classifier learned from them. Its two bars compare accuracy on the 80 training points with accuracy on 200 new points from the same source.

−2−1012−2−1012feature x₁feature x₂kNN on moonsk = 1class Aclass Bdecision boundaryTraining accuracy80/80100.0 %Test accuracy183/20091.5 %Test set: 200 new points

It starts with a k-nearest-neighbour classifier with k=1k = 1: each point of the plane gets the class of the single closest training example. On the noisy "moons" data it gets every training point right (80/80) but only 183 of the 200 new points (91.5 %): the boundary twists around individual noisy points, and those twists do not carry over to new data. Now drag kk to 15, so that each prediction is a vote of the 15 nearest examples. The boundary becomes smooth, the training accuracy drops to 92.5 %, and the test accuracy rises to 94.5 %. Fitting the training data perfectly is not the goal; predicting new data well is. Try the other classifiers too: logistic regression can only draw a straight line, which is why it reaches just 85.5 % on the curved moons.

More experience, better performance

Mitchell's definition says performance should improve with experience. We can check that directly: train the same model on more and more examples and score it on one fixed test set of 1000 examples.

python · try it yourself
from sklearn.datasets import make_classification
from sklearn.neighbors import KNeighborsClassifier

# One fixed test set of 1000 examples; the training set grows. More experience E, better performance P?
X, y = make_classification(n_samples=3000, n_features=8, n_informative=6, n_redundant=0,
                           class_sep=1.2, random_state=2)
X_test, y_test = X[2000:], y[2000:]
for n in [10, 30, 100, 300, 1000, 2000]:
    model = KNeighborsClassifier(n_neighbors=5).fit(X[:n], y[:n])
    print(f"{n:>5} training examples -> test accuracy {model.score(X_test, y_test):.3f}")
   10 training examples -> test accuracy 0.501
   30 training examples -> test accuracy 0.758
  100 training examples -> test accuracy 0.828
  300 training examples -> test accuracy 0.888
 1000 training examples -> test accuracy 0.908
 2000 training examples -> test accuracy 0.920

With 10 examples the model is no better than a coin flip (0.501); with 2000 it is right 92 % of the time. The gains shrink as data grows: going from 1000 to 2000 examples adds only 1.2 points. This shape, a fast rise and then a slow climb, is called a learning curve, and you will use it to decide whether more data is worth collecting.

Pitfalls

  • Judging a model by its training score. The training score measures memory, not skill. Always hold back data the model never sees during training.
  • No clear performance measure. "Make it smart" is not a task. Decide PP before building anything: accuracy, error in dollars, missed fraud cases.
  • Expecting the model to find what the data does not contain. If the hours of practice did not relate to passing at all, no threshold would help. ML finds patterns; it cannot create them.

Practice

  1. Fill in TT, PP and EE for a system that recommends films on a streaming service.
Answer

TT: rank films for each user so that they pick one they enjoy. PP: for example the share of recommended films that users start and finish, or ratings given afterwards. EE: the history of what users watched, finished, rated or skipped.

  1. In the driving-test example, the training accuracy is 0.95 and the accuracy on new learners 0.89. Give two reasons why the second number is lower.
Answer

The threshold was chosen to fit the 40 training examples, including their random noise, so it is slightly tuned to them. Also, the outcome itself is noisy (the hidden rule adds random variation), so even the best possible threshold cannot be right for every learner; 40 examples happened to be easier than the 200 new ones.

  1. In the lab, set the noise back to 1, choose the "circles" data set and the logistic classifier. Why is the test accuracy close to 50 %?
Answer

One class forms a ring around the other. Logistic regression can only draw a straight boundary, and no straight line separates a ring from its centre, so it does little better than guessing (55.0 % in the lab). A kNN model, which can draw curved boundaries, scores 96.0 % with k=5k = 5.

Test yourself

In Mitchell's definition, what is EE for a spam filter?

  1. The share of emails classified correctly
  2. Emails labelled spam or not spam
  3. Deciding whether an email is spam
  4. The number of parameters

A kNN model with k=1k = 1 scores 80/80 on its training points and 91.5 % on new points. What does the gap show?

  1. The model generalises perfectly
  2. The model fitted noise in the training data that does not carry over to new data
  3. The test set is wrong
  4. kNN cannot classify moons

Going from 1000 to 2000 training examples raised test accuracy from 0.908 to 0.920. What does this suggest?

  1. More data always doubles accuracy
  2. The learning curve is flattening; more data still helps, but less each time
  3. The model got worse
  4. The test set is too small

Why did the driving-test program search only thresholds of the form "pass if hours ≥t\ge t"?

  1. Because every ML model is a threshold
  2. Because a model family must be chosen in advance; learning picks the best member of it
  3. Because numpy cannot do anything else
  4. Because the data had only one row