Sub topic 1
Learning by Remembering: Instance-Based Methods
Prerequisites
We assume you know features, labels, training and test sets, vectors, Euclidean distance, Python, and NumPy.
Learning by Remembering
Instance-based learning stores training examples instead of fitting a fixed equation during training. A prediction happens later, when the algorithm compares a new example with stored examples. This is why k-nearest neighbours (k-NN) is called a lazy learner: most computation happens at prediction time.
For classification, each stored example has a class label. The algorithm finds the most similar examples and uses their labels to vote. For regression, it combines their numeric target values.
Measuring Similarity with Distance
A distance metric measures how far two feature vectors are from each other.
| Metric | Formula for vectors \(x\) and \(y\) | Typical use | Column | Column |
|---|---|---|---|---|
| Euclidean | \(\sqrt{\sum_i(x_i-y_i)^2}\) | Straight-line distance | ||
| Manhattan | \(\sum_i | x_i-y_i | \) | Grid-like movement |
| Minkowski | \((\sum_i | x_i-y_i | ^p)^{1/p}\) | General distance family |
For example, the Euclidean distance between (1, 2) and (4, 6) is 5. The Manhattan distance is 7. The chosen metric defines what “similar” means.
Classifying with the k Nearest Neighbours
Given a query point, k-NN computes its distance to every training point, selects the k smallest distances, and returns the majority label.
import numpy as np
from collections import Counter
def knn_predict(X_train, y_train, x, k=3):
distances = np.linalg.norm(X_train - x, axis=1)
nearest = np.argsort(distances)[:k]
return Counter(y_train[nearest]).most_common(1)[0][0]
X = np.array([[1, 1], [1.2, 0.8], [4, 4.2], [3.8, 4]])
y = np.array([0, 0, 1, 1])
print(knn_predict(X, y, np.array([1.1, 0.9]), k=3)) # 0How k Shapes the Decision Boundary
A decision boundary separates regions assigned to different classes. With k=1, the boundary can bend around individual training points. This gives low training error but high variance: a noisy point can change the prediction.
Larger values of k smooth the boundary. They reduce variance but may ignore small, real patterns, causing higher bias. Select k with validation rather than relying on training accuracy.
Exercise
Why can k=1 be sensitive to noise?
Show answer
It copies the label of one point, so a mislabeled or unusual neighbour can determine the prediction.