Sub topic 6
t-SNE step 1: turning distances into probabilities
This chapter covers the first half of t-SNE: how it converts distances between points in the original space into a probability for each pair of points. It assumes you know Euclidean distance, basic probability (distributions, normalisation), and scikit-learn's fit/transform interface. The next chapters cover how the neighbourhood size is controlled (perplexity) and what happens in the low-dimensional space.
The goal of the first step
A neighbour embedding method needs a precise definition of "neighbour". Raw distances are a poor choice. A distance of 3.0 means something different in a dense region than in a sparse one. t-SNE therefore describes each point's neighbourhood as a probability distribution over the other points. Nearby points get high probability, and distant points get almost none.
For each point, the question is: if this point picked one neighbour at random, with closer points more likely to be picked, how likely is each other point to be chosen?
Conditional probabilities from a Gaussian
For points xi and xj in the original space, t-SNE defines the conditional probability that i would pick j as its neighbour:
p(j|i) = exp(-||x_i - x_j||^2 / (2 sigma_i^2))
/ sum over k != i of exp(-||x_i - x_k||^2 / (2 sigma_i^2))Read this in two parts.
- The numerator is a Gaussian centred on x_i. It falls off quickly as the squared distance grows.
- The denominator sums the same quantity over every other point. It normalises the values so that they add up to 1 for a fixed i.
By convention p(i|i) = 0, because a point is not its own neighbour.
The bandwidth sigmai belongs to point i. It sets how fast the Gaussian falls off. A small sigmai means only the very closest points get meaningful probability. A large sigma_i spreads probability over many points.
Why each point gets its own bandwidth
Real data has uneven density. Suppose point A sits in a tight cluster where its nearest neighbours are 0.5 away. Point B is isolated, and its nearest neighbours are 5.0 away. A single shared sigma would cause one of two failures:
- If sigma is small enough to suit A, B's Gaussian is so narrow that every probability underflows toward zero before normalisation. B ends up with an arbitrary, unstable neighbourhood.
- If sigma is large enough to suit B, A's Gaussian covers far too many points, and A's local structure is blurred.
Per-point bandwidths fix this. Each point adapts its Gaussian to its local density, so every point has a neighbourhood of roughly the same effective size. The tool for choosing sigmai is perplexity, which is the next chapter's topic. For now, treat it as a number you set, and treat sigmai as the value found by a search so that the point's distribution has that perplexity.
A small worked computation
The code below computes the conditional probabilities for a tiny dataset with a fixed sigma, so you can see the normalisation at work. It uses only NumPy.
import numpy as np
X = np.array([[0.0, 0.0],
[1.0, 0.0],
[0.0, 1.5],
[5.0, 5.0]])
sigma = 1.0
# Squared Euclidean distances between all pairs
diff = X[:, None, :] - X[None, :, :]
D2 = (diff ** 2).sum(axis=2)
# Gaussian affinities, with the diagonal set to zero
W = np.exp(-D2 / (2 * sigma ** 2))
np.fill_diagonal(W, 0.0)
# Normalise each row so it sums to 1: row i holds p(j|i)
P_cond = W / W.sum(axis=1, keepdims=True)
np.set_printoptions(precision=3, suppress=True)
print(P_cond)
print("row sums:", P_cond.sum(axis=1))Look at the output. Row 0 gives almost all of its probability to points 1 and 2, because they are close to point 0. Point 3 is far from everything, yet its row still sums to 1. All of its probability goes to whichever point is nearest, even though that point is far away in absolute terms. This is a known property of the row normalisation. It guarantees that every point takes part in the embedding, but it also means a row of probabilities says nothing about how far away the neighbours actually are.
Symmetrising into joint probabilities
The conditional probabilities are not symmetric. In general p(j|i) differs from p(i|j), because the two points have different bandwidths. The optimisation in the low-dimensional space is easier to define with a single joint distribution over pairs, so t-SNE symmetrises:
p_ij = (p(j|i) + p(i|j)) / (2n)Here n is the number of points. The sum of all p_ij over all pairs is 1, so P is a proper probability distribution over pairs of points.
Dividing by 2n instead of 2 also matters for outliers. Because each row of the conditional matrix sums to 1, each point i satisfies sum over j of p_ij >= 1/(2n). Even the isolated point in the example above therefore contributes at least a small, guaranteed amount of total probability. Without symmetrisation, an outlier would have almost no pull on its position, because nobody would list it as a neighbour. With it, the outlier's own row ensures it is still attached to the layout.
# Continuing from the previous example
n = X.shape[0]
P = (P_cond + P_cond.T) / (2 * n)
print("total mass:", P.sum())
print("symmetric:", np.allclose(P, P.T))
print("row sums (each >= 1/(2n) = %.3f):" % (1 / (2 * n)))
print(P.sum(axis=1))Run it after the earlier block. Total mass is 1, the matrix is symmetric, and every row sum is at least 1/(2n). Point 3 is the one that sits near that lower bound.
Sparse affinities in practice
Computing the full n by n matrix is O(n²) in time and memory. Real implementations avoid this because most entries are negligibly small. scikit-learn's TSNE with the default method="barnes_hut" computes the nearest neighbours of each point only, using roughly 3 × perplexity neighbours, and sets all other probabilities to zero. The result is a sparse matrix P. This is an approximation of the Gaussian definition, but the dropped entries are tiny when the bandwidth is chosen by perplexity, so the layout barely changes.
This has one consequence worth remembering. With perplexity 30, each point is represented by about 90 neighbours. Raising perplexity raises both the effective neighbourhood size and the cost.
Common errors and gotchas
- Unscaled features. The Gaussian uses Euclidean distance, so a feature with a large numeric range dominates. Standardise features first when units differ. The digits data used in this tutorial has features on a common 0 to 16 scale, so it does not need this.
- Very high dimensions. In hundreds or thousands of dimensions, distances between points concentrate: the nearest and farthest neighbours end up at similar distances. The Gaussian then has little contrast to work with. Reducing to 30 to 50 dimensions with PCA first is a common remedy, and it also speeds up the neighbour search.
- Duplicate points. Identical rows have zero distance and receive the same probabilities. This is harmless to the probabilities, but the duplicates land on top of each other in the plot and hide the true count.
- Reading P as distances. P records relative neighbour rank within each point's neighbourhood. It does not preserve absolute distances, which is why inter-cluster distances in a t-SNE plot carry little meaning.
Checking your understanding
Exercise
A point sits in a very sparse region of the data, far from all other points. With a single shared sigma for all points, what goes wrong for this point? How does giving each point its own sigmai, and symmetrising to pij = (p(j|i) + p(i|j)) / (2n), address the problem?
Show answer
With a small shared sigma, the Gaussian values for this point's distant neighbours are all close to zero, so its probabilities depend on tiny numerical differences and are unstable. With a large shared sigma, dense regions get blurred. A per-point sigmai is chosen by a search so each point's distribution has the same perplexity, which adapts the neighbourhood to local density. Symmetrising then guarantees that the sum of pij over j is at least 1/(2n), so the outlier is still pulled toward its nearest neighbours in the embedding instead of being ignored.
Exercise
In the NumPy example, change the fixed sigma from 1.0 to 0.3 and then to 5.0 and rerun it. Describe how the rows of P_cond change, and which row changes most for sigma = 5.0.
Show answer
With sigma = 0.3 each row becomes sharply peaked on its nearest point, so the probabilities are close to 1 for one neighbour and near 0 for the rest. With sigma = 5.0 the Gaussian is wide compared with the distances between the first three points, so rows 0 to 2 spread their probability almost evenly over the other points, including point 3. Row 3 changes most in relative terms, since at small sigma it sends essentially all its mass to one point, and at large sigma it spreads its mass across all three others. In every case, each row still sums to 1.