Chapter 3 — Sub-chapter 3.6

t-SNE & UMAP Visualization

PCA projects data onto straight axes — but real engineering datasets often live on curved manifolds. t-SNE and UMAP unfold these non-linear structures into vivid 2D maps, revealing hidden clusters in multi-sensor bridge monitoring data that linear methods completely miss.

55 min read 2 interactive demos 4 quiz questions

Why Go Beyond PCA?

In the previous sub-chapter you saw PCA compress high-dimensional data by projecting it onto orthogonal axes of maximum variance. That works brilliantly when the important structure is linear — when clusters, gradients, and trends align with straight axes through the data cloud.

But consider a structural health monitoring (SHM) system on a cable-stayed bridge with 200 sensors recording acceleration, strain, temperature, humidity, and wind speed. The sensor readings interact in highly non-linear ways: thermal expansion warps the deck in a curve, traffic load creates non-linear vibration patterns, and wind couples with cable tension through aerodynamic flutter. The “shape” of the data in 200-dimensional space is not a flat ellipse — it is a tangled, curved manifold.

PCA would flatten this manifold into a straight-line projection, smearing distinct operating conditions (normal traffic, heavy truck convoy, thermal expansion event, potential damage) on top of each other. What you need is a method that can unfold the manifold, preserving the local neighbourhood relationships, so that distinct clusters appear as visually separated groups in 2D.

Non-linear Dimensionality Reduction

Non-linear methods do not restrict themselves to straight projections. Instead, they learn a mapping from high-dimensional space to low-dimensional space that preserves some notion of neighbourhood structure: points that are close in the original space should remain close in the embedding, and points that are far apart should remain separated.

The two most widely used non-linear visualisation methods are:

  • t-SNE (t-distributed Stochastic Neighbour Embedding) — introduced by Laurens van der Maaten and Geoffrey Hinton in 2008.
  • UMAP (Uniform Manifold Approximation and Projection) — introduced by Leland McInnes, John Healy, and James Melville in 2018.

Both produce stunning 2D scatter plots from hundreds of dimensions. But they work very differently under the hood, have different strengths and weaknesses, and must be used with care. This sub-chapter gives you the intuition to wield them effectively on civil engineering datasets.

Civil Engineering Analogy

Imagine you have a crumpled sheet of paper — this is your data living on a 2D manifold embedded in 3D space. PCA would photograph the crumpled ball from above, squashing all the folds into an unreadable mess. t-SNE and UMAP are like carefully un-crumpling the paper, flattening it back out so you can read what is written on it. The text (local neighbourhood relationships) is preserved, even though the paper changes shape.

Prerequisites

This sub-chapter assumes you have read Sub-chapter 3.5 (PCA) and understand the curse of dimensionality, variance, and the idea of projecting data to lower dimensions. Familiarity with probability distributions (Gaussian, Student-t) is helpful but not strictly required — we build intuition from first principles.

t-SNE: The Algorithm

t-SNE converts high-dimensional distances into probabilities, then arranges points in 2D so that similar probabilities are reproduced as faithfully as possible. The process has three conceptual stages.

Step 1: High-Dimensional Affinities

For each data point xi, t-SNE defines a conditional probability pj|i that xi would pick xj as its neighbour under a Gaussian distribution centred on xi:

pj|i = exp(−||xi − xj||2 / 2σi2) / Σk≠i exp(−||xi − xk||2 / 2σi2)

The bandwidth σi of the Gaussian is chosen per-point so that the effective number of neighbours matches a user-specified parameter called perplexity. Think of perplexity as “how many neighbours does each point consider?” Typical values range from 5 to 50.

The conditional probabilities are then symmetrised: pij = (pj|i + pi|j) / 2n, ensuring the affinity matrix is symmetric. Large values of pij mean points i and j are considered neighbours; small values mean they are distant.

Step 2: Low-Dimensional Affinities with Student-t

In the 2D embedding, t-SNE defines analogous affinities qij using a Student-t distribution with one degree of freedom (also known as the Cauchy distribution):

qij = (1 + ||yi − yj||2)−1 / Σk≠l (1 + ||yk − yl||2)−1

The crucial insight is using the heavy-tailed Student-t distribution in the low-dimensional space rather than a Gaussian. Because the Student-t has heavier tails, moderately distant points in high-D can be pushed much further apart in 2D, alleviating the “crowding problem” where everything collapses into a single blob.

Step 3: Minimise KL Divergence via Gradient Descent

t-SNE measures the mismatch between the high-dimensional affinities P and the low-dimensional affinities Q using the Kullback–Leibler (KL) divergence:

KL(P || Q) = Σi≠j pij log(pij / qij)

The 2D coordinates yi are initialised randomly, then iteratively updated via gradient descent to minimise this KL divergence. Points that should be close (high pij) are pulled together; points that should be far apart are pushed away. The result, after a few hundred to a thousand iterations, is a 2D scatter plot where local neighbourhood structure from high-D is faithfully reproduced.

Civil Engineering Analogy

Imagine each sensor reading is a person standing in a crowded room (high-D space). Each person holds elastic bands connecting them to their nearest friends (high pij) and weak threads to acquaintances. t-SNE places everyone onto a flat floor plan (2D) by letting the elastic bands pull friends together while the weak threads snap, allowing strangers to drift apart. The final seating arrangement preserves friendships (local structure) even though the room shape has completely changed.

Perplexity: t-SNE's Key Hyperparameter

Perplexity controls the effective number of neighbours each point considers. It directly influences the bandwidth σi of the Gaussian centred on each point. Understanding perplexity is critical for interpreting t-SNE results correctly.

Low Perplexity (5–10)

Each point only looks at its 5–10 nearest neighbours. This produces tight, fragmented clusters. Fine-grained local structure is preserved, but global relationships between clusters are unreliable. You may see a single true cluster split into multiple spurious sub-clusters.

CE example: Analysing strain gauge data from a single bridge section with low perplexity might separate readings by individual sensor location, but you lose the overall picture of which sections behave similarly.

Medium Perplexity (30–50)

The most common range. Each point considers a moderate neighbourhood. Clusters are well-separated, and the embedding is usually stable across different random initialisations. Most SHM datasets with a few thousand data points work well with perplexity around 30–50.

High Perplexity (100+)

Each point considers a large fraction of the dataset. This broadens the Gaussian bandwidth, making the affinity distribution more uniform. Global structure is somewhat preserved, but fine-grained local detail is washed out. Extremely high perplexity can make t-SNE resemble PCA.

Guideline: Perplexity should generally be between 5 and n/3, where n is the number of data points. A dataset with 300 samples should not use perplexity 150.

Common Pitfall

Never trust a single t-SNE plot. Always run the algorithm with multiple perplexity values and multiple random seeds. Patterns that are consistent across settings reflect genuine structure; patterns that appear only with one specific perplexity are likely artifacts.

Interpreting t-SNE Plots

t-SNE produces beautiful scatter plots, but they are deceptively easy to misinterpret. Here are the rules every civil engineer should know before drawing conclusions from a t-SNE visualisation.

What You CAN Interpret

  • Cluster existence: If groups of points are clearly separated in the plot, those points are genuinely similar to each other and dissimilar to other groups in the original high-D space.
  • Relative within-cluster density: Tighter clusters generally contain more similar points; spread-out groups have more internal variation.
  • Outliers: Points isolated from all clusters are genuinely unusual in the original data.

What You CANNOT Interpret

  • Distances between clusters: The distance between two clusters in the t-SNE plot does not reliably indicate how different they are. A cluster placed far away could be very similar or very different — t-SNE does not preserve global distances.
  • Cluster sizes: A cluster that appears large in the plot is not necessarily more varied. t-SNE can artificially expand or compress clusters to balance crowding.
  • Axis values: The x and y axes have no physical meaning. Rotating, flipping, or scaling the plot does not change its validity. Never label the axes or read off coordinates.
Civil Engineering Analogy

Think of t-SNE like a schematic metro map. The map shows which stations are on the same line and the order of stops (local neighbourhood), but it deliberately distorts physical distances and directions to make the diagram readable. You would never measure the actual walking distance between two stations on a metro map — and similarly, you should never measure inter-cluster distances on a t-SNE plot.

The Optimisation Process

Understanding how t-SNE iteratively moves points helps you diagnose problems and tune parameters.

Random Initialisation

The 2D coordinates are initialised from a small Gaussian distribution. Because the initialisation is random, running t-SNE twice on the same data will produce different-looking plots — but the same clusters should emerge consistently.

Early Exaggeration

During the first 250 iterations, t-SNE multiplies all pij values by a factor (typically 12). This forces clusters to move apart quickly before refining their positions. Without early exaggeration, clusters may overlap and fail to separate.

Learning Rate and Momentum

The learning rate controls step size in gradient descent. Too small, and points get stuck in poor configurations; too large, and the layout oscillates wildly. Modern implementations default to n/12 (where n is the number of points) or 200, with adaptive momentum that speeds up convergence.

Convergence

t-SNE typically runs for 1,000 iterations. The KL divergence decreases over time, and the layout stabilises. If you see points still moving significantly at iteration 1,000, increase the number of iterations. On large SHM datasets (50,000+ time windows), use the Barnes–Hut approximation which reduces complexity from O(n2) to O(n log n).

UMAP: Uniform Manifold Approximation and Projection

UMAP approaches the same problem — embedding high-dimensional data into 2D — from a completely different mathematical foundation: algebraic topology and fuzzy set theory. Despite the heavier mathematical machinery, the intuition is surprisingly accessible.

Step 1: Build a Fuzzy Topological Representation

UMAP constructs a weighted k-nearest-neighbour graph in the high-dimensional space. For each point, it finds the k nearest neighbours (controlled by the n_neighbors parameter) and assigns edge weights based on distance — but with a twist.

Each point defines its own local notion of distance, scaled so that its nearest neighbour is distance 0. This local metric adapts to the data density: in dense regions, only very close points get high weights; in sparse regions, more distant points are still considered neighbours. The result is a fuzzy simplicial set — a topological representation of the data that captures its shape at multiple scales.

Step 2: Construct Low-Dimensional Equivalent

UMAP also builds a fuzzy simplicial set in the low-dimensional embedding space. The goal is to find 2D coordinates such that the low-dimensional fuzzy set matches the high-dimensional one as closely as possible.

Step 3: Optimise via Cross-Entropy

UMAP minimises the fuzzy set cross-entropy between the high-dimensional and low-dimensional representations using stochastic gradient descent with negative sampling. This is analogous to t-SNE's KL divergence minimisation, but UMAP's loss function is symmetric: it penalises both pulling apart true neighbours (attraction) and pushing together non-neighbours (repulsion) equally, whereas t-SNE's KL divergence is asymmetric.

Why UMAP Is Faster

UMAP uses several computational tricks that make it significantly faster than t-SNE:

  • Approximate nearest neighbours: Instead of computing all pairwise distances (O(n2)), UMAP uses algorithms like NN-Descent that find approximate k-nearest neighbours in O(n1.14) time.
  • Negative sampling: Rather than computing repulsion over all n2 pairs, UMAP randomly samples a small number of non-neighbours per iteration.
  • Fewer iterations: UMAP's SGD converges in 200–500 epochs versus t-SNE's 1,000+.

On a bridge SHM dataset with 100,000 time windows and 200 sensor features, UMAP can finish in under a minute where t-SNE might take 30 minutes — a critical difference for real-time monitoring dashboards.

UMAP Key Parameters

n_neighbors

Analogous to t-SNE's perplexity, n_neighbors controls how many nearest neighbours define the local topology. Small values (5–15) preserve very local structure and produce tighter, more fragmented clusters. Large values (50–200) capture more global structure and produce smoother, more connected layouts.

CE guideline: For multi-sensor SHM data with well-separated operating conditions, start with n_neighbors=15 and increase if clusters are too fragmented.

min_dist

Controls how tightly points are allowed to pack together in the embedding. A small min_dist (0.0–0.1) produces very dense, clumpy clusters with clear boundaries. A larger value (0.5–1.0) produces a more uniform, spread-out layout that better preserves the broader topological structure at the expense of within-cluster detail.

metric

UMAP supports a wide range of distance metrics: Euclidean, cosine, Manhattan, Chebyshev, Mahalanobis, and even custom functions. For SHM time-series features, cosine similarity often works better than Euclidean distance because it captures the shape of sensor response patterns regardless of amplitude.

t-SNE vs. UMAP: When to Use Which

Both methods produce 2D scatter plots from high-dimensional data, but they have distinct characteristics that make each better suited to different situations.

Comparison Table

Criterion t-SNE UMAP
Speed Slow on large datasets (O(n2) or O(n log n) with Barnes-Hut) Fast, scales well to 1M+ points
Global structure Poorly preserved; cluster positions are arbitrary Better preserved; relative cluster positions are more meaningful
Local structure Excellent; primary design goal Excellent; comparable to t-SNE
Reproducibility Different runs yield different layouts (stochastic) More stable with fixed random seed
New data Cannot embed new points without re-running Supports transform() on unseen data
Higher-dim output Possible but rarely used beyond 2–3D Works well in 2D through 100D for general DR
Mathematical basis Probability distributions, KL divergence Algebraic topology, fuzzy sets, cross-entropy

Recommendation for Civil Engineering

For most civil engineering visualisation tasks — especially SHM dashboards that need to process new data in near real-time — UMAP is the better default choice. It is faster, better preserves global cluster relationships, and can project new incoming sensor windows without re-running the entire algorithm.

Use t-SNE when you need the highest-quality local neighbourhood visualisation for a fixed, moderate-sized dataset (up to ~10,000 points) and are willing to invest computation time and multiple runs to verify stability.

Limitations and Pitfalls

t-SNE Does Not Preserve Global Structure

This is the single most important limitation. The relative positions and distances between clusters in a t-SNE plot are not meaningful. Two clusters placed far apart might be very similar in the original space; two clusters placed close together might be very different. The KL divergence objective heavily penalises placing true neighbours far apart but barely penalises placing non-neighbours close together.

Practical impact: If you use t-SNE to visualise SHM data and see three clusters, you can conclude that three distinct operating conditions exist — but you cannot conclude that cluster A is “more similar” to cluster B than to cluster C based on their 2D positions.

Not Suitable for New / Unseen Data

Standard t-SNE has no transform() method. To embed a new sensor reading, you must re-run the entire algorithm on the combined old + new data. For a real-time monitoring system receiving data every second, this is impractical. UMAP partially addresses this with its transform() method, but even UMAP's transform can degrade if the new data is very different from the training distribution.

Stochastic Nature

Both t-SNE and UMAP are stochastic: different random seeds produce different-looking plots. Genuine clusters will appear consistently across runs, but their positions, orientations, and sizes will vary. Never base a conclusion on a single run — always verify with multiple initialisations.

Hyperparameter Sensitivity

Both methods are sensitive to their key parameters. Changing perplexity from 5 to 50 can dramatically alter the t-SNE output. Changing n_neighbors or min_dist in UMAP has similar effects. Always explore a range of parameter values before drawing conclusions.

Visualisation Only — Not for Downstream ML

t-SNE embeddings are designed for human visual inspection, not as input features for machine learning models. The embedding distorts distances and densities in ways that mislead classifiers and regressors. If you need a reduced representation for modelling, use PCA or autoencoders. Use t-SNE/UMAP for exploration and presentation only.

Critical Warning for Engineers

Never use t-SNE cluster separations as evidence for structural damage without independent validation. The algorithm can create apparent clusters even in uniformly random data if the perplexity is set too low. Always cross-reference visual clusters with physical sensor metadata and known loading events.

CE Application: Visualising Multi-Sensor SHM Data

Structural health monitoring systems on large bridges, dams, and tunnels generate immense volumes of high-dimensional time-series data. t-SNE and UMAP are invaluable for turning this flood of numbers into actionable visual insights.

Typical SHM Data Pipeline

  1. Raw data: 200 sensors × 100 Hz × 24 hours = 1.7 billion readings per day.
  2. Feature extraction: Divide into 10-minute windows. For each window, compute statistical features per sensor: mean, std, max, min, RMS, kurtosis, dominant frequency, spectral entropy. This yields ~144 windows/day × 200 sensors × 8 features = 230,400 dimensions per window. Flatten or aggregate to get a manageable feature vector per window (e.g., 1,600 dimensions).
  3. Dimensionality reduction: Apply PCA to reduce from 1,600 to 50 dimensions (retaining 95% variance), then apply UMAP to project from 50 to 2 dimensions for visualisation.
  4. Visualisation: Colour-code the 2D scatter plot by known metadata (time of day, temperature range, traffic load level). Clusters should correspond to distinct operating conditions.
  5. Anomaly detection: Points that fall outside all known clusters may indicate unusual structural behaviour — a potential damage event warranting physical inspection.

What Engineers Have Found

Published studies applying t-SNE and UMAP to SHM data have revealed:

  • Distinct clusters corresponding to temperature-driven expansion states (winter contraction, summer expansion, transition seasons).
  • Sub-clusters within a temperature regime that correspond to traffic loading levels (night-time quiescence, morning rush hour, heavy truck convoy).
  • Isolated outlier points corresponding to known seismic events, extreme wind storms, or maintenance activities (bridge closures, load testing).
  • Gradual cluster drift over months indicating slow deterioration of bearings or cable tension loss.
Civil Engineering Analogy

Running UMAP on SHM data is like giving the bridge a medical imaging scan. Just as an MRI condenses millions of voxels into a human-readable image that a doctor can inspect for tumours, UMAP condenses millions of sensor readings into a 2D map that an engineer can inspect for anomalies. The map does not replace physical inspection, but it tells you where to look.

Interactive Demo: t-SNE Perplexity Explorer

This demo simulates high-dimensional clustered data (representing sensor feature vectors from different bridge operating conditions) and embeds it in 2D using a simplified t-SNE algorithm. Drag the perplexity slider to see how the embedding changes: low perplexity fragments clusters; high perplexity merges them.

t-SNE Perplexity Explorer

Adjust perplexity to observe how neighbourhood size affects 2D cluster layout.

Status: Ready  |  Perplexity: 30  |  Clusters: 5  |  Points: 150

Interactive Demo: PCA vs. t-SNE Comparison

This side-by-side comparison embeds the same high-dimensional dataset using PCA (left) and a simplified t-SNE (right). Notice how PCA preserves global spread but overlaps clusters, while t-SNE separates clusters clearly but distorts global distances.

PCA vs. t-SNE on Same Dataset

Regenerate data to see both projections update simultaneously.

PCA Projection
t-SNE Embedding
Status: Ready  |  Points: 120  |  Original dims: 8  |  Clusters: 4

Practical Workflow for Engineers

Follow this step-by-step workflow when applying t-SNE or UMAP to your civil engineering datasets.

Step 1: Pre-process and Standardise

Remove missing values, handle outliers, and standardise all features to zero mean and unit variance. Both t-SNE and UMAP are distance-based methods — features on larger scales will dominate the distance computations just as they do in PCA.

Step 2: Apply PCA First

If your data has more than ~50 dimensions, apply PCA to reduce to 30–50 components before running t-SNE or UMAP. This speeds up computation, reduces noise, and often improves the quality of the embedding. The original t-SNE paper recommends PCA pre-processing to 50 dimensions.

Step 3: Choose Your Method

Use UMAP for large datasets (> 10,000 points), when you need to embed new data, or when global cluster relationships matter. Use t-SNE for smaller datasets when you want the sharpest local cluster separation and are willing to run multiple times.

Step 4: Explore Parameters

Run the algorithm with at least 3–5 different parameter settings. For t-SNE, try perplexity = {5, 15, 30, 50}. For UMAP, try n_neighbors = {5, 15, 30, 50} with min_dist = {0.0, 0.1, 0.5}. Compare results to distinguish genuine structure from artifacts.

Step 5: Validate with Domain Knowledge

Colour-code the resulting scatter plot by known labels: temperature range, traffic load, time of day, sensor location. If the clusters align with physical intuition, the embedding is trustworthy. If they do not, revisit feature engineering and parameter settings.

CE Application: t-SNE/UMAP for Sensor & SHM Visualization

When PCA can't separate your data, non-linear embeddings reveal hidden structure.

SHM Sensor Patterns

t-SNE on vibration spectra from bridge sensors reveals clusters of "normal", "thermal drift", and "damage" patterns that PCA misses in high-dimensional frequency data.

Hydrochemical Facies

UMAP on multi-ion water chemistry data creates stunning visualizations where each cluster represents a distinct water type (Ca-HCO₃, Na-Cl, etc.) — far better than Piper diagrams for large datasets.

Warning: t-SNE/UMAP embeddings are for visualization only — distances between clusters aren't meaningful. Don't measure "how far apart" two soil groups are in t-SNE space.
Try it interactively

Hunt for structure with colour-by-feature scatter

Load a dataset, pick any two features as X / Y and colour the points by a third — a poor-man's 2-D projection that often hints at the clusters t-SNE / UMAP will surface.

Open Explorer

Test Your Understanding

Quick Check 1

What distribution does t-SNE use in the low-dimensional space to compute affinities between embedded points?

Quick Check 2

An engineer runs t-SNE on SHM data and sees two well-separated clusters A and B. Cluster A is placed 10 units away from cluster B on the 2D plot. Can she conclude that A and B are very different in the original sensor space?

Quick Check 3

Which advantage does UMAP have over t-SNE for a real-time bridge monitoring system that receives new sensor data every second?

Quick Check 4

Before applying t-SNE to a 500-dimensional SHM feature vector, the recommended best practice is to:

Key Takeaways

Summary

  • t-SNE converts high-D distances into probabilities (Gaussian in high-D, Student-t in low-D) and minimises KL divergence via gradient descent to produce 2D embeddings with excellent local structure.
  • Perplexity controls how many neighbours each point considers. Always try multiple values (5–50) and verify clusters are consistent.
  • UMAP uses fuzzy topological representations and cross-entropy optimisation. It is faster, better preserves global structure, and supports projecting new data.
  • Neither method preserves global distances reliably. Cluster existence is trustworthy; inter-cluster distances and cluster sizes are not.
  • For civil engineering SHM, UMAP is the recommended default. Apply PCA pre-processing (to ~50 dimensions) before t-SNE or UMAP for best results.
  • Use t-SNE and UMAP for visualisation and exploration only — not as input features for downstream ML models.
  • Always validate visual clusters against physical metadata (temperature, traffic load, known events) before drawing engineering conclusions.

What Comes Next

In Sub-chapter 3.7 (Anomaly Detection), you will learn how to move from visual cluster inspection to automated anomaly detection. We will explore isolation forests, autoencoders, and one-class SVMs that can flag unusual sensor patterns without human intervention — the next step towards autonomous structural health monitoring.

Real-world case study · UMAP for long-term bridge SHM exploration

Tamar Bridge SHM — UMAP visualises 15 years of strain & temperature so engineers can see the bridge "live"

The Tamar Bridge (UK) is one of the world's longest continuously-monitored suspension bridges. Researchers at the University of Sheffield's Dynamics Research Group use UMAP (and earlier t-SNE) to compress dozens of channels of strain, temperature and traffic into a 2-D map that exposes daily, seasonal and damage-related drifts at a glance.

0Continuous record
0UMAP embedding
0Sensor channels
0Main span

After a decade of continuous monitoring, the Tamar archive is many gigabytes of high-dimensional time series. Looking at any single channel hides the relationships: the bridge's behaviour is jointly determined by traffic, temperature, wind and slow ageing of cables.

  • Engineers need a single picture that they can show in a board meeting.
  • PCA gives linear axes that mix three physical regimes; nonlinear methods preserve neighbourhoods better.
  • The visualisation has to be stable enough that "today" can be added to "the last decade" without re-running the whole pipeline.

The Sheffield DRG group publishes a workflow that compresses windowed SHM features to 2-D with UMAP.

  • Features: per-hour summaries of strain, cable tension, temperature, traffic and wind.
  • Model: UMAP (uniform manifold approximation & projection) — nonlinear, preserves local structure, supports new-point projection.
  • Output: a 2-D scatter where day/night cycles appear as loops, seasons as colour gradients, and unusual events (traffic incidents, storms, retrofits) as off-manifold points.

UMAP isn't the diagnosis — it's the dashboard. Once engineers can see the manifold, they know where to point classical SHM tools.

  • The Tamar visualisation toolchain has been published, open-sourced and adopted by the bridge operator.
  • Similar UMAP-based dashboards now appear in SHM for the Humber Bridge (UK), Sutong Bridge (China) and the Hong Kong–Zhuhai–Macau Bridge.
  • Pattern: nonlinear dim-reduction for visualisation; PCA/regression for quantitative damage indices — both live side by side.
  • UMAP > t-SNE for production SHM. Reproducible, projects new points, scales better.
  • Visualisation is a deliverable. The economic value isn't the algorithm; it's the picture an asset manager can interpret in a meeting.
  • Use linear & nonlinear together. PCA for confounder removal; UMAP for exploration. Don't pick one.