Sub topic 10
The curse of dimensionality
This chapter assumes you know how k-NN classifies by majority vote, how Euclidean and Minkowski distances work, and why feature scaling matters. It also assumes you can run NumPy and scikit-learn code. Here you will see why k-NN gets worse as the number of features grows, and what you can do about it.
Why dimensions matter for k-NN
k-NN rests on one assumption: points that are close in feature space have similar labels. That assumption needs "close" to be meaningful. A point's nearest neighbours should be much nearer than the typical point. In a few dimensions this holds. In hundreds of dimensions it often does not.
The curse of dimensionality is the name for a set of effects that appear as the number of features d grows:
- Data becomes sparse, because the space grows exponentially faster than your sample.
- Distances between points become nearly equal.
- Neighbourhoods stop being local.
- Irrelevant features add noise to every distance.
These effects hit k-NN harder than most models. k-NN has no learned parameters that could downweight useless features. It trusts the distance function completely.
Effect 1: space grows faster than data
Suppose each feature is scaled to [0, 1] and you want about 10 training points per axis-aligned cell of width 0.1.
- In 1 dimension you need 10 cells, so about 100 points.
- In 2 dimensions you need 100 cells.
- In d dimensions you need 10^d cells.
With 10 features that is ten billion cells. Your dataset of 10,000 rows covers a tiny fraction of them, so most of the space has no training points nearby.
Neighbourhoods stop being local
A second way to see this: how long must a cube's edge be to capture a fraction p of uniformly distributed data? In d dimensions the edge length is p^(1/d). The table uses p = 0.01, which is 1% of the data.
| Dimensions d | Edge length needed for 1% of data |
|---|---|
| 1 | 0.01 |
| 2 | 0.10 |
| 3 | 0.22 |
| 10 | 0.63 |
| 100 | 0.95 |
In 100 dimensions, a "local" neighbourhood holding 1% of the data spans 95% of the range of every feature. The k nearest neighbours are no longer close to the query in any useful sense. Their labels are close to a random sample of the whole dataset.
Effect 2: distance concentration
When d is large, the distances from a query to all training points cluster around the same value. The nearest point is barely nearer than the farthest.
The following script measures this on random uniform data. It reports the relative contrast, (max - min) / min. This is how much farther the farthest point is than the nearest one, as a fraction of the nearest distance.
import numpy as np
rng = np.random.default_rng(0)
n = 1000
for d in [1, 2, 10, 100, 1000]:
X = rng.random((n, d))
query = rng.random(d)
dist = np.linalg.norm(X - query, axis=1)
contrast = (dist.max() - dist.min()) / dist.min()
print(f"d={d:5d} min={dist.min():.3f} max={dist.max():.3f} contrast={contrast:.2f}")You should see the relative contrast fall steadily as d grows. At d = 1 the nearest point can be a tiny fraction of the farthest distance, so the contrast is huge. At d = 1000 the minimum and maximum are within a modest factor of each other. The exact numbers depend on the random seed, but the trend is stable.
The reason is arithmetic. A squared Euclidean distance is a sum of d per-feature terms. The mean of the sum grows with d. Its standard deviation grows only like the square root of d. So the spread relative to the mean shrinks as 1/√d.
Corners and the unit ball
A related fact explains why intuition from 2D and 3D fails. Compare the volume of a ball of radius 1 to the cube of side 2 that contains it.
| Dimensions d | Ball volume as a fraction of cube volume |
|---|---|
| 2 | 0.785 |
| 3 | 0.524 |
| 10 | 0.0025 |
In 10 dimensions, almost all of the cube's volume lies in its corners, far from the centre. Uniformly random points are mostly far from any given centre, and they are almost all about the same distance away. A distance threshold cuts the data into "almost none" or "almost all", with little in between.
Effect 3: irrelevant features add noise
Real datasets have many features that carry no signal about the label. Each one adds a random term to every distance. If only 5 of 100 features matter, the 95 noise features dominate the sum, and the neighbours you find are neighbours in noise.
This differs from the geometric effects above. Even a dataset with a low-dimensional structure can fool k-NN if you give it many useless columns. The next experiment makes that visible. It takes the wine dataset, whose 13 features are informative, and appends columns of pure Gaussian noise. The scaler runs inside a pipeline, so it is fitted separately in each cross-validation fold.
import numpy as np
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)
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])
model = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=5))
score = cross_val_score(model, X_aug, y, cv=5).mean()
print(f"noise features={n_noise:4d} cv accuracy={score:.3f}")With no noise columns, accuracy is high because the standardised wine features separate the classes well. As noise columns are added, cross-validated accuracy falls. By 200 noise columns the 13 real features are a small part of every distance, and the model is much weaker. Your exact numbers may differ slightly by library version, but the decline is the point.
Scaling does not rescue this. Standardising gives each noise feature the same weight as each real one, which is exactly the problem.
Why real data is often less cursed
The effects above are worst for data spread uniformly through the full space. Real data usually is not. Pixels of handwritten digits, for example, live near a much lower-dimensional surface, because neighbouring pixels are strongly correlated and only certain shapes occur. The relevant quantity is the intrinsic dimension: the number of degrees of freedom the data actually varies in. A 784-pixel image dataset may behave more like a 10 to 20 dimensional problem.
Consequences:
- Do not judge risk by the column count alone. 500 correlated features can be far safer than 30 independent noisy ones.
- Distance concentration is measurable on your own data. Compute the relative contrast from a query to your training points, as in the first script. If it is near zero, expect weak neighbours.
- Correlated features still inflate distance toward their shared direction. That is a different problem from the curse, but it interacts with it.
Mitigations
No single fix works everywhere. Choose by what you know about the data.
| Approach | When it helps | Cost or risk |
|---|---|---|
| Feature selection | Many columns are known or measured to be irrelevant | Needs a selection method that is fitted inside cross-validation, or you leak information |
| Dimensionality reduction (for example PCA) | Features are correlated and data has low intrinsic dimension | Components can mix informative and noisy directions; PCA ignores the labels |
| More training data | You can collect it cheaply | Needed volume grows exponentially with intrinsic dimension |
| Different metric (for example cosine, or Manhattan) | Direction matters more than magnitude, as with text or embeddings | Does not remove the underlying sparsity |
| Learned embeddings | You have a model that maps raw inputs to a compact, task-relevant space | Quality of neighbours depends on the embedding |
| Another algorithm | Dimension stays high and nothing above helps | You lose k-NN's simplicity |
Manhattan distance is sometimes said to suffer less from concentration than Euclidean distance in high dimensions. Some research supports a mild advantage for fractional or low-order Minkowski norms, but the effect is modest, and you should confirm it by cross-validation rather than assume it.
Reduce inside the pipeline
Whatever transformation you choose, put it in the pipeline so that it is fitted only on each training fold. This sketch tunes the number of PCA components along with k:
from sklearn.datasets import load_wine
from sklearn.decomposition import PCA
from sklearn.model_selection import GridSearchCV
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_wine(return_X_y=True)
pipe = Pipeline([
("scale", StandardScaler()),
("pca", PCA()),
("knn", KNeighborsClassifier()),
])
param_grid = {
"pca__n_components": [2, 5, 8, 13],
"knn__n_neighbors": [3, 5, 9],
}
grid = GridSearchCV(pipe, param_grid, cv=5)
grid.fit(X, y)
print(grid.best_params_, round(grid.best_score_, 3))On a 13-feature dataset the gain is small, because the problem is not very cursed. The same structure matters far more on data with hundreds of columns.
Effects on search speed
The curse also affects the search structures you will meet in a later chapter. KD-trees and ball trees prune the search by ruling out regions of space. When distances concentrate, few regions can be ruled out, because almost every region might contain a point near the query's distance. As a rule of thumb, tree-based search is fast for roughly 20 or fewer effective dimensions and tends to fall back toward brute-force cost above that. Higher dimensions generally call for brute force on vectorised hardware or for approximate methods.
Practical checklist
- Count features, then estimate how many are informative. Remove obvious noise and duplicates first.
- Scale features inside a pipeline.
- Compute the relative contrast on a sample of queries. A very low value is a warning sign.
- Try dimensionality reduction and feature selection as pipeline steps, and compare by cross-validation.
- Compare k-NN against a model that learns feature weights, such as a regularised linear model or a tree ensemble. If it wins clearly, the curse is probably the cause.
Exercise
A dataset has 20 informative features and you append 180 columns of independent noise, all standardised. Explain why k-NN accuracy is likely to drop, and why standardising does not fix it. Name one change that could.
Show answer
Each squared distance is a sum over all 200 features. The 180 noise terms add large random contributions that swamp the 20 informative terms, so the nearest neighbours are chosen mostly by noise. Standardising gives every feature equal variance, so noise columns are weighted the same as real ones and the problem remains. Removing the noise columns by feature selection (fitted inside cross-validation), or applying supervised dimensionality reduction, could help.
Exercise
Using the table of edge lengths p^(1/d), compute the edge length needed to capture 5% of uniformly distributed data in d = 20. What does the answer say about the neighbourhood?
Show answer
0.05^(1/20) = exp(ln(0.05) / 20) = exp(-2.996 / 20) = exp(-0.1498), which is about 0.86. A cube holding only 5% of the data must span about 86% of the range of each feature, so the neighbourhood is not local at all.