Compute t-SNE input affinities with a perplexity search

Why it matters Every embedding visualisation of a model's latent space starts by computing these affinities.

t-SNE first turns distances into neighbour probabilities, choosing a bandwidth per point so every point has the same perplexity.

Write tsne_p(X, perplexity, tol=1e-5, iters=100). For each row i, binary-search beta_i (a precision, start lo=0, hi=inf, beta=1) so that the entropy H of p_j|i proportional to exp(-beta * ||x_i - x_j||^2) over j != i matches log(perplexity) (natural log) within tol. If H is too high, increase beta (double if hi is inf, else midpoint); otherwise decrease it (midpoint with lo). Then return the symmetric P = (P_cond + P_cond^T) / (2 n), with zeros on the diagonal.

Signaturedef tsne_p(X, perplexity, tol=1e-5, iters=100)

Example

for 2 points, each point's only neighbour gets probability 1, so P = [[0, 0.5], [0.5, 0]].

Understand the idea

t-SNE starts by turning distances into neighbour probabilities. Each point i uses a Gaussian with its own precision beta_i, chosen so the spread of its neighbour distribution matches a target perplexity (roughly the number of effective neighbours). Dense regions get narrow Gaussians and sparse regions wide ones. Worked example: point i has neighbours at squared distances 1 and 4, beta = 1. Weights exp(-1) = 0.368 and exp(-4) = 0.018 normalise to p = [0.953, 0.047]. Entropy H = -sum p ln p = about 0.191. For perplexity 2 the target is ln 2 = 0.693, so H is too low and beta must go down to widen the Gaussian. Rule: p_j|i is proportional to exp(-beta_i ||x_i - x_j||^2) for j != i; binary search beta_i so H matches ln(perplexity) within tol; raise beta when H is too high (double while hi is infinite, else midpoint), lower it otherwise. Finally P = (P_cond + P_cond^T) / (2n) with a zero diagonal. Used in: visualising embeddings, and the same affinity step appears in UMAP style methods.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampletsne_p([[0, 0], [1, 1]], 1.5)
  • Sample 2: randomtsne_p(_X, 3.0)