Velamuvi AIAcademy

Lesson 3 of 8 · No Labels

Dimensionality Reduction Overview

Why fewer features help: the curse of dimensionality, selection vs extraction, linear vs non-linear methods, and a map of PCA, t-SNE, UMAP and autoencoders.

  • 16 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain the curse of dimensionality, and see distances lose their meaning as features are added
  • Tell feature selection apart from feature extraction
  • Tell linear from non-linear methods, and recognise data that needs a non-linear one
  • Name what dimensionality reduction is used for: visualisation, compression, denoising and speed
  • Choose between PCA, t-SNE, UMAP and autoencoders, and know where each is covered

The idea in plain words

Every feature is one dimension. A customer described by 2 numbers is a point on a flat map; an 8 × 8 pixel image described by 64 numbers is a point in a 64-dimensional space. Nobody can picture 64 dimensions, but the maths works the same way, and many datasets have hundreds or thousands of features.

It works because real features overlap. Height in centimetres and height in inches are the same information twice. The 64 pixels of a handwritten digit are far from independent: neighbouring pixels are usually dark together. In What Is Unsupervised Learning?, four customer features turned out to hold only two hidden factors, and two numbers per customer kept 99.7% of the variation. Fewer numbers are faster to process, easier to plot, and often better for models, because of a problem with a dramatic name.

The curse of dimensionality

In Instance-Based Models, adding noise features made k-nearest neighbours less accurate. The reason is geometry. The program below scatters 1,000 random points, measures how far one more random point is from each of them, and compares the nearest with the farthest, for more and more features:

Try it yourselfPython
import numpy as np

rng = np.random.default_rng(0)
for d in [2, 10, 100, 1000]:
    points = rng.uniform(0, 1, size=(1000, d))     # 1,000 random points with d features
    query = rng.uniform(0, 1, size=d)              # one more point
    dist = np.linalg.norm(points - query, axis=1)  # its distance to each of the 1,000
    print(f"{d:>4} features: nearest {dist.min():5.2f}, farthest {dist.max():5.2f}, "
          f"farthest / nearest = {dist.max() / dist.min():6.2f}")
Output
   2 features: nearest  0.01, farthest  1.33, farthest / nearest = 135.62
  10 features: nearest  0.47, farthest  2.11, farthest / nearest =   4.48
 100 features: nearest  3.35, farthest  4.65, farthest / nearest =   1.39
1000 features: nearest 12.17, farthest 13.55, farthest / nearest =   1.11

With 2 features, the nearest point is 135 times closer than the farthest: "near" and "far" mean something. With 1,000 features, every point is roughly the same distance away, and the farthest is only 11% farther than the nearest. Any method built on distances, such as k-means, DBSCAN or k-nearest neighbours, loses its sense of who is similar to whom.

The space also grows explosively. To have one example in every cell of a grid with 10 steps per feature, 2 features need 100 examples, but 10 features need 10 billion. With a fixed amount of data, every extra feature leaves the data more thinly spread. Reducing dimensions is one cure; another is keeping only the features that matter.

Feature selection vs feature extraction

There are two ways to end up with fewer features:

  • Feature selection keeps some of the original columns and drops the rest. The result is easy to explain: "the model uses radius, texture and smoothness".
  • Feature extraction builds new columns, each computed from many of the original ones. It can pack more information into fewer columns, but a new column such as "0.3 × radius + 0.2 × texture − …" is harder to explain.

Selection can be unsupervised, for example dropping columns that never change or that copy another column, or supervised, keeping the columns that best predict the label (the Feature Selection course covers those methods). The program below does one of each on 30 measurements of breast tumours, ignoring the diagnosis:

Try it yourselfPython
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler

data = load_breast_cancer()
X, names = data.data, data.feature_names
print(f"original: {X.shape[1]} measurements of each tumour")

# Feature selection: keep original columns, skipping near-copies of columns already kept
corr = np.abs(np.corrcoef(X, rowvar=False))
keep = []
for j in range(X.shape[1]):
    if all(corr[j, k] < 0.9 for k in keep):
        keep.append(j)
print(f"selection:  {len(keep)} of the original columns, e.g. {', '.join(names[keep[:3]])}")
print(f"  (dropped e.g. 'mean perimeter': correlation with 'mean radius' is {corr[0, 2]:.3f})")

# Feature extraction: new columns, each a weighted mix of all 30
pca = PCA(n_components=0.9).fit(StandardScaler().fit_transform(X))
print(f"extraction: {pca.n_components_} new columns keep 90% of the variance")
Output
original: 30 measurements of each tumour
selection:  21 of the original columns, e.g. mean radius, mean texture, mean smoothness
  (dropped e.g. 'mean perimeter': correlation with 'mean radius' is 0.998)
extraction: 7 new columns keep 90% of the variance

A tumour's perimeter follows almost perfectly from its radius (correlation 0.998), so keeping both adds nothing. Dropping such near-copies leaves 21 original columns. PCA goes further: 7 new columns hold 90% of the variation in all 30, but each one mixes every measurement.

Linear vs non-linear methods

A linear method makes every new feature a weighted sum of the original ones. Geometrically, it lays a flat sheet (or a straight line) through the data and records each point's position on it, like a shadow. PCA is the best-known linear method. A non-linear method can bend: it can follow data that lies along a curved shape.

Points on a ring show the difference. Each point really needs only one number, its angle around the ring, but no straight line captures it:

Try it yourselfPython
import numpy as np
from sklearn.decomposition import PCA

angle = np.linspace(0, 2 * np.pi, 100, endpoint=False)
X = np.column_stack([np.cos(angle), np.sin(angle)])     # 100 points on a ring, 2 features each

# Linear: the best single straight direction
pca = PCA().fit(X)
print("PCA, share of the variance along each direction:", np.round(pca.explained_variance_ratio_, 2))

# Non-linear: one curved coordinate, the angle around the ring
theta = np.arctan2(X[:, 1], X[:, 0])                    # 1 number per point
rebuilt = np.column_stack([np.cos(theta), np.sin(theta)])
print("rebuilt from the angle alone, largest error:", round(np.abs(rebuilt - X).max(), 6))
Output
PCA, share of the variance along each direction: [0.5 0.5]
rebuilt from the angle alone, largest error: 0.0

PCA finds no direction better than any other: each keeps exactly half of the variation, so dropping one loses half the information. Yet one curved coordinate, the angle, describes every point perfectly. Here we knew the formula for the angle; non-linear methods such as t-SNE, UMAP and autoencoders find curved coordinates like it from the data alone.

Linear (PCA)Non-linear (t-SNE, UMAP, autoencoders)
New featuresWeighted sums of the original featuresCurved functions, learned from the data
Best atStraight-line structure and the big pictureCurved structure and keeping neighbours together
Speed and repeatabilityVery fast, the same answer every timeSlower, and results change with settings and random seeds
Reading the resultEach new feature has weights you can inspectThe new axes have no meaning of their own

What it is used for

  1. Visualisation: squeeze data into 2 or 3 numbers per example and draw it, to see groups, outliers and mistakes.
  2. Compression: store fewer numbers per example, saving memory and disk.
  3. Speed: models train and predict faster on fewer features, and distance-based models suffer less from the curse.
  4. Denoising: random noise spreads over all directions, while the real signal sits in a few strong ones, so keeping only those removes much of the noise.

The program below tries the first three on 1,797 images of handwritten digits, 64 pixels each. All pixels share one unit, darkness from 0 to 16, so they need no scaling:

Try it yourselfPython
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline

X, y = load_digits(return_X_y=True)          # 1,797 images of 8 x 8 = 64 pixels

pca = PCA(n_components=2).fit(X)             # visualisation: 2 numbers for a 2-D map
print(f"2 components keep {pca.explained_variance_ratio_.sum():.0%} of the variance")

pca = PCA(n_components=0.9).fit(X)           # compression: keep 90% of the variance
print(f"{pca.n_components_} components keep 90% of the variance")

small = make_pipeline(PCA(n_components=pca.n_components_), KNeighborsClassifier())   # speed
full_acc = cross_val_score(KNeighborsClassifier(), X, y, cv=5).mean()
small_acc = cross_val_score(small, X, y, cv=5).mean()
print(f"k-NN accuracy: {full_acc:.3f} on 64 pixels, {small_acc:.3f} on {pca.n_components_} components")
Output
2 components keep 29% of the variance
21 components keep 90% of the variance
k-NN accuracy: 0.963 on 64 pixels, 0.959 on 21 components

A 2-D PCA map keeps only 29% of the variation, which is why t-SNE and UMAP, which concentrate on neighbours, usually draw clearer maps of data like this. For compression, 21 numbers per image keep 90%, and k-nearest neighbours classifies digits almost as well from those 21 numbers as from all 64, while doing a third of the work for every distance. Now the fourth use, denoising:

Try it yourselfPython
import numpy as np
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA

X, _ = load_digits(return_X_y=True)
noisy = X + np.random.default_rng(0).normal(0, 3, X.shape)    # random noise on every pixel

pca = PCA(n_components=20).fit(noisy)                         # keep the 20 strongest directions
cleaned = pca.inverse_transform(pca.transform(noisy))         # rebuild the images from them

print(f"noisy images:  average squared error {np.mean((noisy - X) ** 2):.1f}")
print(f"after PCA:     average squared error {np.mean((cleaned - X) ** 2):.1f}")
Output
noisy images:  average squared error 9.0
after PCA:     average squared error 5.0

The program adds noise to every pixel, squeezes each noisy image into 20 numbers and rebuilds it. The rebuilt images are closer to the clean originals than the noisy ones were: the 20 strongest directions kept the digits and left much of the noise behind. The next lesson explains inverse_transform, which does the rebuilding.

A map of the main methods

MethodTypeWhat it keepsNew dataTypical useWhere to learn it
PCALinearThe directions of greatest variancetransformCompression, denoising, speed, a first lookPrincipal Component Analysis, next
t-SNENon-linearEach point's nearest neighboursNo transform2-D pictures of clusterst-SNE and UMAP
UMAPNon-linearNeighbours, plus more of the big picture than t-SNEtransform2-D pictures, and features for other modelst-SNE and UMAP
AutoencoderNon-linear (a neural network)Whatever the network needs to rebuild its inputThe encoderImages, sound, anomaly detectionNeeds neural networks: start with Introduction to Deep Learning

An autoencoder is a neural network trained to copy its input through a narrow middle layer: the encoder squeezes each example into a few numbers, and the decoder rebuilds the example from them. PCA and t-SNE are in scikit-learn; UMAP lives in the separate umap-learn library. scikit-learn also offers TruncatedSVD for sparse data such as word counts, and more non-linear methods in sklearn.manifold.

A sensible order is to try PCA first, because it is fast, repeatable and easy to check. Reach for t-SNE or UMAP when you want a 2-D picture of clusters, and for an autoencoder when you have images or sound and enough data to train a network.

Common mistakes

Practice

Practice exercise

Measure the curse of dimensionality: how big must a neighbourhood be to hold just 10% of the data as the number of features grows? Look at the edge for 100 features: is that neighbourhood still local?

Your solutionPython
# Points are spread evenly through a cube whose sides run from 0 to 1, in d dimensions.
# A smaller cube with edge e holds a share e ** d of them.
# So to hold 10% of the points, the smaller cube needs edge = 0.1 ** (1 / d).
#
# For d in 1, 2, 3, 10 and 100, print the edge rounded to 2 decimals, like:
# d=1: edge 0.10
Knowledge check

Which of these is feature extraction rather than feature selection?

Summary

  • Dimensionality reduction describes each example with fewer numbers. It works because real features overlap and carry noise.
  • The curse of dimensionality: as features are added, data becomes sparse and distances become nearly equal, which hurts distance-based methods.
  • Feature selection keeps some original columns and is easy to explain; feature extraction builds new, mixed columns and packs in more information.
  • Linear methods such as PCA are fast and repeatable but only find flat structure; non-linear methods such as t-SNE, UMAP and autoencoders can follow curves.
  • Reduction serves visualisation, compression, denoising and speed. Start with PCA, and check that the reduction helps your goal.

Next: Principal Component Analysis.

Finished reading? Tick it off to track your progress.