Sub topic 1
Learning by remembering: instance-based methods
Prerequisites
This chapter assumes you know the basics of supervised learning: features, labels, and the split between training and test sets. You should be able to read short Python and NumPy code. You should also know that Euclidean distance is the straight-line distance between two points represented as vectors.
What instance-based learning means
Most models you meet first, such as linear regression or logistic regression, learn a small set of parameters from the training data. After training, they can discard the data. Predictions use only the parameters.
An instance-based method works differently. It stores the training examples (the instances) and does the work when a prediction is requested. To predict for a new point, it looks up the stored examples most similar to that point and uses their labels or values.
This is also called lazy learning. The "lazy" part refers to the fact that there is no fitting step that produces parameters. The model postpones its computation until it sees a query.
k-nearest neighbours (k-NN) is the standard example. The "k" is a number you choose. To predict for a new point, k-NN finds the k training points closest to it and combines their labels.
Eager and lazy learners compared
| Property | Eager learner (e.g. logistic regression) | Lazy learner (k-NN) |
|---|---|---|
| What training does | Fits parameters | Stores the data |
| What is kept | Parameters only | The whole training set |
| Cost of a prediction | Usually low | Distances to many stored points |
| Shape of the model | Fixed by the model family | Follows the data locally |
The trade-off is clear. A lazy learner makes few assumptions about the shape of the relationship between features and labels, so it can follow complicated patterns. In return, it uses more memory and takes longer per prediction.
The idea in one picture
The flow below shows what happens at prediction time.
Notice that the stored training set is used at prediction time, not only during training. Everything after the query arrives is the model.
A first look in code
The code below shows the core of the idea. There is no training step. The function receives the stored data on every call, finds the closest point, and copies its label. This is the special case k = 1.
import numpy as np
X_train = np.array([[1.0, 1.0], [1.2, 0.8], [4.0, 4.2], [3.8, 4.0]])
y_train = np.array([0, 0, 1, 1])
def nearest_label(x):
dists = np.linalg.norm(X_train - x, axis=1)
return y_train[np.argmin(dists)]
print(nearest_label(np.array([1.1, 0.9]))) # 0
print(nearest_label(np.array([3.9, 4.1]))) # 1np.linalg.norm(X_train - x, axis=1) computes the Euclidean distance from x to each row of X_train. np.argmin returns the position of the smallest distance. The label stored at that position is the prediction.
What the approach assumes
Instance-based learning rests on one assumption: points that are close together in feature space tend to have similar labels. If this holds, copying the labels of nearby examples is a sensible strategy. If it fails, the method has nothing to fall back on.
This makes two things matter a great deal:
- The notion of "close". The distance measure decides which points count as similar. The next chapter covers distance metrics.
- The features themselves. Irrelevant or badly scaled features distort distances, and k-NN has no parameters that could learn to ignore them.
Common errors
- Thinking k-NN has no hyperparameters. There is no fitting step, but you still choose k, the distance metric, and the voting rule. These settings decide the quality of the predictions.
- Expecting cheap predictions. A naive prediction compares the query to every stored point. With many training points, this becomes slow, and later chapters cover faster search.
- Discarding the training data. With k-NN, the data is the model. If you delete it, you cannot predict.
Exercise
A logistic regression model and a k-NN classifier are both trained on the same 100,000 examples. Which one needs the training data at prediction time, and why?
Show answer
The k-NN classifier does. It has no fitted parameters, so to predict it must compare the query to the stored training points and combine the labels of the closest ones. Logistic regression has already compressed what it learned into its coefficients, so it can predict without the training data.
Exercise
In the code above, what would change if you replaced np.argmin(dists) with the indices of the three smallest distances?
Show answer
The function would use three neighbours instead of one (k = 3). You would then need a rule to combine their three labels, such as a majority vote.