Sub topic 9
The KL divergence objective
This chapter covers the quantity t-SNE minimises and what that choice does to the plots. It assumes you know how t-SNE builds the high-dimensional affinities p_ij from perplexity, and that the low-dimensional affinities q_ij use a Student-t kernel. It also assumes you know basic logarithms and gradient descent.
From two sets of affinities to one number
t-SNE produces two similarity matrices over the same n points:
Pcomes from the original data. Each entryp_ijis the symmetrised probability that points i and j are neighbours.Qcomes from the current 2-D layout. Each entryq_ijuses the heavy-tailed kernel:
q_ij = (1 + ||y_i - y_j||^2)^-1 / sum over k != l of (1 + ||y_k - y_l||^2)^-1Both matrices are normalised so that all off-diagonal entries sum to 1. Each is therefore a single probability distribution over pairs of points. To compare two distributions, t-SNE uses the Kullback-Leibler (KL) divergence:
C = KL(P || Q) = sum over i != j of p_ij * log(p_ij / q_ij)C is zero only when Q equals P exactly, and it is never negative. Moving the points y_i changes Q, so t-SNE searches for the layout that makes Q as close to P as possible.
KL is asymmetric, and that is the point
KL(P || Q) is not the same as KL(Q || P). Each pair contributes p_ij * log(p_ij / q_ij), weighted by p_ij. That weighting produces two very different penalties:
- Large
p_ij, smallq_ij. Two true neighbours are placed far apart. The log term is large and the weight is large, so the cost is high. - Small
p_ij, largeq_ij. Two unrelated points are placed close together. The log term is negative and the weight is tiny, so the cost is almost nothing.
The optimiser is therefore strongly pushed to keep neighbours together. It is barely pushed to keep non-neighbours apart. This explains why t-SNE preserves local structure well and tells you little about global structure.
The next script prints the cost of a single pair for both situations.
import numpy as np
def pair_cost(p, q):
"""Contribution of one pair to KL(P || Q)."""
return p * np.log(p / q)
print("True neighbours (p = 0.1), placed with q = ...")
for q in [0.1, 0.01, 0.001]:
print(f" q = {q:<6} cost = {pair_cost(0.1, q):+.4f}")
print("Unrelated points (p = 0.001), placed with q = ...")
for q in [0.001, 0.01, 0.1]:
print(f" q = {q:<6} cost = {pair_cost(0.001, q):+.4f}")Splitting a true neighbour pair by a factor of 100 costs about +0.46. Putting unrelated points 100 times too close changes the cost by about -0.005. In the full sum, the normalisation of Q keeps the total non-negative, but the push against unrelated points that sit too close is much weaker than the pull between neighbours.
The gradient: attraction and repulsion
The gradient with respect to one point has a compact form:
dC/dy_i = 4 * sum over j of (p_ij - q_ij) * (y_i - y_j) * (1 + ||y_i - y_j||^2)^-1Read the sign of (p_ij - q_ij) for each other point j:
| Situation | Sign of `p_ij - q_ij` | Effect on `y_i` |
|---|---|---|
| Points are closer in 2-D than the data justifies (`q_ij > p_ij`) | Negative | Pushed away from `y_j` |
| Points are farther in 2-D than the data justifies (`q_ij < p_ij`) | Positive | Pulled toward `y_j` |
| `q_ij` matches `p_ij` | Zero | No force from this pair |
The last factor, (1 + d^2)^-1, shrinks the force between distant pairs. Faraway points influence each other little, which helps clusters separate without being disturbed by the rest of the map. Standard gradient descent with momentum then updates the layout, as covered in the next chapter on optimisation.
What the value of C tells you
scikit-learn stores the final objective value in the kl_divergence_ attribute. Lower is a better fit between P and Q. You can compare runs on the same data with the same perplexity, for example to pick the best of several random seeds.
from sklearn.datasets import load_digits
from sklearn.manifold import TSNE
X, y = load_digits(return_X_y=True)
for seed in range(3):
tsne = TSNE(perplexity=30, init="random", learning_rate="auto",
random_state=seed)
tsne.fit_transform(X)
print(f"seed {seed}: KL = {tsne.kl_divergence_:.3f}, "
f"iterations = {tsne.n_iter_}")The three values differ because the loss surface is non-convex and different starting layouts end in different local minima. A run with a lower KL has fit P better. That is evidence about that run, not proof that its picture is more useful.
Why you cannot compare KL across settings
Do not compare KL values between different perplexities, different datasets, or different preprocessing. Changing the perplexity changes P itself, so the two numbers measure the fit to two different targets. A perplexity of 5 gives a very sparse P that can be matched more closely than a smooth P at perplexity 100, and so it often scores a lower KL. That does not make its picture better. To compare methods or parameter settings, use a measure computed against the original neighbourhoods, such as trustworthiness, which a later chapter covers.
Consequences you will see in plots
The asymmetry has direct effects when you read an embedding:
- Cluster separation is cheap to fake. Pushing unrelated groups together costs little, and the optimiser has no strong reason to keep them at faithful distances. The gaps between clusters are not reliable.
- Cluster sizes are not densities. Perplexity-based bandwidths adapt to local density, so
Palready normalises density away. Equal-looking blobs can come from very different densities. - Tearing a cluster is costly. If true neighbours end up apart, the loss goes up sharply. This is why t-SNE rarely splits a genuine cluster, and why you should suspect a real substructure when it does.
- Dense points far apart in 2-D are common. The loss treats missed neighbours as the serious error and stray proximity as a minor one.
Common mistakes
- Reporting
kl_divergence_as an accuracy score. It is not bounded by 1 and has no fixed scale. - Treating a lower KL from a different perplexity as a better embedding.
- Running one seed and trusting its KL. Run a few seeds and look at both the values and the pictures.
- Expecting zero. Because
Qis a 2-D layout of data that is not truly 2-D, a perfect match is impossible, and a final KL well above zero is normal.
Exercise
Two true neighbours (pij = 0.05) are placed with qij = 0.005. Separately, two unrelated points (pij = 0.0005) are placed with qij = 0.005. Using pair_cost(p, q) = p * ln(p / q), which pair costs more, and what does this say about which mistake t-SNE punishes?
Show answer
The first pair costs 0.05 ln(10), about +0.115. The second pair costs 0.0005 ln(0.1), about -0.00115, which is negligible in magnitude and slightly negative. Splitting true neighbours is punished heavily, while placing unrelated points too close is barely punished. So t-SNE keeps local neighbourhoods but says little reliable about global distances.
Exercise
You run t-SNE with perplexity 5 and get kldivergence = 0.8, then with perplexity 50 and get 1.4. Can you conclude the perplexity-5 embedding is better?
Show answer
No. The two runs minimise the divergence to different P matrices, so the numbers are not comparable. Judge the settings with a measure computed against the original neighbourhoods, such as trustworthiness, and by inspecting several seeds.