$$ \newcommand{\dint}{\mathrm{d}} \newcommand{\vphi}{\boldsymbol{\phi}} \newcommand{\vpi}{\boldsymbol{\pi}} \newcommand{\vpsi}{\boldsymbol{\psi}} \newcommand{\vomg}{\boldsymbol{\omega}} \newcommand{\vsigma}{\boldsymbol{\sigma}} \newcommand{\vzeta}{\boldsymbol{\zeta}} \renewcommand{\vx}{\mathbf{x}} \renewcommand{\vy}{\mathbf{y}} \renewcommand{\vz}{\mathbf{z}} \renewcommand{\vh}{\mathbf{h}} \renewcommand{\b}{\mathbf} \renewcommand{\vec}{\mathrm{vec}} \newcommand{\vecemph}{\mathrm{vec}} \newcommand{\mvn}{\mathcal{MN}} \newcommand{\G}{\mathcal{G}} \newcommand{\M}{\mathcal{M}} \newcommand{\N}{\mathcal{N}} \newcommand{\S}{\mathcal{S}} \newcommand{\diag}[1]{\mathrm{diag}(#1)} \newcommand{\diagemph}[1]{\mathrm{diag}(#1)} \newcommand{\tr}[1]{\text{tr}(#1)} \renewcommand{\C}{\mathbb{C}} \renewcommand{\R}{\mathbb{R}} \renewcommand{\E}{\mathbb{E}} \newcommand{\D}{\mathcal{D}} \newcommand{\inner}[1]{\langle #1 \rangle} \newcommand{\innerbig}[1]{\left \langle #1 \right \rangle} \newcommand{\abs}[1]{\lvert #1 \rvert} \newcommand{\norm}[1]{\lVert #1 \rVert} \newcommand{\two}{\mathrm{II}} \newcommand{\GL}{\mathrm{GL}} \newcommand{\Id}{\mathrm{Id}} \newcommand{\grad}[1]{\mathrm{grad} \, #1} \newcommand{\gradat}[2]{\mathrm{grad} \, #1 \, \vert_{#2}} \newcommand{\Hess}[1]{\mathrm{Hess} \, #1} \newcommand{\T}{\text{T}} \newcommand{\dim}[1]{\mathrm{dim} \, #1} \newcommand{\partder}[2]{\frac{\partial #1}{\partial #2}} \newcommand{\rank}[1]{\mathrm{rank} \, #1} $$

Nonlinear dimensionality reduction

See high-dimensional data in the plane: PCA, t-SNE and UMAP built step by step, and applied to MNIST and to the features of a Keras network.

Learning goals: measure what a map preserves; build the affinities, cost and gradient of t-SNE; build the graph and loss of UMAP; optimize them with Keras; compare the methods and read their maps with care.

Context and objectives

Course

Seeing high-dimensional data

A handwritten digit of MNIST is a point of $\mathbb R^{784}$: one number per pixel. A learned representation of a network is a point of $\mathbb R^{64}$, or $\mathbb R^{4096}$ for a vision model. We can neither plot nor imagine such spaces, yet we constantly need to look at them: are the classes separated? do similar images end up close? is there an outlier, a mislabeled sample, a hidden subgroup?

The aim of dimensionality reduction for visualization is a map in the plane in which neighbours stay neighbours. The classical tool, PCA, is linear: it projects on the directions of largest variance. Images of digits do not lie near a plane; they lie near a curved, low-dimensional surface of $\mathbb R^{784}$ (the manifold hypothesis), and a linear projection squashes it: far-apart images land on top of each other. t-SNE (van der Maaten and Hinton, 2008) and UMAP (McInnes, Healy and Melville, 2018) are neighbour embedding methods: they describe, for every point, who its neighbours are in the original space, then move 2-D points until the same neighbourhoods appear on the map.

In this course you build both methods step by step, with small programs, on MNIST: PCA first, then every ingredient of t-SNE (affinities, perplexity, kernel, cost, gradient), an optimizer written by hand and a Keras one, then the ingredients of UMAP, and finally an application to the features learned by a Keras classifier, with a comparison of the two methods. You will also learn what these maps do not mean, which is as important as how to compute them.

Exercise

Objectives to carry out

  1. Project MNIST with PCA and quantify what a map must preserve, with neighbourhood metrics (Part 1).
  2. Compute the Gaussian affinities of t-SNE and tune the width of each point by the perplexity (Part 2).
  3. Write the low-dimensional affinities, the KL cost and its gradient, and check the gradient with TensorFlow (Part 3).
  4. Optimize a map by gradient descent with momentum, then with a Keras optimizer; test the early exaggeration (Part 4).
  5. Build UMAP’s fuzzy graph, fit its membership curve and minimize its loss with Keras (Part 5).
  6. Train a Keras classifier on MNIST, map its learned features and compare t-SNE with UMAP (Part 6).
  7. Explore perplexity, n_neighbors and min_dist, stability and new data (Part 7).
  8. Deliver a short report with numbers, figures and warnings (Part 8).

Each part starts with a short course (definitions, statements and proofs) and proposes small exercises with a light Python starting code (TO DO lines). When an exercise asks for a plot, the expected display is shown before the correction. The correction, folded just after, is commented line by line. Try the exercise before you open it.

Course

How to work: environment

Install tensorflow==2.21.0 numpy matplotlib scipy scikit-learn umap-learn in an isolated environment (checked with Python 3.12, TensorFlow CPU 2.21 and umap-learn 0.6). MNIST is downloaded by keras.datasets.mnist.load_data(). We use 2,000 random training images for most exercises and 1,000 for the from-scratch optimizers, so that everything runs in a few seconds on a CPU. Run the blocks in order in one notebook or session: later exercises reuse earlier functions and variables.

PythonCode provided · imports, MNIST subset and a plotting helper
import numpy as npimport matplotlib.pyplot as pltimport tensorflow as tffrom tensorflow import kerasfrom tensorflow.keras import layersSEED = 0keras.utils.set_random_seed(SEED)np.set_printoptions(precision=4, suppress=True)(x_all, y_all), (x_test_all, y_test_all) = keras.datasets.mnist.load_data()      # 60,000 + 10,000 images of 28 x 28 pixelsrng = np.random.default_rng(SEED)pick = rng.choice(len(x_all), 2000, replace=False)X = x_all[pick].reshape(-1, 784).astype("float64") / 255.0                       # 2,000 images, 784 pixel values in [0, 1]y = y_all[pick]                                                                   # their digit labels (used only for colouring and checking)print("data:", X.shape, "labels:", np.bincount(y))def scatter(Y, labels, title, ax=None):    """2-D map coloured by digit."""    ax = ax or plt.gca()    for digit in range(10):        m = labels == digit        ax.scatter(Y[m, 0], Y[m, 1], s=6, color=plt.cm.tab10(digit), label=str(digit))    ax.set_title(title); ax.set_xticks([]); ax.set_yticks([])    ax.legend(markerscale=2, fontsize=7, ncol=2, loc="best")

Part 1 · Why a linear projection is not enough

Course

PCA: the best linear map

DefinitionPrincipal component analysis

Let $X_c\in\mathbb R^{n\times d}$ be the data matrix with the mean of each column removed, and $X_c=U\Sigma V^{\top}$ its singular value decomposition. The principal directions are the columns $v_1,v_2,\dots$ of $V$, the principal components of a point $x$ are its coordinates $v_k^{\top}x$, and the 2-D PCA map is $Y=X_cV_2$ with $V_2=(v_1\,v_2)$. The share of variance carried by direction $k$ is $\sigma_k^2/\sum_l\sigma_l^2$.

PropositionThe first principal direction maximizes the variance

Among all unit vectors $v$, the variance of the projections $X_cv$ is largest for $v=v_1$, and it equals $\sigma_1^2/n$ (up to the normalization $1/n$ of the variance). More generally $V_2$ is the best 2-D orthogonal projection in the sense of the mean squared reconstruction error (Eckart–Young).

Proof

For a unit vector $v$, $\|X_cv\|^2=v^{\top}X_c^{\top}X_cv$ is a Rayleigh quotient of the symmetric matrix $X_c^{\top}X_c=V\Sigma^2V^{\top}$. Writing $v=\sum_kc_kv_k$ with $\sum c_k^2=1$ gives $\|X_cv\|^2=\sum_kc_k^2\sigma_k^2\le\sigma_1^2$, with equality for $v=v_1$. For two dimensions, the reconstruction error of an orthogonal projection $P$ of rank 2 is $\|X_c\|_F^2-\|X_cP\|_F^2$, and the same argument applied to the trace $\operatorname{tr}(P\,X_c^{\top}X_c)$ shows that it is minimal for the projection on $\operatorname{span}(v_1,v_2)$ (Ky Fan). $\square$

PCA is the optimal linear map for the criterion of variance. It is useful (fast, deterministic, invertible), but its criterion is global: it cares about the large distances. For a map that must keep neighbours, variance is the wrong target.

Exercise

Exercise 1.1 · PCA of MNIST

  1. Center the 2,000 images and compute the singular value decomposition.
  2. Project on the two first principal directions and compute the share of variance they carry, and the number of components needed for 90% of the variance.
  3. Plot the map, coloured by digit.
PythonStarting code · PCA
Xc = ...  # TO DO: center the data: subtract the mean imageU, S, Vt = np.linalg.svd(Xc, full_matrices=False)        # singular value decomposition of the centered dataY_pca = ...  # TO DO: coordinates on the two first principal directionsexplained = ...  # TO DO: share of the variance carried by each directionprint("variance explained by the two first components:", explained[:2].sum())print("components needed for 90% of the variance:", int(np.searchsorted(np.cumsum(explained), 0.90)) + 1)scatter(Y_pca, y, "PCA of 2,000 MNIST images")plt.show()
Expected display: what your code should plot
Expected display of the exercise
Show the correction
PythonComplete solution · SVD and the PCA map
# PCA works on centered data: subtract the mean image from every image.Xc = X - X.mean(axis=0)  # center the data: subtract the mean image# The rows of Vt are the principal directions; S holds the singular values (S**2 / n are the variances along them).U, S, Vt = np.linalg.svd(Xc, full_matrices=False)        # singular value decomposition of the centered data# Coordinates of each image on the first two principal directions: a 2,000 x 2 map.Y_pca = Xc @ Vt[:2].T  # coordinates on the two first principal directions# Share of the total variance carried by each direction.explained = S**2 / np.sum(S**2)  # share of the variance carried by each directionprint("variance explained by the two first components:", explained[:2].sum())print("components needed for 90% of the variance:", int(np.searchsorted(np.cumsum(explained), 0.90)) + 1)scatter(Y_pca, y, "PCA of 2,000 MNIST images")plt.show()

The two first components carry only $16.9\%$ of the variance and $83$ components are needed for $90\%$: MNIST is not close to a plane. In the map the classes overlap heavily; only the zeros and the ones are somewhat isolated.

Course

What must a good map preserve?

DefinitionNeighbourhood preservation

Let $N_k^{\text{high}}(i)$ be the set of the $k$ nearest neighbours of point $i$ in the original space and $N_k^{\text{map}}(i)$ in the map. The neighbour overlap is $\dfrac1{nk}\sum_i|N_k^{\text{high}}(i)\cap N_k^{\text{map}}(i)|\in[0,1]$. The $k$-NN accuracy is the fraction of points whose label is the majority label of their $k$ neighbours in the map. The trustworthiness (Venna and Kaski) penalizes the points that appear as neighbours in the map without being neighbours in the original space.

The first metric compares a map with the original space; the second one uses the labels, which the methods never see, to check that the structure of the map is meaningful. The accuracy of the same $k$-NN rule in the original 784-d space is the reference to compare with.

Exercise

Exercise 1.2 · measure a map

  1. Write the matrix of squared distances of a data set, from $|a|^2+|b|^2-2a\cdot b$.
  2. Write the neighbour overlap and the $k$-NN accuracy of a map.
  3. Evaluate the PCA map of Exercise 1.1, and the 5-NN accuracy in the original space.
PythonStarting code · neighbourhood metrics
def pairwise_sq_dists(A):    sq = (A ** 2).sum(axis=1)    D = ...  # TO DO: |a|^2 + |b|^2 - 2 a.b for every pair    np.fill_diagonal(D, 0.0)    return np.maximum(D, 0.0)                              # rounding errors may give tiny negative valuesdef knn_indices(D, k):    Dm = D.copy()    np.fill_diagonal(Dm, np.inf)                           # a point is not its own neighbour    return ...  # TO DO: indices of the k smallest distances in each rowdef knn_overlap(D_high, D_low, k=10):    a, b = knn_indices(D_high, k), knn_indices(D_low, k)    return ...  # TO DO: share of the k neighbours kept in 2-Ddef knn_accuracy(D_low, labels, k=5):    nn = knn_indices(D_low, k)    votes = np.array([np.bincount(labels[row], minlength=10).argmax() for row in nn])   # majority vote of the neighbours    return float(np.mean(votes == labels))D_high = pairwise_sq_dists(X)D_pca = pairwise_sq_dists(Y_pca)print("neighbours kept by PCA (k = 10):", knn_overlap(D_high, D_pca, 10))print("5-NN accuracy of the digits in the PCA map:", knn_accuracy(D_pca, y, 5), "| in the 784-d space:", knn_accuracy(D_high, y, 5))
Show the correction
PythonComplete solution · distances, overlap and k-NN accuracy
# All the squared distances at once, with no loop: |a - b|^2 = |a|^2 + |b|^2 - 2 a.b (a matrix product for the cross terms).def pairwise_sq_dists(A):    sq = (A ** 2).sum(axis=1)    D = sq[:, None] + sq[None, :] - 2 * A @ A.T  # |a|^2 + |b|^2 - 2 a.b for every pair    np.fill_diagonal(D, 0.0)    # Rounding errors can give tiny negative values: clip them to 0.    return np.maximum(D, 0.0)                              # rounding errors may give tiny negative values# Sort each row and keep the k nearest points; the diagonal is set to infinity so that a point is not its own neighbour.def knn_indices(D, k):    Dm = D.copy()    np.fill_diagonal(Dm, np.inf)                           # a point is not its own neighbour    return np.argsort(Dm, axis=1)[:, :k]  # indices of the k smallest distances in each row# For each point, the share of its k neighbours in the original space that are also its k neighbours in the map.def knn_overlap(D_high, D_low, k=10):    a, b = knn_indices(D_high, k), knn_indices(D_low, k)    return float(np.mean([len(set(a[i]) & set(b[i])) / k for i in range(len(a))]))  # share of the k neighbours kept in 2-D# Leave-one-out k-NN classification: each point takes the majority digit of its neighbours; the point itself is excluded.def knn_accuracy(D_low, labels, k=5):    nn = knn_indices(D_low, k)    votes = np.array([np.bincount(labels[row], minlength=10).argmax() for row in nn])   # majority vote of the neighbours    return float(np.mean(votes == labels))D_high = pairwise_sq_dists(X)D_pca = pairwise_sq_dists(Y_pca)print("neighbours kept by PCA (k = 10):", knn_overlap(D_high, D_pca, 10))print("5-NN accuracy of the digits in the PCA map:", knn_accuracy(D_pca, y, 5), "| in the 784-d space:", knn_accuracy(D_high, y, 5))

The PCA map keeps only $7.8\%$ of the 10 nearest neighbours, and its 5-NN accuracy is $0.427$, against $0.900$ in the original 784-d space: the information is there, but a linear projection to 2-D loses it. This is the problem that t-SNE and UMAP address.

Part 2 · t-SNE, step 1: from distances to probabilities

Course

t-SNE, step 1: who are my neighbours?

t-SNE turns distances into probabilities of being neighbours. Around a point $x_i$, draw a Gaussian of width $\sigma_i$ and let each other point be picked with a probability proportional to its Gaussian weight:

DefinitionConditional probabilities and perplexity

$\displaystyle p_{j|i}=\frac{\exp\!\big(-\|x_i-x_j\|^2/2\sigma_i^2\big)}{\sum_{k\ne i}\exp\!\big(-\|x_i-x_k\|^2/2\sigma_i^2\big)},\quad p_{i|i}=0.$ The perplexity of the distribution $p_{\cdot|i}$ is $\operatorname{Perp}(i)=2^{H(p_{\cdot|i})}$ with $H=-\sum_jp_{j|i}\log_2p_{j|i}$ its Shannon entropy in bits: the effective number of neighbours of $i$. A uniform distribution on $m$ points has perplexity $m$.

A small $\sigma_i$ concentrates the probability on the nearest point (perplexity close to 1); a large one spreads it (perplexity close to $n-1$). The user chooses one perplexity, typically 5 to 50, and the width of each point is found to match it: dense regions get a small $\sigma_i$, sparse regions a large one.

The t-SNE pipeline: Gaussian affinities of the data, Student-t affinities of the map, minimization of the KL divergence over the map coordinates
The two steps of t-SNE. The data are fixed; the 2-D coordinates are the unknowns.
PropositionThe perplexity increases with sigma

For a fixed point $i$, the entropy $H(p_{\cdot|i})$ is a non-decreasing function of $\sigma_i$, strictly increasing unless all the distances from $x_i$ are equal. Hence the equation $\operatorname{Perp}=\text{target}$ has a unique solution $\sigma_i$ that can be found by bisection.

Proof

Write $\beta=1/(2\sigma_i^2)$, $D_j=\|x_i-x_j\|^2$, $Z(\beta)=\sum_je^{-\beta D_j}$ and $p_j=e^{-\beta D_j}/Z$. In nats, $H=-\sum p_j\log p_j=\beta\,\mathbb E_p[D]+\log Z$. Since $\dfrac{d\log Z}{d\beta}=-\mathbb E_p[D]$ and $\dfrac{d\,\mathbb E_p[D]}{d\beta}=-\operatorname{Var}_p(D)$, we get $\dfrac{dH}{d\beta}=\mathbb E_p[D]+\beta\big(-\operatorname{Var}_p(D)\big)-\mathbb E_p[D]=-\beta\operatorname{Var}_p(D)\le0$. So $H$ decreases when $\beta$ grows, that is, increases with $\sigma$, strictly when the variance of $D$ under $p$ is positive. $\square$

Finally the probabilities are symmetrized, so that every point takes part in the cost: $p_{ij}=\dfrac{p_{j|i}+p_{i|j}}{2n}$.

PropositionSymmetrized affinities

$\sum_{i\ne j}p_{ij}=1$, $p_{ij}=p_{ji}$ and $\sum_jp_{ij}\ge\dfrac1{2n}$ for every $i$.

Proof

Symmetry is clear. $\sum_{i,j}p_{j|i}=n$ because each row sums to 1, so $\sum_{i,j}p_{ij}=(n+n)/(2n)=1$. For a fixed $i$, $\sum_jp_{ij}=\dfrac{\sum_jp_{j|i}+\sum_jp_{i|j}}{2n}=\dfrac{1+\sum_jp_{i|j}}{2n}\ge\dfrac1{2n}$. $\square$

The last inequality is the reason for the symmetrization: even an outlier, which nobody picks as a neighbour, keeps a total weight of at least $1/(2n)$ and is therefore placed on the map.

Exercise

Exercise 2.1 · conditional probabilities

  1. Write $p_{j|i}$ for one point $i$ and a given $\sigma$, with the exponentials stabilized.
  2. For image 0 and $\sigma=0.5,2,5,20$, print the sum, the three largest probabilities and the entropy in bits.
  3. Explain what happens at small and large $\sigma$.
PythonStarting code · Gaussian affinities
def conditional_p(D_row, i, sigma):    """p_{j|i}: probability that i picks j as a neighbour, for a Gaussian of standard deviation sigma around x_i."""    logits = ...  # TO DO: -|x_i - x_j|^2 / (2 sigma^2)    logits[i] = -np.inf                                     # a point never picks itself    logits = logits - logits.max()                          # stabilize the exponential    p = np.exp(logits)    return ...  # TO DO: normalize so that the probabilities sum to 1i = 0print("squared distances from image 0: nearest", np.sort(D_high[i])[1], " median", np.median(D_high[i]))for sigma in [0.5, 2.0, 5.0, 20.0]:    p = conditional_p(D_high[i], i, sigma)    top = np.sort(p)[::-1][:3]    entropy = -np.sum(p[p > 0] * np.log2(p[p > 0]))    print(f"sigma = {sigma:5.1f}: sum = {p.sum():.3f}, three largest = {top}, entropy = {entropy:.2f} bits")
Show the correction
PythonComplete solution · the effect of sigma
# p_{j|i}: a Gaussian centred on image i, evaluated at the other images and normalized to sum to 1.def conditional_p(D_row, i, sigma):    """p_{j|i}: probability that i picks j as a neighbour, for a Gaussian of standard deviation sigma around x_i."""    logits = -D_row / (2 * sigma ** 2)  # -|x_i - x_j|^2 / (2 sigma^2)    logits[i] = -np.inf                                     # a point never picks itself    # Subtracting the maximum does not change the normalized result and avoids overflow or all-zero exponentials.    logits = logits - logits.max()                          # stabilize the exponential    p = np.exp(logits)    return p / p.sum()  # normalize so that the probabilities sum to 1i = 0print("squared distances from image 0: nearest", np.sort(D_high[i])[1], " median", np.median(D_high[i]))for sigma in [0.5, 2.0, 5.0, 20.0]:    p = conditional_p(D_high[i], i, sigma)    top = np.sort(p)[::-1][:3]    entropy = -np.sum(p[p > 0] * np.log2(p[p > 0]))    print(f"sigma = {sigma:5.1f}: sum = {p.sum():.3f}, three largest = {top}, entropy = {entropy:.2f} bits")

At $\sigma=0.5$ one neighbour takes $92\%$ of the probability (entropy $0.43$ bit); at $\sigma=20$ all the 1,999 points have almost the same probability (entropy $10.96$ bits, the maximum $\log_2 1999$). In between, $\sigma$ controls how many neighbours count.

Exercise

Exercise 2.2 · find sigma by bisection

  1. Write the perplexity of a distribution, $2^H$.
  2. Write a bisection that finds, for each point, the $\sigma$ whose perplexity is 30 (the proposition says it is unique).
  3. Compute the probabilities of all the points and check the perplexities, then look at the range of $\sigma_i$.
PythonStarting code · perplexity and bisection
def perplexity(p):    H = ...  # TO DO: Shannon entropy in bits    return ...  # TO DO: perplexity = 2^H: the "effective number of neighbours"def sigma_for_perplexity(D_row, i, target=30.0, n_iter=60):    lo, hi = 1e-3, 1e3                                      # search interval for sigma    for _ in range(n_iter):        mid = np.sqrt(lo * hi)                              # geometric bisection: sigma spans several decades        if perplexity(conditional_p(D_row, i, mid)) > target:            hi = ...  # TO DO: too many effective neighbours: reduce sigma        else:            lo = ...  # TO DO: too few: increase sigma    return np.sqrt(lo * hi)n = len(X)sigmas = np.array([sigma_for_perplexity(D_high[i], i) for i in range(n)])P_cond = np.array([conditional_p(D_high[i], i, sigmas[i]) for i in range(n)])perps = np.array([perplexity(P_cond[i]) for i in range(n)])print("perplexity of every point: min", perps.min(), "max", perps.max())print("sigma_i quantiles (10%, 50%, 90%):", np.quantile(sigmas, [0.1, 0.5, 0.9]), "(dense regions get a small sigma)")
Show the correction
PythonComplete solution · one sigma per point
# 2 to the power of the entropy in bits: the effective number of neighbours.def perplexity(p):    H = -np.sum(p[p > 0] * np.log2(p[p > 0]))  # Shannon entropy in bits    return 2.0 ** H  # perplexity = 2^H: the "effective number of neighbours"def sigma_for_perplexity(D_row, i, target=30.0, n_iter=60):    lo, hi = 1e-3, 1e3                                      # search interval for sigma    for _ in range(n_iter):        # Bisection on a logarithmic scale, because sigma can vary over several orders of magnitude.        mid = np.sqrt(lo * hi)                              # geometric bisection: sigma spans several decades        if perplexity(conditional_p(D_row, i, mid)) > target:            hi = mid  # too many effective neighbours: reduce sigma        else:            lo = mid  # too few: increase sigma    return np.sqrt(lo * hi)n = len(X)# One sigma per point: the loop runs the bisection 2,000 times (about 2 s).sigmas = np.array([sigma_for_perplexity(D_high[i], i) for i in range(n)])P_cond = np.array([conditional_p(D_high[i], i, sigmas[i]) for i in range(n)])perps = np.array([perplexity(P_cond[i]) for i in range(n)])print("perplexity of every point: min", perps.min(), "max", perps.max())print("sigma_i quantiles (10%, 50%, 90%):", np.quantile(sigmas, [0.1, 0.5, 0.9]), "(dense regions get a small sigma)")

All the perplexities are $30$ to $10^{-12}$. The widths $\sigma_i$ have the quantiles $1.38,\ 1.71,\ 2.05$ (10%, 50%, 90%): points in dense regions of digit space use a narrower Gaussian than isolated ones.

Exercise

Exercise 2.3 · symmetrize

  1. Symmetrize the matrix of conditional probabilities and check that it sums to 1 and is symmetric.
  2. Check the lower bound $1/(2n)$ on the total weight of every point.
  3. Look at the five strongest neighbours of image 0 and their digits.
PythonStarting code · symmetrized affinities
P = ...  # TO DO: symmetrize: p_ij = (p_{j|i} + p_{i|j}) / (2n)print("sum of P:", P.sum(), "| symmetric:", np.allclose(P, P.T))print("smallest total weight of a point:", P.sum(axis=1).min(), ">= 1/(2n) =", 1 / (2 * n))nn = ...  # TO DO: the five strongest neighbours of image 0print("strongest neighbours of image 0:", nn, "digits:", y[nn], "(image 0 is a", y[0], ")")
Show the correction
PythonComplete solution · the matrix P
# Symmetrization: p_ij = (p_{j|i} + p_{i|j}) / (2n); the factor 2n makes the whole matrix sum to 1.P = (P_cond + P_cond.T) / (2 * n)  # symmetrize: p_ij = (p_{j|i} + p_{i|j}) / (2n)print("sum of P:", P.sum(), "| symmetric:", np.allclose(P, P.T))print("smallest total weight of a point:", P.sum(axis=1).min(), ">= 1/(2n) =", 1 / (2 * n))nn = np.argsort(-P[0])[:5]  # the five strongest neighbours of image 0print("strongest neighbours of image 0:", nn, "digits:", y[nn], "(image 0 is a", y[0], ")")

The matrix $P$ sums to 1, it is symmetric, and the smallest total weight of a point is $2.514\cdot10^{-4}$, just above $1/(2n)=2.5\cdot10^{-4}$. Four of the five strongest neighbours of image 0 (a zero) are zeros; the fifth is a six: the neighbourhoods follow the digits, with a few exceptions.

Part 3 · t-SNE, step 2: the map, the cost and its gradient

Course

t-SNE, step 2: the map and its cost

We now look for points $y_1,\dots,y_n\in\mathbb R^2$ that have the same neighbourhoods. In the plane we cannot use a Gaussian: this is the crowding problem. In high dimension a point can have many moderately distant neighbours at the same time, because the volume of a ball grows very fast with its radius; in 2-D there is not enough room, and these neighbours are squeezed into a ring around the point, where they collapse on each other. t-SNE therefore uses, in the map, a distribution with heavy tails, the Student-$t$ distribution with one degree of freedom, which allows moderately distant points to be placed far apart.

Gaussian kernel and Student-t kernel as a function of the distance: the Student-t tail is heavier
A Gaussian decays like $e^{-d^2/2\sigma^2}$, the Student-$t$ kernel only like $1/d^2$.
DefinitionLow-dimensional affinities and cost

$\displaystyle q_{ij}=\frac{(1+\|y_i-y_j\|^2)^{-1}}{\sum_{k\ne l}(1+\|y_k-y_l\|^2)^{-1}},\quad q_{ii}=0,$ and the cost is the Kullback–Leibler divergence $C(Y)=\mathrm{KL}(P\|Q)=\sum_{i\ne j}p_{ij}\log\dfrac{p_{ij}}{q_{ij}}.$

The KL divergence is not symmetric, and this is on purpose: placing neighbours far apart ($p_{ij}$ large, $q_{ij}$ small) is expensive, while placing non-neighbours close ($p_{ij}$ small, $q_{ij}$ large) is cheap. The map keeps local structure at the price of the global one.

TheoremGradient of the t-SNE cost

With $\operatorname{num}_{ij}=(1+\|y_i-y_j\|^2)^{-1}$,

\[\frac{\partial C}{\partial y_i}=4\sum_{j\ne i}(p_{ij}-q_{ij})\,\operatorname{num}_{ij}\,(y_i-y_j).\]
Proof

Since $\sum p_{kl}=1$, $C=\text{const}-\sum_{k\ne l}p_{kl}\log\operatorname{num}_{kl}+\log Z$ with $Z=\sum_{k\ne l}\operatorname{num}_{kl}$. The point $y_i$ appears in the pairs $(i,j)$ and $(j,i)$. First, $\dfrac{\partial\log\operatorname{num}_{ij}}{\partial y_i}=-2\operatorname{num}_{ij}(y_i-y_j)$, so the second term contributes $+4\sum_jp_{ij}\operatorname{num}_{ij}(y_i-y_j)$. Second, $\dfrac{\partial\operatorname{num}_{ij}}{\partial y_i}=-2\operatorname{num}_{ij}^2(y_i-y_j)$, so $\dfrac{\partial\log Z}{\partial y_i}=\dfrac{2}{Z}\sum_j\dfrac{\partial\operatorname{num}_{ij}}{\partial y_i}=-4\sum_jq_{ij}\operatorname{num}_{ij}(y_i-y_j)$, using $\operatorname{num}_{ij}/Z=q_{ij}$. Adding the two contributions gives the formula. $\square$

Read the gradient as a system of springs: the point $i$ is attracted by $j$ when $p_{ij}>q_{ij}$ (the map has them too far apart) and repelled when $q_{ij}>p_{ij}$ (too close).

Exercise

Exercise 3.1 · the low-dimensional affinities and the cost

  1. Write the matrix $Q$ and the matrix $\operatorname{num}$ of a map $Y$ with the Student-$t$ kernel.
  2. Write $\mathrm{KL}(P\|Q)$.
  3. Evaluate the cost of a tiny random map and of the PCA map rescaled to several standard deviations.
PythonStarting code · Q and the KL cost
def q_matrix(Y):    D = pairwise_sq_dists(Y)    num = ...  # TO DO: Student-t kernel with one degree of freedom    np.fill_diagonal(num, 0.0)    return ...  # TO DO: normalize over all pairs: q_ijdef kl(P, Q):    m = P > 0    return ...  # TO DO: KL(P || Q) = sum p_ij log(p_ij / q_ij)rng2 = np.random.default_rng(1)Y_rand = 1e-2 * rng2.normal(size=(n, 2))print("KL(P||Q) for a tiny random map:", kl(P, q_matrix(Y_rand)[0]))for scale in [0.01, 1.0, 10.0, 30.0]:    Y_scaled = ...  # TO DO: the same PCA map, rescaled to a standard deviation of `scale`    print(f"PCA map of standard deviation {scale:5.2f}: KL(P||Q) = {kl(P, q_matrix(Y_scaled)[0]):.3f}")print("KL(P||P) =", round(kl(P, P), 6), "(0 when Q = P)")
Show the correction
PythonComplete solution · the cost of a few maps
# The matrix Q of the map; num is returned too because the gradient reuses it.def q_matrix(Y):    D = pairwise_sq_dists(Y)    num = 1.0 / (1.0 + D)  # Student-t kernel with one degree of freedom    np.fill_diagonal(num, 0.0)    return num / num.sum(), num  # normalize over all pairs: q_ij# KL(P || Q); only the entries where p_ij > 0 contribute, and Q is floored to avoid log(0).def kl(P, Q):    m = P > 0    return float(np.sum(P[m] * np.log(P[m] / np.maximum(Q[m], 1e-12))))  # KL(P || Q) = sum p_ij log(p_ij / q_ij)rng2 = np.random.default_rng(1)Y_rand = 1e-2 * rng2.normal(size=(n, 2))print("KL(P||Q) for a tiny random map:", kl(P, q_matrix(Y_rand)[0]))for scale in [0.01, 1.0, 10.0, 30.0]:    Y_scaled = Y_pca / Y_pca.std(axis=0) * scale  # the same PCA map, rescaled to a standard deviation of `scale`    print(f"PCA map of standard deviation {scale:5.2f}: KL(P||Q) = {kl(P, q_matrix(Y_scaled)[0]):.3f}")print("KL(P||P) =", round(kl(P, P), 6), "(0 when Q = P)")

A tiny random map has $\mathrm{KL}=4.01$: all the $q_{ij}$ are equal. The PCA map has $3.26$, $2.96$ and $3.21$ at standard deviations $1$, $10$ and $30$: the scale of the map matters, because the kernel decays with the distance. $\mathrm{KL}(P\|P)=0$, as expected.

Exercise

Exercise 3.2 · check the gradient

  1. Write the gradient of the theorem in matrix form.
  2. Write the cost with TensorFlow operations and differentiate it with tf.GradientTape.
  3. Compare the two with each other and with central finite differences, on 60 images.
PythonStarting code · analytic gradient, automatic gradient, finite differences
def gradient(P, Y):    Q, num = q_matrix(Y)    PQ = ...  # TO DO: (p_ij - q_ij) / (1 + |y_i - y_j|^2)    return ...  # TO DO: 4 sum_j (p_ij - q_ij)(y_i - y_j)/(1 + |y_i - y_j|^2), in matrix formdef kl_tf(P_tf, Y):    D = tf.reduce_sum((Y[:, None, :] - Y[None, :, :]) ** 2, axis=-1)    num = (1.0 / (1.0 + D)) * (1.0 - tf.eye(tf.shape(Y)[0], dtype=Y.dtype))    Q = num / tf.reduce_sum(num)    return tf.reduce_sum(P_tf * (tf.math.log(P_tf + 1e-12) - tf.math.log(Q + 1e-12)))m = 60                                                      # a small subset so that finite differences are cheapXs = X[:m]; Ds = pairwise_sq_dists(Xs)sig = np.array([sigma_for_perplexity(Ds[i], i, target=8.0) for i in range(m)])Ps = np.array([conditional_p(Ds[i], i, sig[i]) for i in range(m)]); Ps = (Ps + Ps.T) / (2 * m)Ys = np.random.default_rng(2).normal(size=(m, 2))g_formula = gradient(Ps, Ys)Yv = tf.Variable(Ys)with tf.GradientTape() as tape:    loss = ...  # TO DO: the same cost written with TensorFlow operationsg_tape = ...  # TO DO: automatic differentiation of the costprint("formula against GradientTape: max difference", np.abs(g_formula - g_tape).max())h, g_fd = 1e-6, np.zeros(4)for k, (a, b) in enumerate([(0, 0), (0, 1), (7, 0), (30, 1)]):    Yp, Ym = Ys.copy(), Ys.copy(); Yp[a, b] += h; Ym[a, b] -= h    g_fd[k] = ...  # TO DO: central finite difference of the costprint("finite differences:", g_fd, "| formula:", np.array([g_formula[0, 0], g_formula[0, 1], g_formula[7, 0], g_formula[30, 1]]))
Show the correction
PythonComplete solution · three ways to compute the same gradient
# Matrix form of the sum: diag(row sums of PQ) - PQ, multiplied by Y, gives sum_j PQ_ij (y_i - y_j) for every i.def gradient(P, Y):    Q, num = q_matrix(Y)    PQ = (P - Q) * num  # (p_ij - q_ij) / (1 + |y_i - y_j|^2)    return 4.0 * (np.diag(PQ.sum(axis=1)) - PQ) @ Y  # 4 sum_j (p_ij - q_ij)(y_i - y_j)/(1 + |y_i - y_j|^2), in matrix form# The same cost with TensorFlow operations, so that tf.GradientTape can differentiate it. The eye() removes the diagonal.def kl_tf(P_tf, Y):    D = tf.reduce_sum((Y[:, None, :] - Y[None, :, :]) ** 2, axis=-1)    num = (1.0 / (1.0 + D)) * (1.0 - tf.eye(tf.shape(Y)[0], dtype=Y.dtype))    Q = num / tf.reduce_sum(num)    return tf.reduce_sum(P_tf * (tf.math.log(P_tf + 1e-12) - tf.math.log(Q + 1e-12)))m = 60                                                      # a small subset so that finite differences are cheapXs = X[:m]; Ds = pairwise_sq_dists(Xs)sig = np.array([sigma_for_perplexity(Ds[i], i, target=8.0) for i in range(m)])Ps = np.array([conditional_p(Ds[i], i, sig[i]) for i in range(m)]); Ps = (Ps + Ps.T) / (2 * m)Ys = np.random.default_rng(2).normal(size=(m, 2))g_formula = gradient(Ps, Ys)Yv = tf.Variable(Ys)with tf.GradientTape() as tape:    loss = kl_tf(tf.constant(Ps), Yv)  # the same cost written with TensorFlow operations# Automatic differentiation: no formula needed.g_tape = tape.gradient(loss, Yv).numpy()  # automatic differentiation of the costprint("formula against GradientTape: max difference", np.abs(g_formula - g_tape).max())h, g_fd = 1e-6, np.zeros(4)for k, (a, b) in enumerate([(0, 0), (0, 1), (7, 0), (30, 1)]):    Yp, Ym = Ys.copy(), Ys.copy(); Yp[a, b] += h; Ym[a, b] -= h    g_fd[k] = (kl(Ps, q_matrix(Yp)[0]) - kl(Ps, q_matrix(Ym)[0])) / (2 * h)  # central finite difference of the costprint("finite differences:", g_fd, "| formula:", np.array([g_formula[0, 0], g_formula[0, 1], g_formula[7, 0], g_formula[30, 1]]))

The formula and the automatic differentiation agree to $3.7\cdot10^{-10}$, and the finite differences give the same four components $(0.0083,\ -0.0039,\ -0.0027,\ 0.0020)$. Automatic differentiation is the practical way to optimize any cost of this kind, which is what Keras does in the next part.

Part 4 · Optimizing a map: from scratch and with Keras

Course

Moving the points: gradient descent, momentum and exaggeration

The unknowns of t-SNE are the $2n$ coordinates, and the cost is smooth, so we minimize it by gradient descent. Starting from small random coordinates, the update with momentum is $y^{(t+1)}=y^{(t)}-\eta\,\nabla C\big(y^{(t)}\big)+\alpha_t\big(y^{(t)}-y^{(t-1)}\big)$, with a learning rate $\eta$ and a momentum $\alpha_t$ that grows from $0.5$ to $0.8$. The original paper adds early exaggeration: during the first iterations all the $p_{ij}$ are multiplied by a factor (12 in the paper), which strengthens the attraction and lets the clusters move freely before they settle. The cost is non-convex: the result depends on the initialization and on the optimizer.

Because the gradient is obtained by automatic differentiation, any optimizer of Keras can minimize the cost with the coordinates as the tf.Variable to train: this is the same GradientTape and optimizer.apply_gradients as in the course on neural networks, with the points in place of the weights.

Exercise

Exercise 4.1 · t-SNE from scratch

  1. Write the iteration: exaggerated $P$ during the first 100 iterations, the gradient, momentum $0.5$ then $0.8$, and a recentering of the map.
  2. Run it on 1,000 images for 500 iterations and print the true cost every 50 iterations.
  3. Evaluate the neighbour overlap and the 5-NN accuracy of the map and plot it.
PythonStarting code · gradient descent with momentum
def tsne_numpy(P, n_iter=500, lr=200.0, exaggeration=12.0, exag_iters=100, seed=0):    r = np.random.default_rng(seed)    Y = 1e-4 * r.normal(size=(len(P), 2))                    # tiny random start    Y_prev = Y.copy()    history = []    for t in range(n_iter):        Pt = ...  # TO DO: early exaggeration: attract strongly during the first iterations        Q, num = q_matrix(Y)        PQ = (Pt - Q) * num        grad = 4.0 * (np.diag(PQ.sum(axis=1)) - PQ) @ Y        momentum = 0.5 if t < 250 else 0.8                   # momentum grows once the layout is roughly set        Y_new = ...  # TO DO: gradient step with momentum        Y_prev, Y = Y, Y_new - Y_new.mean(axis=0)            # keep the map centred        if t % 50 == 0 or t == n_iter - 1:            history.append((t, kl(P, q_matrix(Y)[0])))       # the true cost, without exaggeration    return Y, historyn1 = 1000D1 = pairwise_sq_dists(X[:n1])s1 = np.array([sigma_for_perplexity(D1[i], i) for i in range(n1)])P1 = np.array([conditional_p(D1[i], i, s1[i]) for i in range(n1)]); P1 = (P1 + P1.T) / (2 * n1)Y1, hist1 = tsne_numpy(P1)print("KL along the iterations:", [(t, round(c, 3)) for t, c in hist1])D_low1 = pairwise_sq_dists(Y1)print("neighbours kept:", knn_overlap(D1, D_low1, 10), "| 5-NN digit accuracy in the map:", knn_accuracy(D_low1, y[:n1], 5))scatter(Y1, y[:n1], "t-SNE written from scratch (1,000 images)"); plt.show()
Expected display: what your code should plot
Expected display of the exercise
Show the correction
PythonComplete solution · a t-SNE written in 30 lines
# The whole algorithm: gradient of the cost, with momentum and early exaggeration.def tsne_numpy(P, n_iter=500, lr=200.0, exaggeration=12.0, exag_iters=100, seed=0):    r = np.random.default_rng(seed)    # A tiny random start, as in the original paper.    Y = 1e-4 * r.normal(size=(len(P), 2))                    # tiny random start    Y_prev = Y.copy()    history = []    for t in range(n_iter):        Pt = P * exaggeration if t < exag_iters else P  # early exaggeration: attract strongly during the first iterations        Q, num = q_matrix(Y)        PQ = (Pt - Q) * num        grad = 4.0 * (np.diag(PQ.sum(axis=1)) - PQ) @ Y        momentum = 0.5 if t < 250 else 0.8                   # momentum grows once the layout is roughly set        # Gradient step plus momentum (a fraction of the previous displacement).        Y_new = Y - lr * grad + momentum * (Y - Y_prev)  # gradient step with momentum        Y_prev, Y = Y, Y_new - Y_new.mean(axis=0)            # keep the map centred        if t % 50 == 0 or t == n_iter - 1:            history.append((t, kl(P, q_matrix(Y)[0])))       # the true cost, without exaggeration    return Y, historyn1 = 1000D1 = pairwise_sq_dists(X[:n1])s1 = np.array([sigma_for_perplexity(D1[i], i) for i in range(n1)])P1 = np.array([conditional_p(D1[i], i, s1[i]) for i in range(n1)]); P1 = (P1 + P1.T) / (2 * n1)Y1, hist1 = tsne_numpy(P1)print("KL along the iterations:", [(t, round(c, 3)) for t, c in hist1])D_low1 = pairwise_sq_dists(Y1)print("neighbours kept:", knn_overlap(D1, D_low1, 10), "| 5-NN digit accuracy in the map:", knn_accuracy(D_low1, y[:n1], 5))scatter(Y1, y[:n1], "t-SNE written from scratch (1,000 images)"); plt.show()

The true cost goes from $3.32$ to $1.54$ (it rises during the exaggerated phase, since it is measured without the exaggeration). The map keeps $48\%$ of the neighbours and has a 5-NN accuracy of $0.842$, but the digits are broken into several islands: 500 plain iterations are not enough to reach the quality of a tuned implementation (adaptive gains, more iterations).

Exercise

Exercise 4.2 · minimize the cost with a Keras optimizer

  1. Make the coordinates a tf.Variable and write the loss as the cost of Exercise 3.2 (with early exaggeration for the 100 first steps).
  2. Update them with keras.optimizers.Adam and tape.gradient for 600 steps.
  3. Compare the final cost and the metrics with those of Exercise 4.1.
PythonStarting code · a Keras optimizer on the coordinates
P1_tf = tf.constant(P1)Yv = tf.Variable(1e-2 * np.random.default_rng(3).normal(size=(n1, 2)))      # trainable coordinates: one 2-D point per imageoptimizer = ...  # TO DO: a Keras optimizer updates the coordinatesfor step in range(600):    with tf.GradientTape() as tape:        exag = 12.0 if step < 100 else 1.0        loss = ...  # TO DO: the cost, with early exaggeration at the start    ...  # TO DO: gradient step with Adam    if step % 100 == 0 or step == 599:        print(step, "KL (true cost):", float(kl_tf(P1_tf, Yv)))D_low_tf = pairwise_sq_dists(Yv.numpy())print("neighbours kept:", knn_overlap(D1, D_low_tf, 10), "| 5-NN digit accuracy:", knn_accuracy(D_low_tf, y[:n1], 5))
Show the correction
PythonComplete solution · Adam on the map coordinates
P1_tf = tf.constant(P1)# The unknowns of the problem are the coordinates themselves, not weights.Yv = tf.Variable(1e-2 * np.random.default_rng(3).normal(size=(n1, 2)))      # trainable coordinates: one 2-D point per image# Any Keras optimizer can be used: Adam rescales the step of each coordinate.optimizer = keras.optimizers.Adam(learning_rate=0.5)  # a Keras optimizer updates the coordinatesfor step in range(600):    with tf.GradientTape() as tape:        exag = 12.0 if step < 100 else 1.0        loss = kl_tf(P1_tf * exag, Yv)  # the cost, with early exaggeration at the start    optimizer.apply_gradients([(tape.gradient(loss, Yv), Yv)])  # gradient step with Adam    if step % 100 == 0 or step == 599:        print(step, "KL (true cost):", float(kl_tf(P1_tf, Yv)))D_low_tf = pairwise_sq_dists(Yv.numpy())print("neighbours kept:", knn_overlap(D1, D_low_tf, 10), "| 5-NN digit accuracy:", knn_accuracy(D_low_tf, y[:n1], 5))

Adam reaches $\mathrm{KL}=1.196$ in 600 steps (against $1.543$), with $49.7\%$ of the neighbours kept and a 5-NN accuracy of $0.851$. Per-coordinate adaptive learning rates replace the hand-tuned gains of the original algorithm.

Exercise

Exercise 4.3 · does the early exaggeration help?

  1. Run the optimizer of Exercise 4.1 without and with an exaggeration of 12, from the same seed.
  2. Compare the final cost, the neighbours kept and the digit accuracy.
  3. Comment: what did you expect, and what do you observe?
PythonStarting code · with and without exaggeration
rows = []for name, exag in [("without exaggeration", 1.0), ("with exaggeration 12", 12.0)]:    Yc, hc = tsne_numpy(P1, exaggeration=exag, seed=5)    Dc = pairwise_sq_dists(Yc)    ...  # TO DO: final cost, neighbours kept, digit accuracyfor r in rows:    print(f"{r[0]:22s} KL {r[1]:.3f}  neighbours kept {r[2]:.3f}  5-NN accuracy {r[3]:.3f}")
Show the correction
PythonComplete solution · an expectation that the experiment does not confirm
rows = []# The same optimizer, once without and once with early exaggeration.for name, exag in [("without exaggeration", 1.0), ("with exaggeration 12", 12.0)]:    Yc, hc = tsne_numpy(P1, exaggeration=exag, seed=5)    Dc = pairwise_sq_dists(Yc)    rows.append((name, hc[-1][1], knn_overlap(D1, Dc, 10), knn_accuracy(Dc, y[:n1], 5)))  # final cost, neighbours kept, digit accuracyfor r in rows:    print(f"{r[0]:22s} KL {r[1]:.3f}  neighbours kept {r[2]:.3f}  5-NN accuracy {r[3]:.3f}")

Without exaggeration the final cost is $1.009$ and the 5-NN accuracy $0.881$; with an exaggeration of 12 they are $1.360$ and $0.852$. In this small experiment the exaggeration costs iterations that the plain optimizer uses to converge (the same ranking holds for three other seeds and for 1,000 iterations, which we checked). Its benefit, as reported by the authors, concerns larger or harder data sets, where it helps to avoid clusters that are split or trapped. A good habit: test an advice on your own problem.

Part 5 · UMAP: a fuzzy graph and a cross-entropy

Course

UMAP: the same idea with a graph

UMAP follows the same two steps as t-SNE: describe the neighbourhood structure of the data, then find 2-D points with the same structure. The description is a weighted graph instead of a probability matrix, and the comparison is a binary cross-entropy instead of a KL divergence.

UMAP pipeline: nearest neighbours, local scales, fuzzy graph, map memberships, cross-entropy loss with attraction and repulsion
The ingredients of UMAP.
DefinitionFuzzy neighbourhood graph

For every point $i$ keep its $k$ nearest neighbours and let $\rho_i$ be the distance to the nearest one. The directed membership of neighbour $j$ is $w_{j|i}=\exp\!\big(-\max(d_{ij}-\rho_i,0)/\sigma_i\big)$, where $\sigma_i$ is chosen so that $\sum_jw_{j|i}=\log_2k$ (the role of the perplexity). The symmetrized weight is the fuzzy union $w_{ij}=w_{j|i}+w_{i|j}-w_{j|i}w_{i|j}$.

PropositionProperties of the fuzzy graph

(i) The nearest neighbour of every point has $w_{j|i}=1$: the graph has no isolated point, whatever the local density. (ii) $0\le w_{ij}\le1$ and $w_{ij}=w_{ji}$. (iii) $w_{ij}\ge\max(w_{j|i},w_{i|j})$.

Proof

(i) For the nearest neighbour $d_{ij}=\rho_i$, so the exponent is $0$. (ii) $w_{ij}=1-(1-w_{j|i})(1-w_{i|j})$ with both factors in $[0,1]$, which gives values in $[0,1]$ and the symmetry. (iii) $w_{ij}-w_{j|i}=w_{i|j}(1-w_{j|i})\ge0$, and likewise for the other one. $\square$

The offset $\rho_i$ is the difference with t-SNE: each point is connected fully to its nearest neighbour, which keeps every point attached to the graph and measures the other distances relative to the local scale. In the map, the membership of a pair at distance $d$ is $q_{ij}=\big(1+a\,d^{2b}\big)^{-1}$, a family of heavy-tailed curves (for $a=b=1$ it is the Student-$t$ kernel of t-SNE); $a$ and $b$ are fitted so that the curve is close to $1$ up to a min_dist and decays like an exponential after it.

DefinitionUMAP loss

$\displaystyle\mathcal L(Y)=-\sum_{i\ne j}\Big[\,w_{ij}\log q_{ij}+(1-w_{ij})\log(1-q_{ij})\,\Big].$ The first term pulls neighbours together (attraction), the second one pushes apart the pairs that are not neighbours (repulsion).

PropositionAttraction and repulsion forces

With $q=(1+a\,d^{2b})^{-1}$ and $d=\|y_i-y_j\|$, the derivative with respect to $d$ of the loss of the pair is $\dfrac{\partial\ell_{ij}}{\partial d}=w_{ij}\dfrac{2ab\,d^{2b-1}}{1+a\,d^{2b}}-(1-w_{ij})\dfrac{2b}{d\,(1+a\,d^{2b})}$. The first term is attractive and vanishes when $d\to0$; the second one is repulsive and tends to $+\infty$ in absolute value when $d\to0$.

Proof

With $\ell=-w\log q-(1-w)\log(1-q)$ and $q=(1+a\,d^{2b})^{-1}$: $\log q=-\log(1+a\,d^{2b})$, whose derivative is $-\dfrac{2ab\,d^{2b-1}}{1+a\,d^{2b}}$; and $1-q=\dfrac{a\,d^{2b}}{1+a\,d^{2b}}$, so $\log(1-q)=\log a+2b\log d-\log(1+a\,d^{2b})$, whose derivative is $\dfrac{2b}{d}-\dfrac{2ab\,d^{2b-1}}{1+a\,d^{2b}}=\dfrac{2b}{d\,(1+a\,d^{2b})}$. Multiplying by $-w$ and $-(1-w)$ gives the two terms. $\square$

Unlike t-SNE, the loss has no global normalization $Z$: each pair contributes on its own, which allows stochastic optimization with a few random non-neighbours per point (negative sampling), and explains the speed of UMAP on large data. In this course we minimize the loss over all pairs of 1,000 points, with the exact gradient given by TensorFlow.

Exercise

Exercise 5.1 · local scales

  1. Find the 15 nearest neighbours of every image, their distances and $\rho_i$.
  2. Write the bisection for $\sigma_i$ such that the memberships of the neighbours sum to $\log_2k$.
  3. Check the sums and look at the quantiles of $\rho_i$ and $\sigma_i$.
PythonStarting code · rho and sigma
k = 15Dist = np.sqrt(D_high)                                          # Euclidean distances (D_high holds squared distances)knn_idx = ...  # TO DO: the k nearest neighbours of every imageknn_dist = np.take_along_axis(Dist, knn_idx, axis=1)            # their distances, sortedrho = ...  # TO DO: rho_i: distance from x_i to its nearest neighbourdef sigma_for_target(d, r, target, n_iter=64):    lo, hi = 1e-6, 1e3    for _ in range(n_iter):        mid = np.sqrt(lo * hi)        total = ...  # TO DO: sum of the memberships of the k neighbours        if total > target:            hi = ...  # TO DO: too much mass: shrink sigma        else:            lo = mid    return np.sqrt(lo * hi)target = np.log2(k)                                             # UMAP asks the memberships of a point to sum to log2(k)sigma_u = np.array([sigma_for_target(knn_dist[i], rho[i], target) for i in range(n)])check = np.array([np.sum(np.exp(-np.maximum(knn_dist[i] - rho[i], 0) / sigma_u[i])) for i in range(n)])print("target log2(k) =", target, "| obtained: min", check.min(), "max", check.max())print("rho_i quantiles (10%, 50%, 90%):", np.quantile(rho, [0.1, 0.5, 0.9]), "| sigma_i:", np.quantile(sigma_u, [0.1, 0.5, 0.9]))
Show the correction
PythonComplete solution · the offset rho and the width sigma
k = 15Dist = np.sqrt(D_high)                                          # Euclidean distances (D_high holds squared distances)# Indices of the k = 15 nearest neighbours of every image.knn_idx = knn_indices(D_high, k)  # the k nearest neighbours of every imageknn_dist = np.take_along_axis(Dist, knn_idx, axis=1)            # their distances, sorted# rho_i: every point is linked at full strength to its nearest neighbour.rho = knn_dist[:, 0]  # rho_i: distance from x_i to its nearest neighbour# Bisection on sigma so that the memberships sum to log2(k).def sigma_for_target(d, r, target, n_iter=64):    lo, hi = 1e-6, 1e3    for _ in range(n_iter):        mid = np.sqrt(lo * hi)        total = np.sum(np.exp(-np.maximum(d - r, 0.0) / mid))  # sum of the memberships of the k neighbours        if total > target:            hi = mid  # too much mass: shrink sigma        else:            lo = mid    return np.sqrt(lo * hi)target = np.log2(k)                                             # UMAP asks the memberships of a point to sum to log2(k)sigma_u = np.array([sigma_for_target(knn_dist[i], rho[i], target) for i in range(n)])check = np.array([np.sum(np.exp(-np.maximum(knn_dist[i] - rho[i], 0) / sigma_u[i])) for i in range(n)])print("target log2(k) =", target, "| obtained: min", check.min(), "max", check.max())print("rho_i quantiles (10%, 50%, 90%):", np.quantile(rho, [0.1, 0.5, 0.9]), "| sigma_i:", np.quantile(sigma_u, [0.1, 0.5, 0.9]))

The memberships sum to $\log_215=3.907$ for every point. The nearest-neighbour distance $\rho_i$ has the quantiles $3.2,\ 5.5,\ 7.0$ and $\sigma_i$ the quantiles $0.27,\ 0.56,\ 1.08$: the local scales vary by a factor of 4 or more across the data.

Exercise

Exercise 5.2 · the fuzzy graph

  1. Build the matrix of directed memberships $w_{j|i}$ (zero outside the neighbours).
  2. Take the fuzzy union to get $W$.
  3. Check the properties of the proposition and look at the strongest links of image 0.
PythonStarting code · fuzzy union
W_cond = np.zeros((n, n))for i in range(n):    W_cond[i, knn_idx[i]] = ...  # TO DO: membership of each neighbour: 1 at the nearest one, decreasing beyondW = ...  # TO DO: fuzzy union of the two directed memberships: a + b - abprint("nearest neighbour weight is 1 for every point:", np.allclose(W_cond[np.arange(n), knn_idx[:, 0]], 1.0))print("each row of W_cond sums to log2(k):", W_cond.sum(axis=1)[:3])print("symmetric:", np.allclose(W, W.T), "| all weights in [0, 1]:", W.min() >= 0 and W.max() <= 1, "| non-zero entries per point:", (W > 0).sum(axis=1).mean())j = np.argsort(-W[0])[:5]print("strongest neighbours of image 0:", j, "weights", W[0, j], "digits", y[j], "(image 0 is a", y[0], ")")
Show the correction
PythonComplete solution · weights between 0 and 1, symmetric, no isolated point
W_cond = np.zeros((n, n))for i in range(n):    # Memberships outside the 15 neighbours are zero: the matrix is sparse.    W_cond[i, knn_idx[i]] = np.exp(-np.maximum(knn_dist[i] - rho[i], 0.0) / sigma_u[i])  # membership of each neighbour: 1 at the nearest one, decreasing beyond# Fuzzy union of two memberships: a + b - ab = 1 - (1 - a)(1 - b).W = W_cond + W_cond.T - W_cond * W_cond.T  # fuzzy union of the two directed memberships: a + b - abprint("nearest neighbour weight is 1 for every point:", np.allclose(W_cond[np.arange(n), knn_idx[:, 0]], 1.0))print("each row of W_cond sums to log2(k):", W_cond.sum(axis=1)[:3])print("symmetric:", np.allclose(W, W.T), "| all weights in [0, 1]:", W.min() >= 0 and W.max() <= 1, "| non-zero entries per point:", (W > 0).sum(axis=1).mean())j = np.argsort(-W[0])[:5]print("strongest neighbours of image 0:", j, "weights", W[0, j], "digits", y[j], "(image 0 is a", y[0], ")")

Every point has a neighbour of weight exactly $1$, the matrix is symmetric with values in $[0,1]$, and a point has on average $21.6$ non-zero links (15 chosen by itself and the others by points that selected it).

Exercise

Exercise 5.3 · the membership curve

  1. Write the target curve (1 up to min_dist, then an exponential decay) and fit $a,b$ of $1/(1+a\,x^{2b})$ with scipy.optimize.curve_fit.
  2. Do it for min_dist $=0,\ 0.1,\ 0.5$ and print the memberships at distances $0.5$ and $3$.
  3. Compare with the Student-$t$ kernel of t-SNE.
PythonStarting code · fit a and b
from scipy.optimize import curve_fitdef fit_ab(min_dist=0.1, spread=1.0):    xs = np.linspace(0, 3 * spread, 300)    wanted = ...  # TO DO: the target curve: flat up to min_dist, then an exponential decay    kernel = ...  # TO DO: the family of low-dimensional memberships    (a, b), _ = curve_fit(kernel, xs, wanted)    return a, bfor md in [0.0, 0.1, 0.5]:    a_, b_ = fit_ab(md)    print(f"min_dist = {md}: a = {a_:.3f}, b = {b_:.3f}; membership at distance 0.5: {1 / (1 + a_ * 0.5 ** (2 * b_)):.3f}, at distance 3: {1 / (1 + a_ * 3 ** (2 * b_)):.3f}")print("t-SNE kernel (a = b = 1): membership at distance 0.5:", 1 / (1 + 0.25), ", at distance 3:", 1 / (1 + 9))a_umap, b_umap = fit_ab(0.1)
Show the correction
PythonComplete solution · the family of kernels of UMAP
from scipy.optimize import curve_fit# Fit a and b so that the smooth family approximates the piecewise target curve.def fit_ab(min_dist=0.1, spread=1.0):    xs = np.linspace(0, 3 * spread, 300)    wanted = np.where(xs <= min_dist, 1.0, np.exp(-(xs - min_dist) / spread))  # the target curve: flat up to min_dist, then an exponential decay    kernel = lambda x, a, b: 1.0 / (1.0 + a * x ** (2 * b))  # the family of low-dimensional memberships    (a, b), _ = curve_fit(kernel, xs, wanted)    return a, bfor md in [0.0, 0.1, 0.5]:    a_, b_ = fit_ab(md)    print(f"min_dist = {md}: a = {a_:.3f}, b = {b_:.3f}; membership at distance 0.5: {1 / (1 + a_ * 0.5 ** (2 * b_)):.3f}, at distance 3: {1 / (1 + a_ * 3 ** (2 * b_)):.3f}")print("t-SNE kernel (a = b = 1): membership at distance 0.5:", 1 / (1 + 0.25), ", at distance 3:", 1 / (1 + 9))a_umap, b_umap = fit_ab(0.1)

For min_dist $=0.1$ the fit gives $a=1.577$, $b=0.895$. A larger min_dist makes the curve flatter near $0$ ($a=0.583$, $b=1.334$ for $0.5$: membership $0.92$ at distance $0.5$) so that points are allowed to stay packed; with $a=b=1$ (t-SNE) the membership at distance $0.5$ is $0.8$.

Exercise

Exercise 5.4 · minimize the UMAP loss with Keras

  1. Build the fuzzy graph of the first 1,000 images and write the loss with TensorFlow operations (all pairs, diagonal excluded).
  2. Start from the PCA map rescaled to a standard deviation of 10 and minimize the loss with Adam for 500 steps.
  3. Evaluate and plot the map.
PythonStarting code · the UMAP loss with Keras
W1_cond = np.zeros((n1, n1))D1d = np.sqrt(pairwise_sq_dists(X[:n1])); kidx = knn_indices(D1d ** 2, k)kd = np.take_along_axis(D1d, kidx, axis=1); r1 = kd[:, 0]s1u = np.array([sigma_for_target(kd[i], r1[i], target) for i in range(n1)])for i in range(n1):    W1_cond[i, kidx[i]] = np.exp(-np.maximum(kd[i] - r1[i], 0.0) / s1u[i])W1 = W1_cond + W1_cond.T - W1_cond * W1_cond.T                    # fuzzy graph of the 1,000 first imagesW1_tf = tf.constant(W1)off_diag = 1.0 - np.eye(n1)                                        # the diagonal (a point with itself) is excluded from the lossdef umap_loss(Y, a, b):    D = tf.reduce_sum((Y[:, None, :] - Y[None, :, :]) ** 2, axis=-1) + tf.eye(n1, dtype=Y.dtype)     # +1 on the diagonal avoids 0**b    Q = ...  # TO DO: low-dimensional membership q_ij    ce = ...  # TO DO: cross-entropy: attraction where w_ij is large, repulsion where it is small    return tf.reduce_sum(ce * off_diag) / n1Xc1 = X[:n1] - X[:n1].mean(axis=0)Y0 = Xc1 @ np.linalg.svd(Xc1, full_matrices=False)[2][:2].TY0 = Y0 / Y0.std(axis=0) * 10.0                                    # PCA start, rescaled to a standard deviation of 10Yu = tf.Variable(Y0)opt = keras.optimizers.Adam(learning_rate=0.5)for step in range(501):    with tf.GradientTape() as tape:        loss = umap_loss(Yu, a_umap, b_umap)    ...  # TO DO: Adam step on the coordinates    if step % 100 == 0:        print(step, "cross-entropy:", float(loss))D_low_u = pairwise_sq_dists(Yu.numpy())print("neighbours kept:", knn_overlap(D1, D_low_u, 10), "| 5-NN digit accuracy:", knn_accuracy(D_low_u, y[:n1], 5))scatter(Yu.numpy(), y[:n1], "UMAP loss minimized with Keras (1,000 images)"); plt.show()
Expected display: what your code should plot
Expected display of the exercise
Show the correction
PythonComplete solution · a UMAP written with a Keras optimizer
W1_cond = np.zeros((n1, n1))D1d = np.sqrt(pairwise_sq_dists(X[:n1])); kidx = knn_indices(D1d ** 2, k)kd = np.take_along_axis(D1d, kidx, axis=1); r1 = kd[:, 0]s1u = np.array([sigma_for_target(kd[i], r1[i], target) for i in range(n1)])for i in range(n1):    W1_cond[i, kidx[i]] = np.exp(-np.maximum(kd[i] - r1[i], 0.0) / s1u[i])W1 = W1_cond + W1_cond.T - W1_cond * W1_cond.T                    # fuzzy graph of the 1,000 first imagesW1_tf = tf.constant(W1)off_diag = 1.0 - np.eye(n1)                                        # the diagonal (a point with itself) is excluded from the loss# Binary cross-entropy summed over all pairs: attraction where w is large, repulsion where it is small.def umap_loss(Y, a, b):    # + eye: the diagonal distance is 0 and 0 ** b has an infinite derivative; the diagonal is masked later.    D = tf.reduce_sum((Y[:, None, :] - Y[None, :, :]) ** 2, axis=-1) + tf.eye(n1, dtype=Y.dtype)     # +1 on the diagonal avoids 0**b    Q = 1.0 / (1.0 + a * D ** b)  # low-dimensional membership q_ij    ce = -(W1_tf * tf.math.log(Q + 1e-9) + (1.0 - W1_tf) * tf.math.log(1.0 - Q + 1e-9))  # cross-entropy: attraction where w_ij is large, repulsion where it is small    return tf.reduce_sum(ce * off_diag) / n1Xc1 = X[:n1] - X[:n1].mean(axis=0)Y0 = Xc1 @ np.linalg.svd(Xc1, full_matrices=False)[2][:2].T# UMAP maps typically live at a scale of a few units to ten: start from PCA at that scale.Y0 = Y0 / Y0.std(axis=0) * 10.0                                    # PCA start, rescaled to a standard deviation of 10Yu = tf.Variable(Y0)opt = keras.optimizers.Adam(learning_rate=0.5)for step in range(501):    with tf.GradientTape() as tape:        loss = umap_loss(Yu, a_umap, b_umap)    opt.apply_gradients([(tape.gradient(loss, Yu), Yu)])  # Adam step on the coordinates    if step % 100 == 0:        print(step, "cross-entropy:", float(loss))D_low_u = pairwise_sq_dists(Yu.numpy())print("neighbours kept:", knn_overlap(D1, D_low_u, 10), "| 5-NN digit accuracy:", knn_accuracy(D_low_u, y[:n1], 5))scatter(Yu.numpy(), y[:n1], "UMAP loss minimized with Keras (1,000 images)"); plt.show()

The loss decreases from $36.3$ to $21.5$. The map keeps $49.4\%$ of the 10 neighbours and has a 5-NN accuracy of $0.861$, comparable with the t-SNE of Exercise 4.2 on the same images.

Part 6 · MNIST with Keras: pixels, learned features, t-SNE and UMAP

Course

Maps of what a network has learned

Dimensionality reduction is not only for raw data. A classifier maps an image to a learned representation: the activations of its last hidden layer, here $64$ numbers. If the network works, images of the same digit should be close in this space, and a map of it shows how the network sees the data, where it hesitates (digits that overlap) and where it is confident. We train a Dense network on the 60,000 MNIST images, extract the features of 3,000 test images with a Keras model that stops at the layer named features, and map them with t-SNE and UMAP, next to the maps of the raw pixels.

Exercise

Exercise 6.1 · a Keras classifier and its feature extractor

  1. Build a Dense network $784\to128\to64\to10$ with the functional API; name the 64-unit layer features. Train it for 5 epochs on MNIST.
  2. Build a model that returns the output of features.
  3. Take 3,000 test images and compute their pixels and their learned features.
PythonStarting code · classifier and feature extractor
x_train = x_all.reshape(-1, 784).astype("float32") / 255.0x_test = x_test_all.reshape(-1, 784).astype("float32") / 255.0keras.utils.set_random_seed(SEED)inputs = keras.Input(shape=(784,))h = ...  # TO DO: first hidden layerfeatures = ...  # TO DO: last hidden layer: the learned representation (64 numbers)logits = ...  # TO DO: one logit per digitclassifier = keras.Model(inputs, logits)classifier.compile(optimizer="adam", loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=["accuracy"])classifier.fit(x_train, y_all, epochs=5, batch_size=128, validation_split=0.1, verbose=0)print("test accuracy:", classifier.evaluate(x_test, y_test_all, verbose=0)[1])extractor = ...  # TO DO: a model that stops at the layer "features"sel = np.random.default_rng(7).choice(len(x_test), 3000, replace=False)X_pix, X_feat, y_sel = x_test[sel].astype("float64"), extractor.predict(x_test[sel], verbose=0).astype("float64"), y_test_all[sel]print("pixels:", X_pix.shape, "learned features:", X_feat.shape)
Show the correction
PythonComplete solution · learned features of 3,000 test images
x_train = x_all.reshape(-1, 784).astype("float32") / 255.0x_test = x_test_all.reshape(-1, 784).astype("float32") / 255.0keras.utils.set_random_seed(SEED)inputs = keras.Input(shape=(784,))h = layers.Dense(128, activation="relu")(inputs)  # first hidden layerfeatures = layers.Dense(64, activation="relu", name="features")(h)  # last hidden layer: the learned representation (64 numbers)logits = layers.Dense(10)(features)  # one logit per digitclassifier = keras.Model(inputs, logits)classifier.compile(optimizer="adam", loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=["accuracy"])classifier.fit(x_train, y_all, epochs=5, batch_size=128, validation_split=0.1, verbose=0)print("test accuracy:", classifier.evaluate(x_test, y_test_all, verbose=0)[1])# A model sharing the layers of the classifier but stopping at "features".extractor = keras.Model(inputs, features)  # a model that stops at the layer "features"sel = np.random.default_rng(7).choice(len(x_test), 3000, replace=False)X_pix, X_feat, y_sel = x_test[sel].astype("float64"), extractor.predict(x_test[sel], verbose=0).astype("float64"), y_test_all[sel]print("pixels:", X_pix.shape, "learned features:", X_feat.shape)

The test accuracy is $97.3\%$. We keep the pixels ($3000\times784$) and the learned features ($3000\times64$) of the same images.

Exercise

Exercise 6.2 · t-SNE of the pixels and of the features

  1. Write a function that computes a t-SNE map with sklearn.manifold.TSNE (PCA initialization, perplexity 30) and returns the final KL.
  2. Map the pixels and the learned features and plot the two maps side by side.
  3. Compare the final costs and describe the differences.
PythonStarting code · t-SNE of two representations
from sklearn.manifold import TSNE, trustworthinessdef embed(A, perplexity=30, seed=0, init="pca"):    tsne = TSNE(n_components=2, perplexity=perplexity, init=init, learning_rate="auto", random_state=seed)    return tsne.fit_transform(A), tsne.kl_divergence_Y_pix, kl_pix = ...  # TO DO: t-SNE of the raw pixelsY_feat, kl_feat = ...  # TO DO: t-SNE of the 64 learned featuresfig, axes = plt.subplots(1, 2, figsize=(12, 5))scatter(Y_pix, y_sel, "t-SNE of the pixels (784-d)", axes[0])scatter(Y_feat, y_sel, "t-SNE of the learned features (64-d)", axes[1])plt.show()print("final KL: pixels", kl_pix, "| features", kl_feat)
Expected display: what your code should plot
Expected display of the exercise
Show the correction
PythonComplete solution · the network separates the digits better than the pixels
from sklearn.manifold import TSNE, trustworthiness# Wrapper of scikit-learn t-SNE with PCA initialization (more stable) and the automatic learning rate.def embed(A, perplexity=30, seed=0, init="pca"):    tsne = TSNE(n_components=2, perplexity=perplexity, init=init, learning_rate="auto", random_state=seed)    return tsne.fit_transform(A), tsne.kl_divergence_Y_pix, kl_pix = embed(X_pix)  # t-SNE of the raw pixelsY_feat, kl_feat = embed(X_feat)  # t-SNE of the 64 learned featuresfig, axes = plt.subplots(1, 2, figsize=(12, 5))scatter(Y_pix, y_sel, "t-SNE of the pixels (784-d)", axes[0])scatter(Y_feat, y_sel, "t-SNE of the learned features (64-d)", axes[1])plt.show()print("final KL: pixels", kl_pix, "| features", kl_feat)

The features give a clearly cleaner map than the pixels (final KL $1.04$ against $1.34$): the classes form compact, well-separated islands, whereas in the pixel map the fours, nines and sevens overlap. The network has pulled together the images of each digit.

Exercise

Exercise 6.3 · PCA against t-SNE, with numbers

  1. Compute the PCA map of the same 3,000 pixel images.
  2. For the PCA map and the two t-SNE maps, compute the 5-NN accuracy and the trustworthiness.
  3. Compare with the 5-NN accuracy in the original spaces.
PythonStarting code · metrics of the maps
Xc3 = X_pix - X_pix.mean(axis=0)Y_pca3 = Xc3 @ np.linalg.svd(Xc3, full_matrices=False)[2][:2].T     # PCA of the same 3,000 pixel imagestable = {}for name, A, Y2 in [("PCA of the pixels", X_pix, Y_pca3), ("t-SNE of the pixels", X_pix, Y_pix), ("t-SNE of the learned features", X_feat, Y_feat)]:    D_low = pairwise_sq_dists(Y2)    acc = ...  # TO DO: digits recovered by 5 nearest neighbours in the 2-D map    trust = ...  # TO DO: trustworthiness: are the neighbours in the map real neighbours?    table[name] = (acc, trust)print(f"{'map':32s} {'5-NN accuracy':>14s} {'trustworthiness':>16s}")for name, (acc, trust) in table.items():    print(f"{name:32s} {acc:14.3f} {trust:16.3f}")print("5-NN accuracy in the original spaces: pixels", knn_accuracy(pairwise_sq_dists(X_pix), y_sel, 5), "| features", knn_accuracy(pairwise_sq_dists(X_feat), y_sel, 5))
Show the correction
PythonComplete solution · what a nonlinear map recovers
Xc3 = X_pix - X_pix.mean(axis=0)Y_pca3 = Xc3 @ np.linalg.svd(Xc3, full_matrices=False)[2][:2].T     # PCA of the same 3,000 pixel imagestable = {}for name, A, Y2 in [("PCA of the pixels", X_pix, Y_pca3), ("t-SNE of the pixels", X_pix, Y_pix), ("t-SNE of the learned features", X_feat, Y_feat)]:    D_low = pairwise_sq_dists(Y2)    acc = knn_accuracy(D_low, y_sel, 5)  # digits recovered by 5 nearest neighbours in the 2-D map    # Trustworthiness: 1 minus the penalty for points that are neighbours in the map without being neighbours in the original space.    trust = trustworthiness(A, Y2, n_neighbors=10)  # trustworthiness: are the neighbours in the map real neighbours?    table[name] = (acc, trust)print(f"{'map':32s} {'5-NN accuracy':>14s} {'trustworthiness':>16s}")for name, (acc, trust) in table.items():    print(f"{name:32s} {acc:14.3f} {trust:16.3f}")print("5-NN accuracy in the original spaces: pixels", knn_accuracy(pairwise_sq_dists(X_pix), y_sel, 5), "| features", knn_accuracy(pairwise_sq_dists(X_feat), y_sel, 5))

map5-NN accuracytrustworthiness
PCA of the pixels0.4310.743
t-SNE of the pixels0.9180.976
t-SNE of the learned features0.9580.992

In the original spaces the same 5-NN rule gives $0.920$ (pixels) and $0.962$ (features): the t-SNE maps in two dimensions keep almost all the neighbourhood information that PCA loses.

Course

Comparing t-SNE and UMAP

t-SNEUMAP
Neighbourhoods in the dataGaussian probabilities, one width per point from the perplexityweighted graph on $k$ neighbours, offset $\rho_i$ and width $\sigma_i$ from $\log_2k$
Neighbourhoods in the mapStudent-$t$ kernel normalized over all pairscurve $(1+a\,d^{2b})^{-1}$, no normalization
Cost$\mathrm{KL}(P\|Q)$binary cross-entropy between graphs (attraction and repulsion)
Optimizationgradient on all pairs, or approximations (Barnes–Hut, FFT)stochastic gradient with negative sampling
Main parametersperplexity, iterations, learning rate, exaggerationn_neighbors, min_dist
New pointsno transform (a parametric network can be trained)transform available
Global structurenot controlled by the cost; depends strongly on the initializationnot controlled either, but often better with the default spectral initialization

The honest summary of the literature is that both methods preserve local structure well and that what they show of the global structure (distances between clusters, relative sizes) must not be over-interpreted. In particular the global arrangement seems to depend more on the initialization than on the method (Kobak and Linderman, 2021): our own comparison, below, confirms that t-SNE with a PCA start is not worse than UMAP in this respect.

Exercise

Exercise 6.4 · UMAP with the library

  1. Write a function that fits umap.UMAP on a matrix and returns the map and the elapsed time.
  2. Run it on the 2,000 pixel images and evaluate the map.
  3. Compare with your Keras implementation of Exercise 5.4 and plot the two maps.
PythonStarting code · the UMAP library
import time, warningsimport umapwarnings.filterwarnings("ignore")def embed_umap(A, n_neighbors=15, min_dist=0.1, seed=0):    reducer = umap.UMAP(n_components=2, n_neighbors=n_neighbors, min_dist=min_dist, random_state=seed, n_jobs=1, compatibility_layout=True)    t0 = time.perf_counter()    Y2 = ...  # TO DO: the library does what we wrote: fuzzy graph, then cross-entropy optimization    return Y2, time.perf_counter() - t0, reducerY_umap, t_umap, reducer = embed_umap(X)                                 # the 2,000 pixel images of Part 1D_umap = pairwise_sq_dists(Y_umap)print(f"UMAP (library): {t_umap:.1f} s | neighbours kept {knn_overlap(D_high, D_umap, 10):.3f} | 5-NN accuracy {knn_accuracy(D_umap, y, 5):.3f}")print("for comparison, our Keras version (1,000 images): neighbours kept", knn_overlap(D1, D_low_u, 10), "| 5-NN accuracy", knn_accuracy(D_low_u, y[:n1], 5))fig, axes = plt.subplots(1, 2, figsize=(12, 5))scatter(Y_umap, y, "UMAP of 2,000 images (library)", axes[0]); scatter(Yu.numpy(), y[:n1], "our UMAP loss, 1,000 images", axes[1])plt.show()
Expected display: what your code should plot
Expected display of the exercise
Show the correction
PythonComplete solution · the library does what we wrote, with a faster optimizer
import time, warningsimport umapwarnings.filterwarnings("ignore")# A thin wrapper around the library: n_neighbors and min_dist are its two main parameters.def embed_umap(A, n_neighbors=15, min_dist=0.1, seed=0):    reducer = umap.UMAP(n_components=2, n_neighbors=n_neighbors, min_dist=min_dist, random_state=seed, n_jobs=1, compatibility_layout=True)    t0 = time.perf_counter()    Y2 = reducer.fit_transform(A)  # the library does what we wrote: fuzzy graph, then cross-entropy optimization    return Y2, time.perf_counter() - t0, reducerY_umap, t_umap, reducer = embed_umap(X)                                 # the 2,000 pixel images of Part 1D_umap = pairwise_sq_dists(Y_umap)print(f"UMAP (library): {t_umap:.1f} s | neighbours kept {knn_overlap(D_high, D_umap, 10):.3f} | 5-NN accuracy {knn_accuracy(D_umap, y, 5):.3f}")print("for comparison, our Keras version (1,000 images): neighbours kept", knn_overlap(D1, D_low_u, 10), "| 5-NN accuracy", knn_accuracy(D_low_u, y[:n1], 5))fig, axes = plt.subplots(1, 2, figsize=(12, 5))scatter(Y_umap, y, "UMAP of 2,000 images (library)", axes[0]); scatter(Yu.numpy(), y[:n1], "our UMAP loss, 1,000 images", axes[1])plt.show()

On the 2,000 images the library map keeps $38.8\%$ of the neighbours and has a 5-NN accuracy of $0.883$, against $49.4\%$ and $0.861$ for our version on 1,000 images (the metrics depend on the number of points: do not compare the overlaps of two different sets). The first call is slow because the library compiles its code.

Exercise

Exercise 6.5 · t-SNE against UMAP on two representations

  1. Write a measure of global structure: the rank correlation (Spearman) between the 45 distances between digit centroids in the original space and in the map.
  2. For the pixels and the learned features, compute the t-SNE map and the UMAP map and record the elapsed time, the 5-NN accuracy, the trustworthiness and the global measure.
  3. Print a table and conclude.
PythonStarting code · a comparison table
from scipy.stats import spearmanrdef centroid_distance_corr(A, Y2, labels):    """Global structure: do the distances between the digit centroids in the map follow those of the original space?"""    ca = ...  # TO DO: centroid of each digit in the original space    cy = np.array([Y2[labels == d].mean(axis=0) for d in range(10)])             # and in the 2-D map    iu = np.triu_indices(10, 1)    return ...  # TO DO: rank correlation of the 45 centroid distancesresults = {}for in_name, A in [("pixels", X_pix), ("learned features", X_feat)]:    t0 = time.perf_counter(); Yt = embed(A)[0]; t_t = time.perf_counter() - t0                   # t-SNE    Yu_, t_u, _ = embed_umap(A)                                                                      # UMAP    for name, Y2, secs in [("t-SNE", Yt, t_t), ("UMAP", Yu_, t_u)]:        Dm = pairwise_sq_dists(Y2)        results[(in_name, name)] = (secs, knn_accuracy(Dm, y_sel, 5), trustworthiness(A, Y2, n_neighbors=10), centroid_distance_corr(A, Y2, y_sel))print(f"{'input':18s} {'method':6s} {'time (s)':>9s} {'5-NN acc.':>10s} {'trustw.':>8s} {'global (rho)':>13s}")for (in_name, name), (secs, acc, trust, glob) in results.items():    print(f"{in_name:18s} {name:6s} {secs:9.1f} {acc:10.3f} {trust:8.3f} {glob:13.3f}")
Show the correction
PythonComplete solution · two methods, similar quality on this task
from scipy.stats import spearmanr# Global structure: do digits that are far apart in the original space stay far apart in the map?def centroid_distance_corr(A, Y2, labels):    """Global structure: do the distances between the digit centroids in the map follow those of the original space?"""    ca = np.array([A[labels == d].mean(axis=0) for d in range(10)])  # centroid of each digit in the original space    cy = np.array([Y2[labels == d].mean(axis=0) for d in range(10)])             # and in the 2-D map    iu = np.triu_indices(10, 1)    return float(spearmanr(pairwise_sq_dists(ca)[iu], pairwise_sq_dists(cy)[iu])[0])  # rank correlation of the 45 centroid distances# One run of each method on each representation, with timing.results = {}for in_name, A in [("pixels", X_pix), ("learned features", X_feat)]:    t0 = time.perf_counter(); Yt = embed(A)[0]; t_t = time.perf_counter() - t0                   # t-SNE    Yu_, t_u, _ = embed_umap(A)                                                                      # UMAP    for name, Y2, secs in [("t-SNE", Yt, t_t), ("UMAP", Yu_, t_u)]:        Dm = pairwise_sq_dists(Y2)        results[(in_name, name)] = (secs, knn_accuracy(Dm, y_sel, 5), trustworthiness(A, Y2, n_neighbors=10), centroid_distance_corr(A, Y2, y_sel))print(f"{'input':18s} {'method':6s} {'time (s)':>9s} {'5-NN acc.':>10s} {'trustw.':>8s} {'global (rho)':>13s}")for (in_name, name), (secs, acc, trust, glob) in results.items():    print(f"{in_name:18s} {name:6s} {secs:9.1f} {acc:10.3f} {trust:8.3f} {glob:13.3f}")

inputmethodtime (s)5-NN acc.trustw.global $\rho$
pixelst-SNE3.80.9180.9760.692
pixelsUMAP3.50.9060.9610.696
learned featurest-SNE3.60.9580.9920.591
learned featuresUMAP3.00.9580.9840.539

On 3,000 points the two methods are close in quality and in time; t-SNE is slightly better on trustworthiness and, here, on the global measure for the learned features. UMAP’s advantage in speed appears when the number of points grows (hundreds of thousands) and is not visible at this size. The usual claim that UMAP preserves the global structure better is not reproduced by this test, in which t-SNE starts from PCA.

Part 7 · Reading the maps correctly, parameters and new data

Course

What a map says, and what it does not say

  • Neighbourhoods are meaningful, distances are not. Two points that are close in the map are likely to be neighbours in the data. The distance between two clusters, their relative sizes and their densities depend on the parameters and carry little information.
  • The parameters change the picture. A small perplexity or n_neighbors makes the map very local (small islands, even invented ones); a very large one makes it smoother and closer to a global projection.
  • The result is random. The cost is non-convex: another seed, or another initialization, gives another map. Repeat the computation before believing a feature of the map.
  • A map is not a clustering. A cluster that appears can be an artefact; a mixture that appears can be a limit of the 2-D plane. Check with the original space (the 5-NN accuracy above) or with the labels.
  • New data. t-SNE has no transform: to place a new image one must recompute the map, or train a network that predicts the coordinates (parametric t-SNE). UMAP can transform new points.
Exercise

Exercise 7.1 · the perplexity of t-SNE

  1. Compute the t-SNE map of the 2,000 pixel images for perplexities $5,\ 30,\ 100,\ 300$.
  2. For each, print the final cost, the neighbours kept and the 5-NN accuracy, and plot the four maps.
  3. Which values give a faithful and readable map?
PythonStarting code · perplexity sweep
fig, axes = plt.subplots(1, 4, figsize=(16, 4))D_ref = pairwise_sq_dists(X)for ax, perp in zip(axes, [5, 30, 100, 300]):    Yp, klp = ...  # TO DO: the same data, with four perplexities    Dp = pairwise_sq_dists(Yp)    scatter(Yp, y, f"perplexity {perp}", ax)    print(f"perplexity {perp:3d}: KL {klp:.3f} | neighbours kept {knn_overlap(D_ref, Dp, 10):.3f} | 5-NN accuracy {knn_accuracy(Dp, y, 5):.3f}")plt.show()
Expected display: what your code should plot
Expected display of the exercise
Show the correction
PythonComplete solution · too small is noisy, too large mixes the classes
fig, axes = plt.subplots(1, 4, figsize=(16, 4))D_ref = pairwise_sq_dists(X)for ax, perp in zip(axes, [5, 30, 100, 300]):    # The same data, four perplexities: everything else is identical.    Yp, klp = embed(X, perplexity=perp)  # the same data, with four perplexities    Dp = pairwise_sq_dists(Yp)    scatter(Yp, y, f"perplexity {perp}", ax)    print(f"perplexity {perp:3d}: KL {klp:.3f} | neighbours kept {knn_overlap(D_ref, Dp, 10):.3f} | 5-NN accuracy {knn_accuracy(Dp, y, 5):.3f}")plt.show()

The 5-NN accuracy is $0.899,\ 0.901,\ 0.892$ for the perplexities $5,\ 30,\ 100$ and falls to $0.827$ at $300$, where the neighbours kept also drop ($0.395$): the classes start to merge. The final cost decreases with the perplexity ($1.28,\ 1.23,\ 1.01,\ 0.74$): costs of different perplexities cannot be compared, since the target $P$ changes.

Exercise

Exercise 7.2 · the parameters of UMAP

  1. Compute the UMAP map of the 2,000 pixel images for n_neighbors $=5,\ 15,\ 50,\ 200$ and min_dist $=0,\ 0.1,\ 0.5,\ 0.99$.
  2. For each map print the neighbours kept and the 5-NN accuracy (and the centroid correlation for n_neighbors).
  3. Describe the effect of each parameter on the picture.
PythonStarting code · UMAP parameter sweeps
fig, axes = plt.subplots(2, 4, figsize=(16, 8))for ax, nn in zip(axes[0], [5, 15, 50, 200]):    Yp, secs, _ = ...  # TO DO: the number of neighbours controls how local the graph is    Dp = pairwise_sq_dists(Yp); scatter(Yp, y, f"n_neighbors = {nn}", ax)    print(f"n_neighbors {nn:3d}: neighbours kept {knn_overlap(D_high, Dp, 10):.3f} | 5-NN accuracy {knn_accuracy(Dp, y, 5):.3f} | centroid correlation {centroid_distance_corr(X, Yp, y):.3f}")for ax, md in zip(axes[1], [0.0, 0.1, 0.5, 0.99]):    Yp, secs, _ = ...  # TO DO: min_dist controls how tightly points may be packed    Dp = pairwise_sq_dists(Yp); scatter(Yp, y, f"min_dist = {md}", ax)    print(f"min_dist {md:4.2f}: neighbours kept {knn_overlap(D_high, Dp, 10):.3f} | 5-NN accuracy {knn_accuracy(Dp, y, 5):.3f}")plt.tight_layout(); plt.show()
Expected display: what your code should plot
Expected display of the exercise
Show the correction
PythonComplete solution · n_neighbors sets the scale, min_dist the packing
fig, axes = plt.subplots(2, 4, figsize=(16, 8))for ax, nn in zip(axes[0], [5, 15, 50, 200]):    # The first row varies the neighbourhood size...    Yp, secs, _ = embed_umap(X, n_neighbors=nn)  # the number of neighbours controls how local the graph is    Dp = pairwise_sq_dists(Yp); scatter(Yp, y, f"n_neighbors = {nn}", ax)    print(f"n_neighbors {nn:3d}: neighbours kept {knn_overlap(D_high, Dp, 10):.3f} | 5-NN accuracy {knn_accuracy(Dp, y, 5):.3f} | centroid correlation {centroid_distance_corr(X, Yp, y):.3f}")for ax, md in zip(axes[1], [0.0, 0.1, 0.5, 0.99]):    Yp, secs, _ = embed_umap(X, min_dist=md)  # min_dist controls how tightly points may be packed    Dp = pairwise_sq_dists(Yp); scatter(Yp, y, f"min_dist = {md}", ax)    print(f"min_dist {md:4.2f}: neighbours kept {knn_overlap(D_high, Dp, 10):.3f} | 5-NN accuracy {knn_accuracy(Dp, y, 5):.3f}")plt.tight_layout(); plt.show()

The neighbours kept fall from $0.41$ to $0.30$ when n_neighbors goes from 5 to 200, and the 5-NN accuracy from $0.88$ to $0.83$: the graph becomes less local. min_dist only changes how tightly the points are packed (accuracy $0.89$ at $0$ and $0.79$ at $0.99$, where the clusters touch each other); the topology of the map is the same.

Exercise

Exercise 7.3 · stability across seeds

  1. Compute three maps of the same data with different seeds, for t-SNE (PCA start) and for UMAP.
  2. Measure how different two maps are, after the best rotation, scale and translation, with scipy.spatial.procrustes.
  3. Record also the global measure of each map.
PythonStarting code · seeds and Procrustes
from scipy.spatial import procrustesstab = {}for name in ["t-SNE", "UMAP"]:    maps_ = []    for seed in [0, 1, 2]:        ...  # TO DO: the same method with three seeds    disp = ...  # TO DO: difference between maps after the best rotation, scale and translation    cent = [centroid_distance_corr(X, m, y) for m in maps_]    stab[name] = (disp, cent)    print(f"{name:6s}: disparity of seeds 1 and 2 with seed 0: {np.round(disp, 3)} | centroid correlation per seed: {np.round(cent, 3)}")
Show the correction
PythonComplete solution · reproducibility depends on the initialization
from scipy.spatial import procrustesstab = {}for name in ["t-SNE", "UMAP"]:    maps_ = []    for seed in [0, 1, 2]:        # Same method, same data, three seeds.        maps_.append(embed(X, seed=seed)[0] if name == "t-SNE" else embed_umap(X, seed=seed)[0])  # the same method with three seeds    disp = [procrustes(maps_[0], maps_[s])[2] for s in (1, 2)]  # difference between maps after the best rotation, scale and translation    cent = [centroid_distance_corr(X, m, y) for m in maps_]    stab[name] = (disp, cent)    print(f"{name:6s}: disparity of seeds 1 and 2 with seed 0: {np.round(disp, 3)} | centroid correlation per seed: {np.round(cent, 3)}")

With the PCA initialization, t-SNE gives almost the same map for the three seeds (disparity $0.003$ and $0.004$), whereas the UMAP maps differ more ($0.19$ and $0.16$), with a global measure between $0.55$ and $0.61$ against $0.72$ for t-SNE. The seed only enters through the optimizer here: the starting point, not the method, controls much of the arrangement of the clusters.

Exercise

Exercise 7.4 · new images: parametric t-SNE and UMAP transform

  1. Compute a t-SNE map of 3,000 test images, and a UMAP map of the same images.
  2. Train a Keras network that predicts the t-SNE coordinates of an image (parametric t-SNE) and use reducer.transform for UMAP.
  3. Place 1,000 held-out images on each map and measure the 5-NN accuracy of their placement.
PythonStarting code · placing new images
n_map = 4000; split = 3000y_new = y_test_all[:n_map]A_train, A_new = x_test[:split].astype("float64"), x_test[split:n_map].astype("float64")Y_map, _ = embed(A_train)                                               # t-SNE has no transform: a map is built on the 3,000 images onlyreducer_u = umap.UMAP(n_neighbors=15, min_dist=0.1, random_state=0, n_jobs=1, compatibility_layout=True).fit(A_train)t0 = ...  # TO DO: UMAP can place new images on an existing mapY_train_umap = reducer_u.embedding_mu, sd = Y_map.mean(axis=0), Y_map.std(axis=0)keras.utils.set_random_seed(SEED)mapper = ...  # TO DO: parametric t-SNE: a network that predicts the map coordinatesmapper.compile(optimizer=keras.optimizers.Adam(1e-3), loss="mse")mapper.fit(x_test[:split], (Y_map - mu) / sd, epochs=60, batch_size=64, verbose=0)Y_new_tsne = mapper.predict(x_test[split:n_map], verbose=0) * sd + mudef place_accuracy(Y_train2, Y_new2):    d = ((Y_new2[:, None, :] - Y_train2[None, :, :]) ** 2).sum(-1)    nn = np.argsort(d, axis=1)[:, :5]    vote = np.array([np.bincount(y_new[:split][row], minlength=10).argmax() for row in nn])    return float(np.mean(vote == y_new[split:]))print("held-out images placed on the map, 5-NN accuracy:")print("  t-SNE map + Keras regression network:", place_accuracy(Y_map, Y_new_tsne))print("  UMAP map + transform():              ", place_accuracy(Y_train_umap, Y_new_umap), f"(transform of 1,000 images: {t_tr:.1f} s)")
Show the correction
PythonComplete solution · UMAP transforms new points, t-SNE needs a surrogate
n_map = 4000; split = 3000y_new = y_test_all[:n_map]A_train, A_new = x_test[:split].astype("float64"), x_test[split:n_map].astype("float64")Y_map, _ = embed(A_train)                                               # t-SNE has no transform: a map is built on the 3,000 images onlyreducer_u = umap.UMAP(n_neighbors=15, min_dist=0.1, random_state=0, n_jobs=1, compatibility_layout=True).fit(A_train)# UMAP can map images that were not used to fit it.t0 = time.perf_counter(); Y_new_umap = reducer_u.transform(A_new); t_tr = time.perf_counter() - t0  # UMAP can place new images on an existing mapY_train_umap = reducer_u.embedding_mu, sd = Y_map.mean(axis=0), Y_map.std(axis=0)keras.utils.set_random_seed(SEED)# A regression network: image in, 2-D coordinates out.mapper = keras.Sequential([keras.Input(shape=(784,)), layers.Dense(256, activation="relu"), layers.Dense(128, activation="relu"), layers.Dense(2)])  # parametric t-SNE: a network that predicts the map coordinatesmapper.compile(optimizer=keras.optimizers.Adam(1e-3), loss="mse")mapper.fit(x_test[:split], (Y_map - mu) / sd, epochs=60, batch_size=64, verbose=0)Y_new_tsne = mapper.predict(x_test[split:n_map], verbose=0) * sd + mudef place_accuracy(Y_train2, Y_new2):    d = ((Y_new2[:, None, :] - Y_train2[None, :, :]) ** 2).sum(-1)    nn = np.argsort(d, axis=1)[:, :5]    vote = np.array([np.bincount(y_new[:split][row], minlength=10).argmax() for row in nn])    return float(np.mean(vote == y_new[split:]))print("held-out images placed on the map, 5-NN accuracy:")print("  t-SNE map + Keras regression network:", place_accuracy(Y_map, Y_new_tsne))print("  UMAP map + transform():              ", place_accuracy(Y_train_umap, Y_new_umap), f"(transform of 1,000 images: {t_tr:.1f} s)")

The held-out images placed with transform are classified correctly in $85.4\%$ of the cases (in $3.7$ s for 1,000 images); with the regression network, which only sees 3,000 training images, the accuracy is $69.1\%$. A parametric t-SNE needs far more data or a better loss (the original parametric t-SNE trains the network directly on the t-SNE cost).

Part 8 · Deliverables and limits

Exercise

Build a defensible report

  1. Prove that the perplexity increases with $\sigma$ and explain why the bisection converges.
  2. Derive the gradient of the t-SNE cost and interpret it as springs.
  3. Prove the properties of the fuzzy graph of UMAP and the two forces of its loss.
  4. Report the maps of the pixels and of the learned features, with the 5-NN accuracy and the trustworthiness, and the same numbers for the PCA map.
  5. Compare t-SNE and UMAP on one more data set of your choice (for instance Fashion-MNIST): time, local and global measures, stability across seeds.
  6. Extension: map the features of a second network (the CNN of the Keras course) and describe where the digits that the network confuses lie on the map.

Deliver a rerunnable notebook, a table of results, the figures and a paragraph of limits.

Course

What these experiments do not show

We used 1,000 to 3,000 images and a CPU: the optimizers written here are meant for understanding, not for scale. The maps depend on the parameters and on the seed, and every statement of this page is about a local structure: a map is a hypothesis generator, not a proof of the existence of clusters. The comparison between t-SNE and UMAP was made on one data set, with one initialization for t-SNE and the defaults of the library for UMAP; other data, other sizes and other initializations can give other rankings. Finally the metrics (neighbour overlap, $k$-NN accuracy, trustworthiness) summarize a map by a few numbers and miss what the picture shows; use them together with the picture.

References and related learning

Course

The papers behind the methods