Sub topic 10
The curse of dimensionality
This chapter assumes you know how k-NN classifies with Euclidean distance, why features need scaling, and how to use NumPy and scikit-learn. It explains why neighbour quality drops as the number of features grows.
Why more features can hurt
k-NN relies on one idea: nearby points have similar labels. That idea needs "nearby" to mean something. In high dimensions it stops meaning much.
The curse of dimensionality is the set of effects that appear when the number of features d grows while the number of training points n stays fixed. Three effects matter for k-NN:
- Data becomes sparse. To cover a unit interval with 10 points per axis you need 10 points. To cover a unit cube in
ddimensions at the same density you need 10^d points. Real datasets never grow that fast. - Distances concentrate. The nearest and farthest points end up at almost the same distance from a query.
- Neighbours are not local. To capture a fixed fraction of the data, a neighbourhood must span most of the range of every feature.
Distance concentration
Take points drawn uniformly from the unit cube. As d grows, the distance to the nearest point approaches the distance to the farthest one. The ratio of the two moves toward 1.
The next script measures this. It draws 500 random points per dimension, picks one as the query, and compares its nearest and farthest distances to the rest.
import numpy as np
rng = np.random.default_rng(0)
n = 500
for d in [1, 2, 10, 100, 1000]:
X = rng.random((n, d))
query, rest = X[0], X[1:]
dists = np.linalg.norm(rest - query, axis=1)
print(f"d={d:5d} nearest/farthest = {dists.min() / dists.max():.3f}")For d=1 the ratio is close to 0, so the nearest point is far closer than the farthest. By d=1000 the ratio is much closer to 1 (roughly 0.7 to 0.8). The nearest neighbour is then barely nearer than a random point, so "the k nearest" carries little information.
Irrelevant features add noise
Concentration is worst when many features carry no signal. Each useless feature adds random variation to every distance. With 2 informative features and 50 noise features, the noise dominates the sum of squared differences, and the informative part is buried.
The experiment below adds noise columns to the wine dataset and tracks test accuracy. It scales inside a pipeline, as in earlier chapters.
import numpy as np
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_wine(return_X_y=True)
rng = np.random.default_rng(0)
for n_noise in [0, 10, 50, 200]:
noise = rng.normal(size=(X.shape[0], n_noise))
X_aug = np.hstack([X, noise])
X_tr, X_te, y_tr, y_te = train_test_split(
X_aug, y, test_size=0.25, stratify=y, random_state=0
)
model = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=5))
model.fit(X_tr, y_tr)
print(f"noise features={n_noise:4d} accuracy={model.score(X_te, y_te):.3f}")Accuracy falls as noise columns are added. Exact numbers depend on the split and the random noise, but the downward trend is the point.
What to do about it
| Remedy | Idea | Cost |
|---|---|---|
| Feature selection | Drop features with little relation to the label | Needs a reliable selection method |
| Dimensionality reduction (for example PCA) | Project onto fewer directions that keep most variance | Components are harder to interpret |
| More data | Fill the space more densely | Needed amounts grow exponentially with `d` |
| Different metric | Cosine distance suits sparse, high-dimensional vectors such as text | Must match the data |
| Distance-weighted voting | Lets very close points count more | Helps only if close points exist |
A rule of thumb
Intrinsic dimension matters more than the number of columns. Image pixels are many columns, but the data may lie near a low-dimensional surface, so k-NN can still work. Ten independent noise columns are truly ten dimensions. Check performance with cross-validation as you add or remove features, not by counting columns.
Exercise
A dataset has 5 informative features and 95 pure-noise features. A k-NN classifier scores poorly. Name two changes that could improve it, and say why rescaling alone will not.
Show answer
Remove the noise features with feature selection, or reduce the dimension with PCA (collecting more data also helps). Rescaling gives all features equal weight, so the 95 noise features still contribute as much to each distance as the 5 informative ones.
Exercise
In the nearest/farthest experiment, what does a ratio near 1 tell you about a query point's k nearest neighbours?
Show answer
The neighbours are almost as far away as any other point, so they are not meaningfully more similar to the query than random points. A majority vote among them carries little information.