Sub topic 1
Why high-dimensional data is hard to see
A screen shows two dimensions. Many real datasets have dozens, thousands, or millions. This chapter explains why that gap is a real problem and not only an inconvenience. It also sets up the question the rest of the tutorial answers: how do you place points in 2-D so the plot says something true about the data?
Prerequisites
This chapter assumes you have:
- Basic Python and NumPy.
- Familiarity with scikit-learn's
fit/transforminterface. - Euclidean distance and the idea of a feature vector, meaning a row of numbers describing one sample.
- Basic probability, such as distributions and normalisation.
- A rough idea of gradient descent.
Install numpy, scikit-learn and matplotlib to run the examples. UMAP appears in later chapters.
What "high-dimensional" means
A dataset is high-dimensional when each sample has many features. Each feature is one dimension, so a sample is a point in a space with one axis per feature.
The scikit-learn digits dataset is a small example. Each image is 8×8 pixels, so each sample is a point in 64 dimensions.
from sklearn.datasets import load_digits
X, y = load_digits(return_X_y=True)
print(X.shape) # (1797, 64)
print(X[0].reshape(8, 8))
print(y[:10])Printing one image as an 8×8 grid is easy. Reasoning about 1,797 points in 64-D at once is not. The same pattern holds for gene expression (20,000 genes per cell), text embeddings (hundreds of dimensions per document), and sensor logs.
Why you cannot just plot it
You can plot two or three features directly. With more, the usual workarounds each break down.
| Approach | What goes wrong |
|---|---|
| Plot two chosen features | Ignores the other features. The pair you picked may show nothing. |
| Scatter-plot matrix (all pairs) | Needs d(d−1)/2 panels. For 64 features that is 2,016 plots. |
| Colour, size and shape as extra axes | Adds perhaps three more dimensions before the plot becomes unreadable. |
| Parallel coordinates | Lines overlap heavily with many samples, and the order of axes changes the picture. |
A scatter-plot matrix also shows only pairwise structure. A cluster that exists only as a combination of many features can look like noise in every individual panel.
Geometry changes as dimension grows
Our intuition comes from 2-D and 3-D. In high dimensions several facts differ from that intuition, and they affect every method in this tutorial.
Volume moves to the corners
Take the unit ball (radius 1) inside the cube with side 2 that contains it. In 2-D the ball fills about 79% of the cube. The fraction falls very quickly as the dimension d rises.
import math
def ball_fraction(d):
ball = math.pi ** (d / 2) / math.gamma(d / 2 + 1)
cube = 2.0 ** d
return ball / cube
for d in [2, 3, 10, 20, 50, 100]:
print(f"d={d:>3}: {ball_fraction(d):.3e}")By d = 20 the ball holds a tiny fraction of the cube. Almost all the volume sits in the corners, far from the centre. Uniformly spread data is therefore very sparse. A fixed number of samples covers a space of this kind poorly.
Distances lose contrast
The second effect is called distance concentration. For many distributions, as d grows, the distance from a query point to its nearest sample and to its farthest sample become almost the same. This matters because neighbour-based methods, including t-SNE and UMAP, rely on the idea that "near" and "far" are clearly different.
import numpy as np
rng = np.random.default_rng(0)
for d in [2, 10, 100, 1000]:
X = rng.uniform(size=(500, d))
q = rng.uniform(size=(1, d))
dist = np.linalg.norm(X - q, axis=1)
contrast = (dist.max() - dist.min()) / dist.min()
print(f"d={d:>4}: relative contrast = {contrast:.3f}")The relative contrast, which is the gap between farthest and nearest distance as a fraction of the nearest, shrinks steadily as d increases. In 2-D the farthest point is many times farther than the nearest. In 1,000-D it is only slightly farther.
Why this does not make real data hopeless
Real datasets are rarely spread evenly through all d dimensions. Pixels in a digit image are correlated, because strokes cover neighbouring pixels. Words in a document are correlated through topic. The effective number of degrees of freedom is often far smaller than the number of features. A later chapter on the manifold hypothesis develops this idea. It is the reason a 2-D picture can be faithful at all.
What we want from a visualisation
If we map each 64-D point to a 2-D point, we must lose information. The goal is to choose what to keep. Common targets are:
- Global structure: keep large distances and overall layout correct. PCA does this best.
- Local structure: keep each point's nearest neighbours the same in the map as in the original space. This is what t-SNE and UMAP aim for.
These goals conflict, because 2-D has less room than 64-D. Points that are all close to each other in high dimensions may be impossible to place all close to each other on a plane. Every method makes a compromise, and the compromise shapes what the plot can and cannot tell you.
A first look at the cost
You can already see the problem with the simplest approach: drop all but two original features and plot them.
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
X, y = load_digits(return_X_y=True)
# Two arbitrary pixels out of 64
fig, ax = plt.subplots(figsize=(5, 5))
sc = ax.scatter(X[:, 27], X[:, 36], c=y, cmap="tab10", s=8)
fig.colorbar(sc, label="digit")
ax.set_xlabel("pixel 27")
ax.set_ylabel("pixel 36")
ax.set_title("Two raw pixels out of 64")
plt.show()The colours mix heavily. Two pixels carry only a small part of what separates the digits. The next chapters replace this arbitrary choice with methods that use all 64 features to compute the 2-D coordinates.
Common mistakes at this stage
- Trusting a pairwise plot as the whole picture. A feature pair shows a 2-D shadow of the data. Structure that depends on other features is invisible.
- Assuming distances behave as in 2-D. In high dimensions, "nearest neighbour" can be a weak statement when the data has many noisy features.
- Skipping feature scaling. Features on large scales dominate Euclidean distance. A column measured in thousands overwhelms one measured between 0 and 1. Standardising features is usually the first step. It is covered in the workflow chapter.
- Treating the 2-D plot as the data. The plot is a lossy summary. Conclusions should be checked in the original space, for example with a classifier or a neighbour query.
Exercise
A scatter-plot matrix of a dataset with 30 features is proposed as a way to "see everything". How many panels would it need if it shows each pair of distinct features once, and why would it still miss some structure?
Show answer
It needs 30 × 29 / 2 = 435 panels. Even then, each panel shows only two features at a time. A cluster that is defined by a combination of many features can look like a diffuse blob in every individual panel, so pairwise plots can hide it.
Exercise
You run the distance-concentration script with d = 1000 and see that the relative contrast is close to zero. What does this say about using Euclidean nearest neighbours on that data, and what is one reason real datasets usually do better than the uniform noise in the script?
Show answer
Nearest and farthest points are almost equally far away, so "nearest neighbour" is a weak and unstable notion on that data. Real datasets usually have correlated features, so their points lie near a lower-dimensional structure and distances stay more informative than for uniform noise.