Sub topic 7
Perplexity as an effective neighbourhood size
This chapter assumes you know the t-SNE affinities from the previous chapter: each point i turns its distances into a probability distribution P(j | i) over the other points, using a Gaussian with width σᵢ. Here you will see how perplexity sets that width.
What perplexity measures
For point i, the distribution P(· | i) has a Shannon entropy H (in bits). Perplexity is 2 raised to that entropy:
Perp(Pᵢ) = 2^H(Pᵢ)
If a point spreads its probability evenly over k neighbours, its perplexity is exactly k. Real distributions are uneven, so perplexity is best read as "the number of neighbours this point effectively has".
import numpy as np
def perplexity(p):
p = p[p > 0]
return 2 ** (-(p * np.log2(p)).sum())
print(round(perplexity(np.full(30, 1 / 30)), 3)) # 30.0How t-SNE uses it
You do not set σᵢ directly. You set one perplexity for the whole run, and t-SNE searches for each point's σᵢ separately.
- Pick a candidate σᵢ and compute P(· | i).
- Compute its perplexity.
- Binary-search σᵢ until the perplexity matches your target.
A narrow Gaussian concentrates probability on a few neighbours and gives low perplexity. A wide one spreads it out and gives high perplexity.
Because the search runs per point, σᵢ adapts to local density. Points in dense regions get small σᵢ. Points in sparse regions get large σᵢ. Every point ends up with about the same effective neighbour count.
Seeing the effect
Run the same data at three settings:
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()| Perplexity | Typical result |
|---|---|
| Low (about 5) | Very local view. Classes break into many small islands, some of them noise. |
| Medium (about 30) | Balanced. Classes form clear groups. |
| High (about 100) | More global view. Groups sit closer together and fine detail blurs. |
Common errors
- Perplexity must be smaller than the number of samples. scikit-learn raises an error otherwise.
- Small datasets need small values. With 100 points, a perplexity of 50 means every point treats half the data as a neighbour.
- Do not trust one setting. A cluster that appears only at one perplexity may be an artefact.
- Perplexity is not a count of neighbours. It does not cut anything off. Distant points still get small, non-zero probability.
Exercise
A point has probability 0.25 on each of four neighbours and zero on every other point. What is its perplexity, and what does that tell you?
Show answer
The entropy is -4 × 0.25 × log2(0.25) = 2 bits, so the perplexity is 2^2 = 4. The point behaves as if it has exactly four equally weighted neighbours.