Sub topic 7
Perplexity as an effective neighbourhood size
This chapter assumes you know basic Python and NumPy, the scikit-learn fit/fit_transform interface, Euclidean distance, and basic probability (distributions and normalisation). It builds on the previous chapter, where t-SNE turns distances into conditional probabilities. Here we look at the one setting that controls how those probabilities are spread: perplexity.
The problem perplexity solves
In t-SNE step 1, each point i gets a Gaussian centred on it. The probability that i picks j as a neighbour is
p(j | i) = exp(−‖xᵢ − xⱼ‖² / 2σᵢ²) / Σₖ≠ᵢ exp(−‖xᵢ − xₖ‖² / 2σᵢ²)
The bandwidth σᵢ decides how far the Gaussian reaches. A small σᵢ puts almost all the probability on the nearest one or two points. A large σᵢ spreads it over many points.
Data is rarely uniform. A point in a dense cluster has many close neighbours, and a point in a sparse region has few. One shared σ would be too wide in dense regions and too narrow in sparse ones. t-SNE therefore picks a separate σᵢ for every point. The question is what rule to use. The answer is perplexity.
Definition
For point i, the distribution Pᵢ = p(· | i) has Shannon entropy
H(Pᵢ) = −Σⱼ p(j | i) log₂ p(j | i)
Perplexity is
Perp(Pᵢ) = 2^H(Pᵢ)
If Pᵢ were uniform over k points, its entropy would be log₂ k and its perplexity would be exactly k. So perplexity is the number of neighbours a point effectively has. A perplexity of 30 means "spread the probability about as widely as if there were 30 equally likely neighbours".
Real distributions are not uniform. Close points get most of the weight and distant points get a little. Perplexity summarises that spread as one number, which need not be an integer.
t-SNE takes perplexity as a user setting and searches for the σᵢ that gives every point that same perplexity. Entropy increases monotonically with σᵢ, so a binary search finds it quickly.
Computing it yourself
The following code finds σ for one point by binary search and checks that the resulting perplexity matches the target.
import numpy as np
from sklearn.datasets import load_digits
from scipy.spatial.distance import cdist
X, _ = load_digits(return_X_y=True)
i = 0
d2 = cdist(X[i:i + 1], X, "sqeuclidean").ravel()
d2 = np.delete(d2, i) # a point is not its own neighbour
def perplexity_for(sigma, d2):
logits = -d2 / (2 * sigma ** 2)
logits -= logits.max() # numerical stability
p = np.exp(logits)
p /= p.sum()
p = p[p > 0]
return 2 ** (-(p * np.log2(p)).sum())
def find_sigma(d2, target, tol=1e-5, max_iter=100):
lo, hi = 1e-10, 1e4
for _ in range(max_iter):
mid = (lo + hi) / 2
perp = perplexity_for(mid, d2)
if abs(perp - target) < tol:
break
if perp > target:
hi = mid # too wide, shrink sigma
else:
lo = mid # too narrow, grow sigma
return mid
for target in [5, 30, 100]:
sigma = find_sigma(d2, target)
print(f"target {target:>3}: sigma = {sigma:6.2f}, "
f"perplexity = {perplexity_for(sigma, d2):6.2f}")The printed σ grows with the target while the achieved perplexity matches it. This is the mechanism inside scikit-learn's TSNE, though it runs on a restricted set of nearest neighbours rather than all points.
What the setting does to the plot
Perplexity changes how much of the data each point "sees" when the layout is built.
- Low perplexity (about 2 to 10). Each point attends to a handful of neighbours. The embedding preserves very fine local structure. Real clusters often break into small fragments, and noise can form tiny false clusters.
- Moderate perplexity (about 20 to 50). This balances local detail and larger groupings. It is the usual starting range, and 30 is the scikit-learn default.
- High perplexity (about 100 and above). Each point sees a large share of the data. Fine detail blurs, and the plot starts to reflect broader structure. Runtime also grows.
from sklearn.datasets import load_digits
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
X, y = load_digits(return_X_y=True)
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
for ax, perp in zip(axes, [5, 30, 100]):
Z = TSNE(perplexity=perp, init="pca", learning_rate="auto",
random_state=0).fit_transform(X)
ax.scatter(Z[:, 0], Z[:, 1], c=y, cmap="tab10", s=6)
ax.set_title(f"perplexity = {perp}")
plt.show()The digits data has 1,797 points. At perplexity 5 you should see the digit classes split into several islands. At 30 they should be mostly compact and separate. At 100 the groups are larger and sit closer together.
Choosing a value
Use these rules as a starting point.
- Start at 30 and try a few values across a range, such as 5, 15, 30, 50 and 100.
- Scale to the data. Perplexity must be smaller than the number of samples. scikit-learn raises an error when it is not. For small datasets, try values between 5 and 10 percent of
n, and stay well belown. - Prefer features that are stable across settings. A cluster that appears at perplexity 15, 30 and 50 is more credible than one that only appears at 5.
- For very large datasets, higher values (several hundred) can help preserve global layout, at greater cost.
You can back the choice with a number by computing trustworthiness for each setting, as covered in the chapter on quality metrics. Do not pick a value only because the picture looks tidy.
Common errors
- Reading perplexity as "number of neighbours" exactly. It is an effective count from a smooth weighting. Points beyond that count still get a little weight.
- Perplexity at or above the sample count. This fails or produces a meaningless uniform distribution.
- Comparing runs with different perplexities as if they were the same map. Cluster sizes and gaps change, so differences are not evidence of anything about the data.
- Interpreting one run. Fix
random_statefor reproducibility, and still check that the main structure survives several seeds and values. - Forgetting preprocessing. Perplexity is computed from distances, so unscaled features change which points count as near. Standardise features when their units differ.
Link to UMAP
UMAP has a similar control. Its n_neighbors parameter also sets the local scale. UMAP uses a fixed number of neighbours and fits a per-point scale to it, which later chapters cover. The idea is the same: one setting trades local detail against broader structure.
Exercise
A point has a probability distribution over its neighbours that is uniform over exactly 40 points and zero elsewhere. What is its perplexity? If t-SNE is run with perplexity 30, will it need a larger or a smaller σ for this point than the one that produced this distribution, and why?
Show answer
The entropy is log₂ 40, so the perplexity is 2^(log₂ 40) = 40. A target of 30 is lower, so the distribution must be more concentrated. Entropy increases with σ, so t-SNE has to shrink σ for this point until the effective neighbour count falls from 40 to 30.
Exercise
You run t-SNE on 200 samples with perplexity 250. What goes wrong, and what would you try instead?
Show answer
Perplexity must be smaller than the number of samples, because a point cannot have more effective neighbours than there are other points. scikit-learn raises an error. Use a value well below 200, for example between 5 and 30, and compare a few values.