Sub topic 10
Optimising t-SNE: initialisation, early exaggeration and learning rate
This chapter assumes you know how t-SNE builds its high-dimensional affinities, the Student-t kernel, and the KL divergence objective. It also assumes you know basic gradient descent and the scikit-learn fit_transform interface. Here we look at how the optimiser minimises that objective, and which three settings decide whether it finds a good layout.
The optimisation problem
t-SNE minimises the KL divergence between the high-dimensional affinities P and the low-dimensional affinities Q by gradient descent on the embedding coordinates. For point i, the gradient is:
dC/dy_i = 4 * sum_j (p_ij - q_ij) * (y_i - y_j) / (1 + ||y_i - y_j||^2)Each term acts like a spring between two points. If pij is larger than qij, the points are closer in the original space than in the map, so they attract. If q_ij is larger, they repel.
The objective is non-convex. Different starting points and step sizes can end in different local minima. Three settings shape the path:
- Initialisation: where the points start.
- Early exaggeration: a temporary boost to attraction at the start.
- Learning rate: how far each update moves a point.
scikit-learn also uses momentum (0.5 in the early phase, 0.8 afterwards) and per-parameter adaptive gains. You can't tune these through the public API.
Initialisation
Random initialisation draws points from a tiny Gaussian, with a standard deviation of about 1e-4. The layout starts as a featureless blob. Points that are far apart in the original space can end up near each other early on, and the optimiser has to untangle them.
PCA initialisation starts from the first two principal components, rescaled so the first component has a standard deviation of 1e-4. The starting layout already has the global arrangement of the data. Because the optimiser mostly preserves that arrangement, the final plot keeps more of the large-scale structure. Kobak and Berens (2019) showed that this also makes results more reproducible across seeds.
Since scikit-learn 1.2, init="pca" is the default. If you use an older version, set it explicitly.
Two caveats apply:
- PCA initialisation is deterministic up to the solver. Different seeds then give nearly the same picture, which can look like stability when it only reflects the shared start. Judge reliability by varying perplexity as well as the seed.
init="pca"is not allowed withmetric="precomputed". Useinit="random"there.
from sklearn.datasets import load_digits
from sklearn.manifold import TSNE, trustworthiness
X, y = load_digits(return_X_y=True)
for init in ["random", "pca"]:
tsne = TSNE(perplexity=30, init=init, learning_rate="auto",
random_state=0)
Z = tsne.fit_transform(X)
print(f"init={init:6s} KL={tsne.kl_divergence_:.3f} "
f"iterations={tsne.n_iter_} "
f"trustworthiness={trustworthiness(X, Z, n_neighbors=10):.3f}")The fitted attributes kl_divergence_ and n_iter_ let you check convergence. A lower KL at the same perplexity means a better fit to the same target. You can't compare KL values across different perplexities, because P itself changes.
Early exaggeration
During the first phase, scikit-learn multiplies every pij by `earlyexaggeration` (default 12). With larger P values, attraction dominates the gradient. Points in the same neighbourhood pull together into tight, well-separated clumps that can move through the empty space around them. Clusters can then migrate and merge or separate while the layout is still flexible. After about 250 iterations, the multiplier is removed and the repulsion in Q spreads the clumps out.
The effect in practice:
- Too low a value (for example 1), or a very short exaggeration phase, can leave clusters fragmented. A true cluster may be split into several islands that never rejoin.
- Higher values (for example 20 to 50) form tighter clumps, but they mainly matter on large datasets where the default does not converge.
- The value interacts with the learning rate. Linderman and Steinerberger (2019) showed that early exaggeration works as intended when the learning rate times the exaggeration factor is on the order of the number of points.
Learning rate
The learning rate scales each gradient step.
- Too small: points barely move. The plot looks like a dense ball and the KL stays high. The run may stop because of
n_iter_without_progress, not because it converged. - Too large: points scatter. A common symptom is a round ring of evenly spaced points with no structure inside it (the "ball" or "ring" artefact), and a KL that does not fall.
- Well chosen: the KL falls steadily and the clusters separate.
In scikit-learn, learning_rate="auto" sets the value to max(N / early_exaggeration / 4, 50), where N is the number of samples. Belkina et al. (2019) and Kobak and Berens (2019) recommend a rate of about N/12 for large data. scikit-learn's extra factor of 4 reflects how its updates are scaled. For the digits data (N = 1797), auto gives max(1797 / 12 / 4, 50), which is 50, because the floor applies. Use "auto" unless you have a reason not to.
from sklearn.datasets import load_digits
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
X, y = load_digits(return_X_y=True)
rates = [5, 50, 500, 5000]
fig, axes = plt.subplots(1, len(rates), figsize=(18, 4.5))
for ax, lr in zip(axes, rates):
tsne = TSNE(perplexity=30, init="pca", learning_rate=lr,
random_state=0)
Z = tsne.fit_transform(X)
ax.scatter(Z[:, 0], Z[:, 1], c=y, cmap="tab10", s=5)
ax.set_title(f"lr={lr} KL={tsne.kl_divergence_:.2f}")
plt.show()Convergence and diagnostics
Look at these signals before you trust a plot:
kl_divergence_is the final cost. Compare it only between runs with the same data and perplexity.n_iter_equal to the maximum means the run was cut off. Increase the iteration budget and see whether the picture changes.- A run that ends early because of
n_iter_without_progress(default 300) ormin_grad_normmay have stalled because of a poor learning rate, not because it converged. - Passing
verbose=2prints the KL every 50 iterations, so you can see the exaggeration phase end and watch the cost drop afterwards.
A practical recipe when a plot looks wrong:
- Use
init="pca"andlearning_rate="auto". - If the plot is a blob, raise the iteration budget before changing anything else.
- If you see a ring of evenly spaced points, lower the learning rate.
- If clusters look fragmented, try a larger perplexity or a higher early exaggeration.
- Re-run with two other seeds and confirm the structure you care about persists.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Dense ball, no clusters | Learning rate too low, or too few iterations | Use `"auto"`, raise the iteration budget |
| Ring of evenly spaced points | Learning rate too high | Lower the learning rate |
| One true cluster split into islands | Weak early exaggeration, or random init | Use PCA init, raise exaggeration |
| Different seeds give different global layouts | Random initialisation | Use PCA init |
| Same picture for every seed, assumed "stable" | PCA init hides variation | Also vary perplexity |
Exercise
You run TSNE on 60,000 points with init="random" and learningrate=10. The plot is a single dense blob and niter_ equals the maximum. Name two changes you would try first, and explain why each addresses the symptom.
Show answer
First, set learning_rate="auto" (or about N/12, which is 5,000 for 60,000 points). A rate of 10 is far too small for this N, so points barely move and the optimiser hasn't converged. Second, set init="pca". A PCA start gives the optimiser a sensible global layout and removes the need to untangle random starting positions. You could also raise the iteration budget, since the run stopped at the maximum.
Exercise
Two t-SNE runs on the same data use different perplexities, and the first has a KL of 1.4 and the second 1.9. Can you conclude that the first embedding is better? Why or why not?
Show answer
No. Perplexity changes the high-dimensional affinities P, so the two runs minimise different objectives. KL values are only comparable between runs on the same data with the same perplexity, for example when you compare initialisations or learning rates. To compare embeddings across perplexities, use a measure defined independently of P, such as trustworthiness.