TExcelTAD

Autoencoders, t-SNE and UMAP

PCA, SVD, LDA and random projection are all linear: the new features are weighted sums of the old ones. Data that lies on a curved surface, such as handwritten digits that vary by stroke thickness, slant and loop size, needs non-linear tools. This lesson covers two kinds. An autoencoder is a neural network that learns a compressed code that can be used as features. t-SNE and UMAP draw high-dimensional data as a 2-D map for exploration, and come with a strong warning about what such maps can and cannot tell you.

Autoencoders: compress, then reconstruct

An autoencoder has two parts. The encoder maps an input x (here 64 pixel values) to a short code z (say 2 or 8 numbers); the decoder maps z back to a reconstruction of x. Training minimises the reconstruction error, so the code is forced to keep whatever information is needed to rebuild the input. No labels are used.

input x64 pixels encoder code z2 to 8 decoder outputreconstruction loss = mean squared difference between input and output

A useful fact connects this to PCA: an autoencoder with linear layers and squared error learns the same subspace as PCA. Non-linear activations are what let it go further. The linear case is easy to check in NumPy, with gradient descent on the two weight matrices:

python · try it yourself
import numpy as np
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA

X = load_digits().data / 16.0                 # 1797 images, 64 pixels in [0, 1]
X = X - X.mean(0)
rng = np.random.default_rng(0)
k = 2
W_enc = rng.normal(0, 0.1, (64, k))
W_dec = rng.normal(0, 0.1, (k, 64))
lr = 0.05
for step in range(3001):
    Z = X @ W_enc                             # encode
    R = Z @ W_dec                             # decode
    E = R - X
    if step % 1000 == 0:
        print(f"step {step:>4}: reconstruction MSE {np.mean(E ** 2):.4f}")
    g_dec = Z.T @ E / len(X)
    g_enc = X.T @ (E @ W_dec.T) / len(X)
    W_dec -= lr * g_dec
    W_enc -= lr * g_enc

pca = PCA(n_components=k).fit(X)
mse_pca = np.mean((pca.inverse_transform(pca.transform(X)) - X) ** 2)
print(f"PCA with {k} components:  reconstruction MSE {mse_pca:.4f}")
step    0: reconstruction MSE 0.0732
step 1000: reconstruction MSE 0.0525
step 2000: reconstruction MSE 0.0524
step 3000: reconstruction MSE 0.0524
PCA with 2 components:  reconstruction MSE 0.0524

The linear autoencoder starts at an error of 0.0732 and settles at 0.0524 after about 1,000 steps, exactly PCA's reconstruction error with 2 components. Gradient descent found the same 2-D subspace (its two code axes may be a rotated version of PCA's, but they span the same plane).

A real autoencoder uses non-linear layers and a deep-learning library. This recorded PyTorch example trains a small one on the digits with an 8-number code and compares it with PCA at the same size, both measured on 360 held-out images:

python · try it yourself
import numpy as np
import torch
from torch import nn
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.model_selection import train_test_split

torch.manual_seed(0)
X = load_digits().data.astype(np.float32) / 16.0
X_tr, X_te = train_test_split(X, test_size=360, random_state=0)
k = 8

model = nn.Sequential(
    nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, k),        # encoder
    nn.Linear(k, 32), nn.ReLU(), nn.Linear(32, 64), nn.Sigmoid())   # decoder
opt = torch.optim.Adam(model.parameters(), lr=1e-2)
xt, xv = torch.tensor(X_tr), torch.tensor(X_te)
for epoch in range(301):
    perm = torch.randperm(len(xt))
    for i in range(0, len(xt), 128):
        batch = xt[perm[i:i + 128]]
        loss = nn.functional.mse_loss(model(batch), batch)
        opt.zero_grad()
        loss.backward()
        opt.step()
    if epoch % 100 == 0:
        with torch.no_grad():
            print(f"epoch {epoch:>3}: test MSE {nn.functional.mse_loss(model(xv), xv).item():.4f}")

encoder = model[:3]
with torch.no_grad():
    codes = encoder(xv).numpy()
print("code shape for the test images:", codes.shape)

pca = PCA(n_components=k).fit(X_tr)
mse_pca = np.mean((pca.inverse_transform(pca.transform(X_te)) - X_te) ** 2)
print(f"PCA, {k} components: test MSE {mse_pca:.4f}")
epoch   0: test MSE 0.0841
epoch 100: test MSE 0.0147
epoch 200: test MSE 0.0139
epoch 300: test MSE 0.0142
code shape for the test images: (360, 8)
PCA, 8 components: test MSE 0.0253

On the 360 test images the network's error falls from 0.0841 to 0.0139 by epoch 200 and ends at 0.0142 at epoch 300 (a slight rise: training longer is not always better, which is why the error is watched on held-out data). PCA with the same 8 numbers per image reaches 0.0253, so the non-linear code reconstructs the digits with about 44% less error. After training, encoder(x) turns any image into 8 numbers that can feed another model. Like every fitted step, the autoencoder is trained on the training rows only; here the test images were never seen during training.

Autoencoders shine where PCA cannot reach: images, audio and sensor windows with curved structure, denoising (train to reconstruct the clean input from a noisy one) and anomaly detection (rows the model reconstructs badly are unusual). They cost a training run, tuning and a deep-learning dependency; for tabular data PCA is usually enough.

t-SNE: a map for looking, not for measuring

t-SNE (t-distributed stochastic neighbour embedding) places points in 2-D so that points that are neighbours in the original space stay neighbours on the map. It converts distances into neighbour probabilities in both spaces and moves the 2-D points to make the two sets of probabilities match. The perplexity parameter (typically 5 to 50) sets roughly how many neighbours each point cares about.

python · try it yourself
import numpy as np
from sklearn.datasets import load_digits
from sklearn.manifold import TSNE, trustworthiness
from sklearn.decomposition import PCA

digits = load_digits()
X, y = digits.data[:600], digits.target[:600]

maps = {"PCA": PCA(n_components=2).fit_transform(X)}
for perp in [5, 30]:
    maps[f"t-SNE p={perp}"] = TSNE(n_components=2, perplexity=perp, init="pca",
                                   random_state=0).fit_transform(X)

for name, Z in maps.items():
    # share of each point's 10 nearest map neighbours with the same digit
    d = ((Z[:, None] - Z[None]) ** 2).sum(-1)
    np.fill_diagonal(d, np.inf)
    nn10 = np.argsort(d, axis=1)[:, :10]
    same = (y[nn10] == y[:, None]).mean()
    spread = [round(float(Z[y == c].std(0).mean()), 1) for c in (0, 1)]
    print(f"{name:<11} trustworthiness {trustworthiness(X, Z, n_neighbors=10):.3f}  "
          f"same-digit neighbours {same:.3f}  spread of digit 0, 1: {spread}")
PCA         trustworthiness 0.837  same-digit neighbours 0.569  spread of digit 0, 1: [4.5, 9.4]
t-SNE p=5   trustworthiness 0.989  same-digit neighbours 0.969  spread of digit 0, 1: [6.8, 20.8]
t-SNE p=30  trustworthiness 0.992  same-digit neighbours 0.964  spread of digit 0, 1: [2.4, 7.2]

Trustworthiness (1 is perfect) measures how many of each point's map neighbours are also neighbours in the original 64-D space. The PCA map scores 0.837, and only 56.9% of a point's 10 nearest map neighbours show the same digit; the two t-SNE maps reach about 0.99 and 96 to 97%. t-SNE is far better at showing the groups. But look at the spreads: the size of the digit 0 and digit 1 clusters changes with perplexity, from 6.8 and 20.8 at perplexity 5 to 2.4 and 7.2 at perplexity 30. The same data, two parameter settings, different pictures of how large each group is.

What a t-SNE map does show: which points are neighbours, and whether there are groups. What it does not show reliably:

  • Distances between clusters. Two clusters far apart on the map need not be far apart in the data; t-SNE only cares about local neighbourhoods.
  • Cluster sizes and densities. t-SNE expands dense regions and shrinks sparse ones, so a tight and a loose cluster can look the same size.
  • Shapes that are artefacts. Low perplexity can split one cluster into several; random noise can show apparent clumps. Run several perplexities and seeds before believing a structure.
  • New points. scikit-learn's t-SNE has no transform: it maps only the points it was fitted on. It is a picture, not a preprocessing step for a model.

UMAP

UMAP (uniform manifold approximation and projection, McInnes et al., 2018) builds a nearest-neighbour graph in the original space, treats it as a fuzzy description of the surface the data lies on, and finds a low-dimensional layout with a similar graph. Compared with t-SNE it is usually faster on large data, keeps somewhat more of the global arrangement, and can transform new points, so it is sometimes used as a feature step. Its main knobs are n_neighbors (local versus global view) and min_dist (how tightly points pack).

UMAP lives in the umap-learn package, which depends on Numba, a compiler that does not run in the browser's Python, so there is no runnable example here. On your own machine it is used like any scikit-learn transformer: umap.UMAP(n_neighbors=15, min_dist=0.1, random_state=0).fit_transform(X). The t-SNE caveats apply to UMAP as well: cluster sizes and gaps between clusters are not reliable measures, and plots change with the parameters.

Pitfalls

  • Clustering on a t-SNE map and reporting the clusters as findings: the map's geometry is distorted by design. Cluster in the original space (or a PCA space), then use the map only to look.
  • Training an autoencoder on all data before splitting: it is a fitted step, so it leaks like any other.
  • Comparing t-SNE runs with different seeds point by point: the layout is only defined up to rotation, reflection and stretching.
  • Using t-SNE output as model features: it cannot map new points, and its axes have no meaning.

Practice

  1. A t-SNE plot shows customer group A as a large spread-out cloud and group B as a tiny dense dot. Can you conclude that A is more varied than B?
Answer

No. t-SNE adapts to local density and does not preserve cluster sizes or spreads. Compare the variance of the groups in the original feature space instead.

  1. How would you use an autoencoder to flag unusual sensor readings?
Answer

Train it on normal readings (training data only), then compute the reconstruction error for each new reading. Normal patterns are rebuilt well; unusual ones are not. Choose an error threshold on validation data, for example the 99th percentile of errors on normal validation readings.

Test yourself

What does an autoencoder minimise during training?

  1. The classification error
  2. The difference between the input and its reconstruction
  3. The number of clusters
  4. The perplexity

Which statement about a t-SNE map is reliable?

  1. The distance between two clusters measures how different they are
  2. Points that are close on the map are usually neighbours in the original space
  3. Cluster sizes show how many points each group has
  4. The axes are principal components

Why is scikit-learn's t-SNE not used as a preprocessing step in a model pipeline?

  1. It is supervised
  2. It has no transform for new points
  3. It needs a GPU
  4. It only accepts images

A linear autoencoder trained with squared error learns …

  1. the same subspace as PCA
  2. the LDA directions
  3. a random projection
  4. nothing useful