Sub topic 1
Learning by remembering: instance-based methods
Prerequisites
This chapter assumes you know the following:
- Basic supervised learning: features, labels, and the split into training and test sets.
- Vectors and Euclidean distance between two points.
- Basic Python and NumPy, including array indexing and broadcasting.
- How to split data with
train_test_split.
You do not need to know k-NN yet. This chapter introduces the idea behind it and builds a first working classifier. Later chapters cover distance metrics, choosing k, scaling, and speed.
Two ways to learn from data
Most models you have met so far work in two phases. In the training phase, an algorithm searches for parameters that fit the training data. Linear regression finds coefficients. A neural network finds weights. In the prediction phase, the model applies those parameters to a new input and throws the training data away.
Instance-based learning takes a different route. It keeps the training examples themselves, and it makes a prediction by comparing the new input to the stored examples. An instance is one stored training example: a feature vector and its label.
The k-nearest neighbours algorithm (k-NN) is the standard instance-based method. To predict for a new point, it does three things:
- Measure the distance from the new point to every stored training point.
- Select the k training points with the smallest distances. These are the neighbours.
- Combine the neighbours' labels into one prediction.
The idea rests on an assumption: points that are close in feature space tend to have similar labels. If that assumption holds for your data, remembering the examples is enough. If it fails, no amount of remembering helps.
Lazy versus eager learning
Instance-based methods are called lazy learners, because they delay work until a query arrives. Methods that build a model up front are called eager learners.
| Property | Eager learner (for example, logistic regression) | Lazy learner (k-NN) |
|---|---|---|
| Work at training time | Fits parameters, which can be expensive | Almost none: stores the data |
| Work at prediction time | Cheap: apply the fitted parameters | Expensive: compare to stored points |
| What is kept after training | A compact set of parameters | The whole training set |
| Shape of the model | Fixed by the model family | Adapts to the local data |
| Memory use | Independent of training set size | Grows with training set size |
A phrase you will see often is that k-NN has "no training phase". That is a slight simplification. The fit method in scikit-learn still runs. It validates the input, stores the data, and optionally builds a search structure such as a tree. But it does not optimise any parameters, and there is no loss function to minimise.
A first look at the idea
The diagram below shows the flow of a k-NN prediction. Notice that the stored data is read on every query, not just once.
Here is a tiny example. Imagine two groups of points in two dimensions. Group 0 sits near (1, 1). Group 1 sits near (4, 4). A new point at (1.1, 0.9) is very close to group 0. Its three nearest neighbours will be two or more points from group 0, so the vote returns label 0.
Implementing k-NN from scratch
The following code implements the whole algorithm in a few lines of NumPy.
import numpy as np
from collections import Counter
def knn_predict(X_train, y_train, x, k=3):
# Euclidean distance from x to every training point
dists = np.linalg.norm(X_train - x, axis=1)
# Indices of the k smallest distances
nearest = np.argsort(dists)[:k]
# Majority vote among the neighbours' labels
return Counter(y_train[nearest]).most_common(1)[0][0]
X_train = np.array([[1.0, 1.0], [1.2, 0.8], [4.0, 4.2], [3.8, 4.0], [4.1, 3.9]])
y_train = np.array([0, 0, 1, 1, 1])
print(knn_predict(X_train, y_train, np.array([1.1, 0.9]), k=3)) # 0Walk through the function line by line.
X_train - xsubtracts the query from every row. NumPy broadcasting stretches the one-rowxacross all rows ofX_train.np.linalg.norm(..., axis=1)computes the length of each difference vector. That length is the Euclidean distance.axis=1means one distance per row.np.argsort(dists)[:k]returns the positions of the k smallest distances, not the distances themselves. You need positions because you use them to look up labels.y_train[nearest]fetches the labels of those neighbours.Counter(...).most_common(1)finds the most frequent label.
In this example, the three nearest points to (1.1, 0.9) are the two group 0 points and the closest group 1 point. The vote is two to one for label 0, so the function prints 0.
There is no loop over training steps and no parameter update. All the work happens inside the call. If you called knn_predict ten thousand times, it would re-measure every distance each time.
The same idea in scikit-learn
scikit-learn wraps this idea in KNeighborsClassifier. The fit and predict methods follow the usual estimator interface.
from sklearn.neighbors import KNeighborsClassifier
X_train = [[1.0, 1.0], [1.2, 0.8], [4.0, 4.2], [3.8, 4.0], [4.1, 3.9]]
y_train = [0, 0, 1, 1, 1]
model = KNeighborsClassifier(n_neighbors=3)
model.fit(X_train, y_train)
print(model.predict([[1.1, 0.9]])) # [0]
print(model.predict_proba([[1.1, 0.9]])) # [[0.66666667 0.33333333]]The predict_proba output shows the vote shares. Two of three neighbours vote for class 0, so its probability is 2/3. These are fractions of neighbours, not calibrated probabilities. With a small k, they take only a few distinct values.
What "the model" is in an instance-based method
In an eager learner, you can inspect the fitted parameters. In k-NN, the model is the training set plus three choices:
- The value of k.
- The distance function, which defines what "close" means.
- The combination rule, such as majority vote, weighted vote, or average.
This has a practical consequence. Changing any of these three choices changes the predictions without any retraining. It also means that the quality of the model depends heavily on the distance function. If the distance does not reflect real similarity for your problem, the neighbours are the wrong points. Later chapters cover this in detail, including feature scaling and the curse of dimensionality.
Strengths and costs
Instance-based learning has real advantages.
- Simple and transparent. You can explain a prediction by showing the neighbours that produced it.
- Flexible. The decision boundary can take almost any shape, because it is built from local data and not from a fixed formula.
- Easy to update. Adding a new training example means appending it to the stored data. There is nothing to refit. (If you built a tree for fast search, you may need to rebuild it.)
- Works for several tasks. The same neighbour lookup supports classification, regression, and plain similarity search.
It also has costs that matter in practice.
- Slow predictions. A brute-force query computes n distances for n stored points, each over d features, so the cost is roughly O(n·d) per query. Eager models usually predict in time independent of n.
- Large memory use. The whole training set must stay available at prediction time.
- Sensitivity to the distance. Irrelevant features and mismatched feature scales distort distances.
- Poor behaviour in high dimensions. Distances become less informative as the number of features grows.
Where lazy learning is a good fit
k-NN is a reasonable first choice when the following conditions hold:
- The dataset is small or medium in size, so that prediction time is acceptable.
- The number of meaningful features is modest.
- Similar inputs really do have similar outputs.
- You want a baseline that needs almost no tuning and is easy to explain.
It is a poor fit when you must answer millions of queries per second over millions of points, unless you use the fast search methods covered near the end of this tutorial. It is also a poor fit when the features are many and mostly noise.
Common mistakes at this stage
- Expecting
fitto learn something. Timingfiton k-NN and comparing it with a random forest is misleading. The cost is moved topredict. - Including the query in the training set. If you evaluate on points that are also stored, each point is its own nearest neighbour at distance zero. With k = 1, the training accuracy is then perfect and meaningless. Always evaluate on held-out data.
- Using an even k for two classes. With k = 4 and two classes, a 2–2 tie is possible. Ties are covered in a later chapter. For now, prefer odd values of k in binary problems.
- Forgetting that labels must be aligned with rows. If you shuffle
X_trainbut noty_train, the neighbours' labels are wrong, and the code still runs without any error.
Exercises
Exercise
A colleague says "k-NN has no training phase, so fit does nothing." Give two things that fit can still do in scikit-learn, and say where the main computational cost of k-NN appears.
Show answer
fit validates and stores the training data, and it can build a search structure such as a KD-tree or ball tree. It does not optimise parameters. The main cost appears at prediction time, when each query is compared with the stored points.
Exercise
In the from-scratch function, the line nearest = np.argsort(dists)[:k] returns positions and not distances. Why is that what the next line needs?
Show answer
The next line uses y_train[nearest] to look up the labels of the neighbours. Indexing y_train requires the positions of the chosen training points, which argsort provides. The distances alone would not say which labels to fetch.
Exercise
You train a 1-NN classifier and score it on the same data you stored. The accuracy is 100%. Why is this result not evidence that the model is good?
Show answer
Each stored point is its own nearest neighbour at distance zero, so it always receives its own label. The score does not measure how the model handles unseen points. You need to score on held-out test data.