Velamuvi AIAcademy

Lesson 7 of 12 · Core Algorithms

Instance-Based Models

How instance-based models predict from similar stored examples: k-nearest neighbours by hand, distance measures, choosing k, scaling and too many features.

  • 15 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain how instance-based (lazy) learning differs from learning a formula
  • Classify a new example with k-nearest neighbours, by hand and with scikit-learn
  • Measure similarity with Euclidean and Manhattan distance
  • Choose k with cross-validation, and explain why scaling matters so much
  • Recognise the costs: slow predictions and the curse of dimensionality

The idea in plain words

Linear models learn weights and trees learn questions. Instance-based models learn almost nothing in advance. They keep the training examples, and when a new example arrives they look up the most similar stored examples and base the prediction on their labels, much as an experienced doctor recalls similar past patients.

The best-known instance-based model is k-nearest neighbours (k-NN): find the k stored examples closest to the new one, then let them vote on the class (classification) or average their labels (regression). You used KNeighborsClassifier briefly in Introduction to Machine Learning; this lesson covers the details that make k-NN work well or fail.

k-NN by hand

A clothing shop knows the height, weight and chosen T-shirt size of ten customers. Which size should it suggest to a new customer who is 171 cm tall and weighs 70 kg?

Try it yourselfPython
import numpy as np
from sklearn.neighbors import KNeighborsClassifier

# Stored examples: [height in cm, weight in kg] and the T-shirt size each person chose
X = np.array([[158, 52], [160, 58], [163, 55], [168, 64], [170, 68],
              [172, 63], [178, 80], [180, 77], [183, 85], [175, 74]])
sizes = np.array(["S", "S", "S", "M", "M", "M", "L", "L", "L", "L"])

new_person = np.array([171, 70])
distances = np.sqrt(((X - new_person) ** 2).sum(axis=1))    # straight-line distance
nearest = np.argsort(distances)[:3]                         # positions of the 3 closest
for i in nearest:
    print(f"{X[i]} size {sizes[i]}  distance {distances[i]:.1f}")

labels, counts = np.unique(sizes[nearest], return_counts=True)
print("By hand, the vote says:", labels[counts.argmax()])

model = KNeighborsClassifier(n_neighbors=3).fit(X, sizes)
print("KNeighborsClassifier says:", model.predict([new_person])[0])
Output
[170  68] size M  distance 2.2
[175  74] size L  distance 5.7
[168  64] size M  distance 6.7
By hand, the vote says: M
KNeighborsClassifier says: M

The three most similar customers chose M, L and M, so the vote says M, and scikit-learn agrees. Notice that fit learned no weights or rules: it simply stored the ten examples. All the work (computing ten distances, sorting them, voting) happened when we asked for a prediction.

Measuring distance

"Most similar" means "closest", so the choice of distance matters. The two most common:

Euclidean distance (a straight line):   √((a₁ − b₁)² + (a₂ − b₂)² + …)
Manhattan distance (city blocks):       |a₁ − b₁| + |a₂ − b₂| + …
Try it yourselfPython
import numpy as np

a = np.array([171, 70])      # height, weight
b = np.array([175, 74])

euclidean = np.sqrt(np.sum((a - b) ** 2))      # straight line
manhattan = np.sum(np.abs(a - b))              # along the grid, like city blocks
print(f"Euclidean distance: {euclidean:.2f}")
print(f"Manhattan distance: {manhattan:.2f}")
Output
Euclidean distance: 5.66
Manhattan distance: 8.00

Euclidean distance is the straight line between the two points, and it's what scikit-learn uses by default. Manhattan distance adds up the differences along each feature, like walking city blocks; because it doesn't square the differences, one large difference dominates it less. Choose it with KNeighborsClassifier(metric="manhattan"). For text and other embeddings, cosine distance, which compares the directions of two vectors, is the usual choice.

Choosing k

k is k-NN's main hyperparameter. The program below tries six values on a noisy two-class dataset, using cross-validation as in Generalisation:

Try it yourselfPython
from sklearn.datasets import make_moons
from sklearn.model_selection import cross_validate
from sklearn.neighbors import KNeighborsClassifier

X, y = make_moons(n_samples=400, noise=0.35, random_state=0)

print("  k   train  validation")
for k in [1, 5, 15, 51, 151, 251]:
    scores = cross_validate(KNeighborsClassifier(n_neighbors=k), X, y, cv=5,
                            return_train_score=True)
    print(f"{k:>3}   {scores['train_score'].mean():.2f}   {scores['test_score'].mean():.2f}")
Output
  k   train  validation
  1   1.00   0.83
  5   0.90   0.87
 15   0.89   0.88
 51   0.89   0.89
151   0.83   0.82
251   0.76   0.76
  • k = 1 overfits. Each training example is its own nearest neighbour, so the training score is a perfect 1.00, but every noisy label gets copied to its surroundings: validation is 0.83.
  • k = 51 does best here (0.89): enough neighbours to outvote the noise.
  • k = 251 underfits. Each training fold holds only 320 examples, so every prediction is a vote of most of the dataset, and the model can no longer follow the shape of the classes (0.76).

So k is a complexity dial running the opposite way to tree depth: small k is flexible, large k is simple. Two practical tips: for two classes, an odd k avoids tied votes, and weights="distance" lets closer neighbours count for more.

Why scaling matters

Distances add up differences across features, so a feature with large numbers drowns out the others. The wine dataset has 13 chemical measurements of 178 wines from three growers:

Try it yourselfPython
from sklearn.datasets import load_wine
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_wine(return_X_y=True)
print("Feature ranges, smallest and largest:")
print("  alcohol:", X[:, 0].min(), "to", X[:, 0].max())
print("  proline:", X[:, 12].min(), "to", X[:, 12].max())

raw = cross_val_score(KNeighborsClassifier(n_neighbors=5), X, y, cv=5).mean()
scaled = cross_val_score(make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=5)),
                         X, y, cv=5).mean()
print(f"k-NN on raw features:    accuracy {raw:.2f}")
print(f"k-NN on scaled features: accuracy {scaled:.2f}")
Output
Feature ranges, smallest and largest:
  alcohol: 11.03 to 14.83
  proline: 278.0 to 1680.0
k-NN on raw features:    accuracy 0.69
k-NN on scaled features: accuracy 0.95

Alcohol varies by less than 4 units across all the wines, while proline varies by over 1,400. On raw features, "nearest" means little more than "most similar proline", and accuracy is 0.69. After StandardScaler gives every feature the same spread, all 13 measurements count, and accuracy jumps to 0.95. For k-NN, scaling isn't optional. Put the scaler in a pipeline, so it learns its averages from the training folds only.

The curse of dimensionality

More features can make k-NN worse. The program below takes the breast tumour data (30 real measurements) and adds columns of pure random noise, as happens when you throw every available column at a model:

Try it yourselfPython
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_breast_cancer(return_X_y=True)
rng = np.random.RandomState(0)
model = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=5))

for extra in [0, 10, 50, 200]:
    noise = rng.normal(size=(len(X), extra))          # columns of pure noise
    X_more = np.hstack([X, noise])
    acc = cross_val_score(model, X_more, y, cv=5).mean()
    print(f"30 real features + {extra:>3} noise features: accuracy {acc:.2f}")
Output
30 real features +   0 noise features: accuracy 0.96
30 real features +  10 noise features: accuracy 0.95
30 real features +  50 noise features: accuracy 0.94
30 real features + 200 noise features: accuracy 0.89

Every irrelevant feature adds a random amount to every distance, so the truly similar examples stop being the nearest ones. With 200 noise columns, accuracy falls from 0.96 to 0.89. In very many dimensions, points also tend to end up roughly equally far from each other, which makes "nearest" almost meaningless.

The cures are to keep only relevant features, to reduce the number of dimensions (for example with principal component analysis, covered in Unsupervised Learning), or to compare learned representations such as embeddings instead of raw features.

k-NN for numbers

For regression, k-NN averages the labels of the neighbours:

Try it yourselfPython
import numpy as np
from sklearn.neighbors import KNeighborsRegressor

sizes = np.array([[50], [60], [65], [80], [90], [100], [120], [140]])   # m²
prices = np.array([150, 170, 185, 230, 250, 270, 330, 390])            # thousands

model = KNeighborsRegressor(n_neighbors=3).fit(sizes, prices)
print("Prediction for 85 m²:", model.predict([[85]])[0])
print("Its 3 neighbours' prices:", prices[model.kneighbors([[85]])[1][0]])
print("Prediction for 300 m²:", model.predict([[300]])[0])
Output
Prediction for 85 m²: 250.0
Its 3 neighbours' prices: [250 230 270]
Prediction for 300 m²: 330.0

An 85 m² home gets 250 thousand, the average of its three neighbours. A 300 m² home, far bigger than anything stored, gets 330 thousand, the average of the three largest homes: like trees, k-NN can't predict beyond the range of its training labels.

The cost of being lazy

StrengthsWeaknesses
Simple to understand and explain: "these similar customers chose M"Every prediction compares against the stored examples, so it gets slow with millions of rows
No training time, and new examples can be added without retrainingStores the whole training set in memory
Learns curved boundaries of any shapeNeeds scaled, relevant features; suffers from the curse of dimensionality
Works for classification and regressionCan't extrapolate beyond the training data

scikit-learn speeds up the neighbour search with clever data structures (k-d trees and ball trees, chosen automatically). Other members of the instance-based family include RadiusNeighborsClassifier, which uses every neighbour within a fixed distance, and kernel methods such as support vector machines, which keep a selected set of training examples and compare new examples against them.

Common mistakes

Practice

Practice exercise

Classify a new applicant with 3-nearest neighbours, by hand.

Your solutionPython
import math

# [maths score, English score] of past applicants, and the decision for each
points = [(85, 80), (78, 72), (90, 88), (60, 55), (65, 70), (55, 62), (72, 64), (68, 58)]
labels = ["admit", "admit", "admit", "reject", "reject", "reject", "admit", "reject"]
new_applicant = (70, 65)

# 1. Compute the distance from new_applicant to every point (math.dist does it).
# 2. Take the labels of the 3 nearest points, nearest first.
# 3. Predict the label that appears most often among those 3.
# Print like: Nearest labels: ['admit', 'admit', 'reject'] -> admit
nearest_labels = []
prediction = None

print(f"Nearest labels: {nearest_labels} -> {prediction}")
Knowledge check

What does a k-nearest neighbours model do when you call fit?

Summary

  • Instance-based models store the training examples and predict from the most similar ones; k-NN votes (classification) or averages (regression) over the k nearest.
  • Similarity is a distance: Euclidean by default, Manhattan or cosine when they suit the data better.
  • k is a complexity dial: k = 1 memorises noise, a very large k blurs everything. Choose it with cross-validation.
  • Scale your features and keep them relevant: unscaled or irrelevant features (the curse of dimensionality) wreck distances.
  • k-NN trains instantly but predicts slowly on big data, and can't extrapolate; nearest-neighbour search powers recommendations and semantic search.

Next: Probabilistic Models, which predict by reasoning with probabilities.

Finished reading? Tick it off to track your progress.