t-SNE: fit neighbor probabilities, then move the map
t-SNE
Build perplexity-based affinities and actually optimize a small embedding, while inspecting gradients, stopping rules and interpretation limits.
tsneA map that spends its space on neighbors
Six exhibits have two measured features: (0,0), (1,0), (0,1), (8,8), (9,8), (8,9). A one-dimensional display cannot preserve all distances among them. Which relationships should receive the scarce space?
t-SNE converts nearby relationships into probabilities and moves the displayed points to make a second probability distribution resemble the first. The coordinates are optimization variables. They are not predictions of a hidden physical position.
Our complete example reduces these two-dimensional observations to one dimension. It fits local probability scales, constructs a symmetric target, evaluates the Student-t map objective and updates every displayed coordinate. After 100 accepted updates, its KL objective falls from about 0.621114 to 0.000438. This is a small transparent optimization, with supplied initialization and full all-pairs calculations in floating point. It omits the original optimizer’s acceleration techniques.
Van der Maaten and Hinton’s 2008 paper introduced t-SNE as a development of stochastic neighbor embedding. Its important change is a heavy-tailed similarity function in the display, combined with symmetric input probabilities. Original paper
Two probability distributions and a nonconvex objective
Give each observation its own neighborhood scale
For each input observation, turn squared Euclidean distances into a conditional distribution over other records. The self probability is zero. With positive precision βᵢ, equivalent to 1/(2σᵢ²) where σᵢ is a standard deviation, define:
The logarithm here is natural; using base-two entropy and raising two to that entropy gives the same perplexity. Perplexity is a smooth effective neighbor count, not a hard number of retained edges or a number of clusters. Larger precision concentrates a row on close observations. Different rows generally need different precisions to reach the same perplexity. Paper §2
A useful search check follows by differentiation. If D denotes the squared distance under the current row distribution, then dH/dβ = −β Var(D), so entropy is nonincreasing as precision grows. At β = 0, the row is uniform over n−1 records. If m records tie for the smallest distance, the limiting distribution as β tends to infinity is uniform over those m records. Thus a strictly intermediate target must satisfy m < perplexity < n−1. The program requires this in every row; it does not claim to resolve an impossible target by more iterations.
For numerical evaluation, subtract the smallest squared distance before exponentiating. This cancels from the normalized distribution, makes the largest exponential one and avoids losing the whole denominator. Entropy is computed as log(sum(weights)) + beta × mean(shifted_distance). Small individual probabilities can still underflow; the implementation is not arbitrary-precision arithmetic.
Symmetrize before moving the map
The joint input distribution averages the two directions and divides by the number of observations:
The formulas for w and q apply off the diagonal; the code sets diagonal weights to zero. Both P and Q are normalized over ordered pairs, so the two directions of an edge both count. The input P is held fixed during optimization. Unlike the rowwise input Gaussian scales, Q has one global denominator.
The Student-t weight decays more slowly with distance than a Gaussian weight. It provides a way to place less similar observations farther apart while retaining nonnegligible interaction. This helps with crowding, but cannot make every high-dimensional configuration fit faithfully in one or two dimensions.
The objective and its gradient are:
Terms with pᵢⱼ = 0 contribute zero. To see the gradient, write C as a constant minus the weighted sum of log wᵢⱼ plus log Z, where Z is the sum of all off-diagonal weights. Differentiating the first term gives attraction weighted by P; differentiating the common normalizer gives repulsion weighted by Q. Symmetry and the two pair directions supply the factor four. Holding Q’s denominator fixed while differentiating would omit part of the objective. Paper §3 and Appendix A
When a pair has more target mass than displayed mass, its gradient contribution tends to pull it together under descent. Other pairs and the global denominator also matter. The objective is nonconvex in the coordinates. A lower value is evidence of a better fit to this fixed P, not a certificate of semantic accuracy or global optimality.
Actually optimize a small embedding
Run this Python 3.10+ standard-library program. fit_tsne accepts 3–12 observations with 1–4 aligned integer features in [-100,100], one finite initial scalar coordinate in the same range per record, an intermediate feasible perplexity, 0–200 steps and a positive initial step size at most 100. Booleans are rejected. These limits make the full computation inspectable; they are not general t-SNE requirements. conditional and objective are internal helpers whose inputs are prepared by fit_tsne.
Each row’s precision search uses at most 80 bracket expansions and 80 bisections, requiring absolute entropy error at most 1e-10. An infeasible tie count raises ValueError; failure to find a numerical bracket or tolerance raises ArithmeticError.
For the map, a gradient step is accepted only after an Armijo decrease check, halving the proposed size up to 30 trials:
Each trial is recentered to mean zero. Translation does not change pairwise distances, so this removes a redundant coordinate direction rather than changing the real-arithmetic objective. The check concerns the ordinary fixed-P objective: there is no early exaggeration, momentum, adaptive per-coordinate gain or negative sampling here.
import math
def conditional(distances, perplexity):
"""Internal helper: squared integer distances to other records only."""
nearest = min(distances)
shifts = tuple(d-nearest for d in distances)
if sum(d == nearest for d in distances) >= perplexity:
raise ValueError('perplexity must exceed every nearest-distance tie count')
target = math.log(perplexity)
def at(beta):
w = tuple(math.exp(-beta*d) for d in shifts)
z = math.fsum(w)
p = tuple(v/z for v in w)
entropy = math.log(z)+beta*math.fsum(a*d for a,d in zip(p,shifts))
return p,entropy
lo, hi = 0.0, 1.0
for _ in range(80):
if at(hi)[1] <= target: break
hi *= 2
else: raise ArithmeticError('perplexity bracket not found')
for _ in range(80):
beta = (lo+hi)/2
p,h = at(beta)
if abs(h-target) <= 1e-10: return p,beta,h
if h > target: lo = beta
else: hi = beta
raise ArithmeticError('perplexity tolerance not reached')
def objective(y, p):
"""Internal helper: ordered-pair KL and its analytic 1D gradient."""
n = len(y)
w = tuple(tuple(0.0 if i==j else 1/(1+(y[i]-y[j])**2)
for j in range(n)) for i in range(n))
z = math.fsum(v for row in w for v in row)
q = tuple(tuple(v/z for v in row) for row in w)
loss = math.fsum(p[i][j]*(math.log(p[i][j])-math.log(q[i][j]))
for i in range(n) for j in range(n) if p[i][j]>0)
grad = tuple(4*math.fsum((p[i][j]-q[i][j])*w[i][j]*(y[i]-y[j])
for j in range(n) if i!=j) for i in range(n))
return loss,grad,q
def fit_tsne(points, initial, perplexity=2.5, steps=100, rate=10):
if type(points) not in (list,tuple) or not 3<=len(points)<=12:
raise ValueError('provide 3 to 12 points')
if any(type(row) not in (list,tuple) for row in points):
raise ValueError('each point must be a list or tuple')
d = len(points[0]); n = len(points)
if not 1<=d<=4 or any(len(row)!=d for row in points):
raise ValueError('use 1 to 4 aligned features')
if any(type(x) is not int or abs(x)>100 for row in points for x in row):
raise ValueError('coordinates must be integers in [-100,100]')
if type(initial) not in (list,tuple) or len(initial)!=n:
raise ValueError('one initial scalar coordinate per point required')
if any(type(x) not in (int,float) or not -100<=x<=100 for x in initial):
raise ValueError('initial coordinates must be finite numbers in [-100,100]')
if type(perplexity) not in (int,float) or not 1<perplexity<n-1:
raise ValueError('perplexity must satisfy 1 < perplexity < n-1')
if type(steps) is not int or not 0<=steps<=200:
raise ValueError('steps must be an integer in 0..200')
if type(rate) not in (int,float) or not 0<rate<=100:
raise ValueError('rate must be finite in (0,100]')
xs = tuple(tuple(row) for row in points)
distances = tuple(tuple(sum((a-b)**2 for a,b in zip(x,z)) for z in xs) for x in xs)
rows, betas, entropies = [], [], []
for i in range(n):
ids = tuple(j for j in range(n) if j!=i)
ps,b,h = conditional(tuple(distances[i][j] for j in ids),perplexity)
row = [0.0]*n
for j,v in zip(ids,ps): row[j]=v
rows.append(tuple(row));betas.append(b);entropies.append(h)
p = tuple(tuple((rows[i][j]+rows[j][i])/(2*n) for j in range(n)) for i in range(n))
center = math.fsum(initial)/n
y = tuple(float(x-center) for x in initial)
loss,grad,q = objective(y,p)
trace = [(y,loss,0.0)]
status = 'step-limit'
for _ in range(steps):
if max(map(abs,grad)) <= 1e-10:
status = 'stationary'; break
norm2 = math.fsum(g*g for g in grad)
step = float(rate)
for _ in range(30):
candidate = tuple(x-step*g for x,g in zip(y,grad))
center = math.fsum(candidate)/n
candidate = tuple(x-center for x in candidate)
new_loss,new_grad,new_q = objective(candidate,p)
if new_loss <= loss-1e-4*step*norm2: break
step /= 2
else:
status = 'line-search-failed'; break
y,loss,grad,q = candidate,new_loss,new_grad,new_q
trace.append((y,loss,step))
return {'embedding':y,'p':p,'q':q,'conditionals':tuple(rows),
'betas':tuple(betas),'entropies':tuple(entropies),
'loss':loss,'gradient':grad,'trace':tuple(trace),
'steps_completed':len(trace)-1,'status':status}
if __name__ == '__main__':
xs = ((0,0),(1,0),(0,1),(8,8),(9,8),(8,9))
r = fit_tsne(xs,(-.3,-.2,-.1,.1,.2,.3))
print('KL:',format(r['trace'][0][1],'.6f'),'->',format(r['loss'],'.6f'))
print('embedding:',tuple(round(x,4) for x in r['embedding']))
print('row perplexities:',tuple(round(math.exp(h),6) for h in r['entropies']))
print('completed:',r['steps_completed'],r['status'])
stuck = fit_tsne(xs,(0,)*6)
print('coincident start:',stuck['steps_completed'],stuck['status'],format(stuck['loss'],'.6f'))
The executed output is:
KL: 0.621114 -> 0.000438
embedding: (-2.6488, -2.5459, -2.5459, 2.5057, 2.6175, 2.6174)
row perplexities: (2.5, 2.5, 2.5, 2.5, 2.5, 2.5)
completed: 100 step-limit
coincident start: 0 stationary 0.692635
trace contains the initial coordinates/loss and every accepted update with its actual step size. step-limit means the requested work finished. stationary means the largest absolute gradient component was at most 1e-10 when checked, not that the best embedding was found. line-search-failed preserves the last accepted model after all 30 candidate steps fail; it does not return the rejected trial. A zero step limit still computes and validates the input probabilities.
In the coincident initialization, every coordinate difference is zero, so the displayed gradient formula is exactly zero. The resulting KL is about 0.692635, worse than the separated run. This executed example makes the distinction between a stopping rule and an optimality certificate concrete. The main run ends with two tight groups, but the output does not recover all within-triangle input distances.
With n records, d features, at most A probability evaluations per row, T attempted map steps and at most B trial evaluations per step, the implementation costs O(n²(d+A+BT)) arithmetic work. Here A ≤ 160 and B ≤ 30. Dense probability arrays use O(n²) space and the retained optimization trace adds O(Tn). Floating-point evaluation, bounded teaching data and the full trace distinguish this implementation from scalable approximate solvers.
Read the plot as a fitted representation
A perplexity change changes P. The loss values of two runs with different perplexities are objectives for different target distributions. Comparing the smaller final KL alone does not select the more useful map. Similarly, rescaling some input features can change the neighborhood structure before optimization begins.
Map distances are not calibrated input distances. Local scales adapt across observations, and the optimization sacrifices some relationships to fit others. A dense-looking displayed group is not by itself evidence of higher original sampling density. Empty space, cluster area and the distance between separated islands should not be read as a numerical account of every original relationship. Inspect the corresponding input records and neighborhood measures, and compare reasonable settings and initializations.
An embedding does not discover verified classes. Coloring a map with labels can aid investigation; it does not make a label-consistent picture independent validation. Choosing preprocessing or parameters after viewing final evaluation labels also uses that information. If the map suggests a scientific or operational claim, test that claim using the original measurements and appropriate held-out evidence.
The optimizer matters. The original paper and modern libraries include additional procedures. Early exaggeration temporarily increases attractive target weights; its iterations are not descent steps for the same normalized P objective checked here. The fixed scikit-learn API documents initialization, early exaggeration, learning rate and exact versus Barnes–Hut methods. Different libraries can also use different learning-rate conventions. This program deliberately fixes its own convention and computes all pairs.
The nonparametric fit assigns coordinates to the supplied records. It does not train a general function that maps any future record to the display. Appending data and refitting can move existing points. A separate transformation method, or a parametric model, requires its own definition and evaluation.
Audit the probabilities before interpreting the map
1. A row has squared distances 1, 1 and 4. Can its perplexity be 1.5?
Answer: No under the finite-positive-precision construction. The two closest records are tied, so even the infinite-precision limit has entropy log 2 and perplexity 2. The program rejects targets at or below that tie count. At precision log(2)/3 the row probabilities are (0.4,0.4,0.2), giving perplexity about 2.872.
2. Why divide the symmetric probabilities by 2n?
Answer: Each of the n conditional rows sums to one, so summing both directional terms over ordered off-diagonal pairs gives 2n. Dividing by 2n makes the joint probabilities sum to one. Dividing only by two would leave total mass n and change the objective and gradient normalization.
3. Every initial map point is at zero. Is the returned stationary state a successful optimum?
Answer: Its gradient is zero because every coordinate difference is zero. Yet the executed example has KL about 0.692635, whereas the noncoincident initialization reaches about 0.000438. The stopping condition therefore does not establish the best fit, even before asking whether the representation is useful.
4. A trial step lowers no loss, or you change perplexity between runs. What comparison is valid?
Answer: A trial must satisfy the stated decrease condition for the same P before it enters the trace; exhausting the trial limit keeps the last accepted coordinates. Changing perplexity changes P, so the final KL values are not a direct contest on a common objective. Compare the neighborhood behavior and intended use as well as optimization diagnostics.
From a neighborhood objective to a usable visualization
The original t-SNE paper separates the input probability construction, the Student-t output model and the gradient calculation. That separation remains useful when implementations replace all-pairs computations with faster approximations or change optimization schedules. Its discussion of nonconvexity also explains why a reproducible initialization is part of an experiment, not proof of a unique answer. Original article
Compare PCA, which seeks a linear variance-preserving representation, with UMAP, which constructs a different weighted neighborhood graph and low-dimensional objective. For t-SNE experiments, the fixed TSNE documentation makes the implementation choices visible. Record those choices and retain the original observations alongside the map.
Make a prediction, then check
All initial map coordinates coincide and the gradient is zero. What does that prove?
Learning objectives
- Derive conditional and symmetric neighborhood probabilities and explain attainable perplexity with tied nearest distances.
- Differentiate the globally normalized Student-t objective and inspect actual coordinate updates.
- Separate numerical stopping, fixed-target fit and semantic interpretation of a map.
Prerequisites & connections
Explore related knowledge →References
- Visualizing Data using t-SNE
Laurens van der Maaten; Geoffrey Hinton · 2008 - TSNE — scikit-learn 1.7 API
scikit-learn developers · 2025
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.
- Eight tests pass. One conditional row with probabilities (0.4,0.4,0.2) has an independent closed-form precision log(2)/3, checked within 1e-9; nine additional row entropies are independently recomputed directly from probabilities. Forward dual-number differentiation of an unordered-edge KL expression checks four loss/gradient calculations and 24 gradient entries, differentiating through the global normalizer rather than reproducing the displayed analytic formula.
- The 100 accepted updates are checked against independently differentiated gradients and the Armijo condition. A coincident initialization supplies an executed worse stationary point. Translation/reflection, zero steps, probability normalization, input preservation and twelve invalid/infeasible configurations are tested. A failure stub forces all 30 trial losses to infinity to test line-search-failed and retention of the last accepted model; this is an injected control-flow check, not a natural data counterexample.
- Full original bilingual articles have identical complete Python, five executed stdout lines, four displays, six stable anchors and four answered exercises. Strict MDX/KaTeX plus actual React HTML pass and all four math annotations match. Humanizer prose reread completed; catalogue links use actual IDs.
- Written with AI author checks only. The full-pair floating-point model actually optimizes a one-dimensional embedding of bounded integer feature vectors; it is not merely a neighborhood calculator. It omits early exaggeration, momentum and approximate solvers. Probability-search and optimization limits/statuses, underflow scope, nonconvexity, nonparametric scope and O(n²(d+A+BT)) work/O(n²+Tn) storage are explicit. No global optimum, original-distance calibration, semantic labels, human review, production benchmark or whole-site acceptance claim.
- Root fully reread both articles, complete program, four equations and four answered exercises. Re-ran eight author tests and strict MDX/KaTeX/actual React HTML: four displays, six standard anchors and four answers match in both languages. No modification requested; final five SHA values match the frozen manifest.
- An independent analytic complex-valued log-distance expansion matches nine objective configurations and 45 partial derivatives across three fitted target distributions. It never constructs Q and does not propagate dual-number derivatives. Differences from the authored gradient stay below 2e-10; total gradient obeys translation invariance.
- At the six-point coincident start, an independent quadratic expansion along a cluster-separating direction has coefficient -2.1934987588. A small actual move lowers KL and matches that coefficient, confirming local improvability despite the stationary flag. Reviewed feasible perplexity ties, bounded numerical search, accepted-only trace, nonparametric scope and comparisons when P changes.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- Visualizing Data using t-SNE · Actually opened the original 27-page JMLR PDF. Header on printed page 2579 records submitted May, revised September and published November 2008. Read section 2, pp.2581–2582, for Gaussian conditional probabilities, self exclusion, entropy/perplexity and local scales; sections 3.1 and 3.3, pp.2583–2586, for symmetrization and the Student-t output kernel; the section 4 optimization passage on p.2588 for early exaggeration omitted from the basic pseudocode; section 6.2, pp.2598–2599, for nonconvexity and general-purpose dimensionality-reduction limitations; Appendix A, pp.2600–2601, for ordered-pair normalization and the complete gradient. Some extracted derivative notation is awkward, so the draft independently derives the log-normalizer gradient and tests it with forward automatic differentiation. No source examples, code, figures or benchmark claims are reproduced; text reading only, no visual PDF audit.
- TSNE — scikit-learn 1.7 API · Actually read fixed /1.7 API rendered 1.7.2: lines 620–646 signature, nonconvexity, perplexity, early exaggeration and learning-rate conventions; 676–693 initialization, different local minima and exact versus Barnes–Hut methods; 777–791 historical references. The teaching program has its own stricter input/perplexity limits and uses a full-gradient Armijo optimizer without claiming to reproduce this API. No sklearn run, universal library learning-rate conversion or performance comparison.
- Visualizing Data using t-SNE · Root independently opened original 27-page JMLR PDF. Read entropy/perplexity and local variance discussion lines 144–161; Student-t joint probabilities §3.3 lines 331–344; Appendix A pp.2600–2601, lines 862–936, KL, ordered-pair normalization and both point directions in differentiation. Some extracted derivative notation is awkward; verified the authored gradient independently by complex perturbations of a log-distance expansion. No original figures, benchmarks or whole-paper reading claimed.
- TSNE — scikit-learn 1.7 API · Root independently opened fixed /1.7/ API displaying 1.7.2. Read signature line 620; early exaggeration and learning-rate conventions lines 642–646, including the implementation-specific factor-four wording; iteration/stopping parameters lines 649–664. Did not transfer a library-specific rate convention or optimizer guarantee to the separate Armijo teaching program.
Related topics