Clustering and Dimensionality Reduction

CS-GY 6313 - Fall 2026 - Instructor: Claudio Silva

Giancarlo Pereira

2026-11-13

Agenda

  1. What is clustering, and why does a visualization class care?
  2. Clustering Iris: k-means, other methods, when each fails
  3. Judging a clustering: against labels, choosing k, the dendrogram
  4. Seeing a clustering: cluster colors, clustered heatmaps, silhouette plots
  5. Pitfalls and a checklist
  6. Dimensionality reduction: why, PCA, t-SNE, UMAP, and how to tell whether a projection can be trusted

Why does a visualization class care about clustering?

Clustering as a tool for visualization

  • Too many items to draw: show groups, not points
  • Ordering rows and columns of a matrix or heatmap
  • Coloring a scatterplot or map by group
  • Summarizing a time series or trip collection by pattern

Visualization as a tool for clustering

  • Is there structure at all?
  • How many groups, and how clean are the boundaries?
  • Did the algorithm find what I think it found?
  • Where are the points that don’t fit?

Clustering

Etienne Bernard: “… the goal of clustering is to separate a set of examples into groups called clusters”

IRIS

# Code source: Gaël Varoquaux
# Modified for documentation by Jaques Grobler
# License: BSD 3 clause
#
import matplotlib.pyplot as plt

from sklearn import datasets
iris = datasets.load_iris()

_, ax = plt.subplots()
scatter = ax.scatter(iris.data[:, 2], iris.data[:, 1])
ax.set(xlabel=iris.feature_names[2], ylabel=iris.feature_names[1])
_ = ax.legend(
    scatter.legend_elements()[0], iris.target_names, loc="lower right", title="Classes"
)

IRIS

IRIS – another look

IRIS – clustering

IRIS – k-means

K-means in four lines

  1. Pick k starting centroids (k-means++ spreads them out)
  2. Assign each point to its nearest centroid
  3. Move each centroid to the mean of its assigned points
  4. Repeat 2–3 until assignments stop changing

Objective: minimize within-cluster sum of squares \(\;\sum_{c=1}^{k} \sum_{x \in C_c} \lVert x - \mu_c \rVert^2\)

Built-in assumptions: k is known · clusters are convex and roughly spherical · similar sizes · feature scale is meaningful

Wolfram Mathematica FindClusters

Wolfram Mathematica FindClusters

When k-means fails: shape, not count

Right number of clusters, wrong definition of a cluster.

IRIS - classes

Same axes, same flowers: the species (left) and what k-means found (right).

Validating clusters against labels

How many clusters? Two criteria, two answers

The elbow says 3, the silhouette says 2, the botanist says 3.

Hierarchical clustering: the dendrogram

One tree, every k: the cut height is the choice.

Cluster IDs are arbitrary: the colors mean nothing

Same partition, different picture. Colors should not suggest an order or a meaning the clusters don’t have.

Seeing the whole tree: clustered heatmap

Rows are flowers, columns are measurements, the tree reorders the rows. The side bar is the species, held out.

Per-point quality: the silhouette plot

One bar per point, grouped by cluster. Thin or negative bars are points that may be in the wrong place.

Pitfalls checklist

About the algorithm

  • Every method returns clusters, even on noise
  • k is your choice unless the method is density-based
  • Preprocessing (scaling, features) can change the answer more than the method
  • Results can depend on random starts: run several, report stability

About the picture

  • A 2-D projection can hide or invent separation
  • Cluster IDs and colors are arbitrary
  • Show the ambiguous points, not just the centers
  • Report the criterion you used to pick k, and show its curve

Part 2: Dimensionality reduction

Clustering asked which points belong together.

Dimensionality reduction asks how do we draw 64 numbers per item on a 2-D screen, and it is the tool behind most cluster pictures you will meet.

Dimensionality Reduction

  • Input data may have thousands or millions of dimensions!

  • Dimensionality Reduction represents data with fewer dimensions

    • easier learning – fewer parameters
    • visualization – show high-dimensional data in 2D or 3D
    • discover “intrinsic dimensionality” of the data

Dimensionality Reduction

Assumption: data lies on a lower dimensional space

The manifold hypothesis: a ‘3’ perturbed

What operations did we perform, and what is the intrinsic dimensionality?

Principal Component Analysis: intuition

Principal Component Analysis: intuition

Principal Component Analysis

Principal Component Analysis

PCA of digits

from sklearn.decomposition import PCA
pca = PCA(n_components=2)
data, labels = load_digits(return_X_y=True)
reduced_data=pca.fit_transform(data)
plt.scatter(reduced_data[:, 0], reduced_data[:, 1])
plt.show()

PCA of digits

from sklearn.decomposition import PCA
pca = PCA(n_components=2)
data, labels = load_digits(return_X_y=True)
reduced_data=pca.fit_transform(data)
plt.scatter(reduced_data[:, 0], reduced_data[:, 1], c=labels, cmap="tab10", s=10)
plt.colorbar(ticks=range(10), label="digit")
plt.show()

SNE and t-SNE

t-SNE in three steps

Why a heavy tail? The crowding problem

  • In high dimensions a point can have many neighbors that are all about equally far from it. In 2-D there is not room for them
  • With a Gaussian in the map (SNE), moderately distant pairs look very dissimilar, so the optimizer pulls everything into one crowded blob
  • The Student-t tail decays polynomially: pairs at moderate distance can sit far apart in the map at almost no cost, which opens gaps between clusters

Illustrative kernels: Gaussian vs Student-t (1 degree of freedom), both scaled to 1 at distance 0.

Wattenberg, Viégas, and Johnson, 2016

t-SNE: why it is easy to misread

  • Wattenberg et al. write “A popular method for exploring high-dimensional data is something called t-SNE… it has an almost magical ability to create compelling two-dimensional “maps” from data with hundreds or even thousands of dimensions. Although impressive, these images can be tempting to misread.”

  • Wattenberg et al.: “The algorithm is non-linear and adapts to the underlying data, performing different transformations on different regions. Those differences can be a major source of confusion.”

  • Wattenberg et al.: “A second feature of t-SNE is a tuneable parameter, “perplexity,” which says (loosely) how to balance attention between local and global aspects of your data. The parameter is, in a sense, a guess about the number of close neighbors each point has. The perplexity value has a complex effect on the resulting pictures.”

t-SNE: perplexity

“Those hyperparameters really matter”

Try it: perplexity on 1,797 digits

  • Same data and seed; only the perplexity changes
  • At 5 the groups are loose and fragmented; 30 and 100 give ten clear groups; at 500 (more than a quarter of the dataset) they press into each other
  • Which groups end up next to each other changes from panel to panel

t-SNE: iterations

How much of a difference do the number of steps and the learning rate make?

t-SNE: cluster sizes

“Cluster sizes in a t-SNE plot mean nothing”

t-SNE: distances between clusters

“Distances between clusters might not mean anything”

Try it: same perplexity, different random start

  • Same data, same perplexity (30), random initialization; only the seed changes
  • The same ten groups appear each time, but the arrangement changes
  • Digit 0 (blue) sits at the bottom, the top left, and the far right

t-SNE: random noise

“Random noise doesn’t always look random.”

t-SNE: topology

“For topology, you may need more than one plot”

Topomap (Doraiswamy et al)

Topomap preserves the 0-dimensional persistence diagram of the Rips filtration of the high-dimensional data.

Understanding UMAP (Coenen & Pearce)

UMAP

  • Fast: 70,000 MNIST images (784 dimensions) in under 3 minutes, against 45 minutes for scikit-learn’s t-SNE
  • Reported to preserve global structure better than t-SNE; later work credits much of this to initialization
  • Shown: Fashion-MNIST in 3-D, UMAP left, t-SNE right

UMAP

UMAP, like t-SNE, is a graph layout algorithm: it arranges points in 2-D so that a neighbor graph is preserved.

UMAP parameters

  • n_neighbors - the number of approximate nearest neighbors used to construct the initial high-dimensional graph.

  • min_dist - the minimum distance between points in low-dimensional space.

UMAP parameters

  • n_neighbors - the number of approximate nearest neighbors used to construct the initial high-dimensional graph.

  • min_dist - the minimum distance between points in low-dimensional space.

UMAP parameters

  • n_neighbors - the number of approximate nearest neighbors used to construct the initial high-dimensional graph.

  • min_dist - the minimum distance between points in low-dimensional space.

Try it: UMAP n_neighbors × min_dist

  • Rows: min_dist 0.0 vs 0.5. Columns: n_neighbors 5, 15, 50. min_dist changes how tightly points pack; n_neighbors changes how the groups are laid out relative to each other

UMAP

  • “However, it’s important to note that, because UMAP and t-SNE both necessarily warp the high-dimensional shape of the data when projecting to lower dimensions, any given axis or distance in lower dimensions still isn’t directly interpretable in the way of techniques such as PCA.”

  • Suggested reading: https://pair-code.github.io/understanding-umap/supplement.html

    • “Most dimensionality reduction algorithms fit into either one of two broad categories: Matrix factorization (such as PCA) or Graph layout (such as t-SNE).”
    • “At its core, UMAP is a graph layout algorithm, very similar to t-SNE, but with a number of key theoretical underpinnings that give the algorithm a more solid footing.”

UMAP

PCA, t-SNE or UMAP: which one when?

PCA t-SNE UMAP
Kind linear non-linear, neighbor graph + KL divergence non-linear, fuzzy neighbor graph
Keeps global variance local neighborhoods local neighborhoods, some coarse layout
Axes and distances mean something? yes: axes are directions in the data no: sizes and gaps are artifacts no: gaps are not reliable
Knobs number of components perplexity, steps, learning rate n_neighbors, min_dist
Repeatable? yes depends on initialization and seed depends on seed
New points transform refit transform
Reach for it to get a first look, denoise, preprocess see local cluster structure on small and medium data see structure on larger data, reuse the mapping

Is this projection any good?

  • Score a projection by checking whether neighborhoods survive: for each point, compare its k nearest neighbors in the original space with its k nearest neighbors in the map
  • Trustworthiness: are the neighbors in the map real neighbors? It penalizes false neighbors: points that look close in the map but were far apart in the data
  • Continuity: were the real neighbors kept? It penalizes tears: points that were close in the data but ended up far apart in the map
  • Both run from 0 to 1 (1 is perfect). In scikit-learn: trustworthiness(X, X_map, n_neighbors=k); continuity is the same function with the two spaces swapped
  • Both are local: they say nothing about the distances between clusters

T(k) = 1 − 2 / (N·k·(2N − 3k − 1)) · Σi Σj ∈ Ui (r(i,j) − k)

Ui = false neighbors of i (in its map neighborhood, not in its data neighborhood); r(i,j) = rank of j among i’s neighbors in the original space

Four projections of the digits, scored

But the score barely moves with perplexity

  • Perplexity 5 to 500 stays between 0.98 and 0.99, although the maps on the earlier slides look quite different. The metric separates methods (dashed lines: PCA, LLE) but is too coarse to pick a perplexity, and it cannot see cluster sizes or the gaps between clusters

Before you trust a projection

  1. Vary the settings: several perplexities (5 to 100) or n_neighbors (5 to 50), and at least two seeds. Keep only what is stable
  2. Do not read cluster size, cluster density, or the distance between clusters
  3. Compare with a baseline: PCA, and a noise dataset of the same size. Do the “clusters” appear there too?
  4. Score it: trustworthiness and continuity; if you have labels, how well do they predict from the map (for example k-NN accuracy)?
  5. Report it: method, parameters, seed and preprocessing, in the caption
  6. Use it to ask questions of the original data, not as evidence on its own

What about user interaction?

Steering a projection

  • Steerable methods (the check marks in the table: LSP, PLMP, PLP, LAMP) let the user influence the layout instead of accepting one static map
  • A common recipe: pick a small set of control points, place them where you want them in 2-D, and position the remaining points relative to them
  • Interactions follow from that: drag a point, group points, change a parameter and see the map update
  • Questions to ask of any interactive projection in a project: what can the user change, and what stays fixed?

Recommended reading