t-SNE (t-Distributed Stochastic Neighbor Embedding) › Building the Mathematical Foundation
Machine Learning from ScratchAll chapters t-SNE (t-Distributed Stochastic Neighbor Embedding) › Building the Mathematical FoundationOne section · Sections in this chapter2 / 8 ↓
Reading tools Definitions & inline links
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
To understand how t-SNE works, we need to follow its core logic: the algorithm tries to preserve relationships between nearby points when moving from high dimensions to low dimensions. Instead of trying to preserve exact distances, t-SNE preserves similarities. Think of it as keeping friends close together rather than measuring exact distances between people in a room.
The algorithm operates in three main steps. First, it measures how similar points are in the original high-dimensional space. Second, it creates a low-dimensional representation and measures similarities there. Third, it adjusts the low-dimensional positions until the two sets of similarities match as closely as possible.
Measuring similarities in high-dimensional space
We start with our original data points and in high-dimensional space. The first step is straightforward: compute how far apart these points are using squared Euclidean distance.
where:
- : the -th data point in the original high-dimensional space
- : the -th data point in the original high-dimensional space
- : squared Euclidean distance between points and
- : squared L2 norm (sum of squared differences across all dimensions)
This gives us raw distances, but t-SNE doesn't work directly with distances. Instead, it converts them into probabilities that express similarity. Why probabilities? Because they naturally normalize the scale and make similarities relative rather than absolute. A distance of 5 units means something different if most points are separated by 100 units versus if most are separated by 1 unit.
To convert distances into similarities, we use a Gaussian (normal) distribution centered at each point. The conditional probability represents the probability that point would pick as its neighbor if neighbors were selected in proportion to their probability density under this Gaussian.
where:
- : conditional probability that point picks point as its neighbor
- : bandwidth of the Gaussian kernel centered at point (controls the effective neighborhood size)
- : exponential function (converts distances to similarities)
- : sum over all points except point (normalization)
Let's break down what each part does:
- The numerator gives higher values to closer points and lower values to distant points. The exponential ensures all values are positive.
- The variance controls the width of the Gaussian. Larger means we consider more distant neighbors.
- The denominator normalizes these values so they sum to 1, making them proper probabilities.
The variance is different for each point, which is unusual but important. In dense regions of the data, we use smaller to focus on very close neighbors. In sparse regions, we use larger to capture the local structure. The perplexity parameter controls these variances indirectly. Higher perplexity means the Gaussian is wider, effectively considering more neighbors.
Now we have conditional probabilities , but there's a problem: might not equal . To fix this asymmetry, we symmetrize by averaging:
where:
- : symmetric joint probability of similarity between points and
- : total number of data points in the dataset
- The factor ensures that
This gives us a symmetric joint probability distribution where . The division by ensures all probabilities sum to 1 over all pairs. These symmetrized probabilities represent our target: they encode which points should be close together in the visualization.
Measuring similarities in low-dimensional space
Next, we need to measure similarities in the low-dimensional space where we want to visualize our data. Let and be the low-dimensional coordinates we're trying to find. We could use the same Gaussian distribution here, but that creates a problem called crowding.
The crowding problem happens because high-dimensional spaces have much more "room" than low-dimensional spaces. Imagine 100 points evenly distributed in 50 dimensions. When we try to place them in 2 dimensions while keeping all pairwise distances the same, they'll be forced too close together in the center. Moderate distances in high dimensions become impossible to represent in low dimensions.
To solve this, t-SNE uses a heavy-tailed distribution in low dimensions: the Student t-distribution with one degree of freedom (also called the Cauchy distribution). The similarity between points and is:
where:
- : similarity between points and in the low-dimensional space
- : low-dimensional representation of point (coordinates we're optimizing)
- : low-dimensional representation of point
- : squared Euclidean distance between points in low-dimensional space
- : Student t-distribution kernel with one degree of freedom
- : sum over all distinct pairs of points for normalization
The key difference from the Gaussian is instead of . The t-distribution has heavier tails, meaning it decreases more slowly as distance increases. This allows moderately distant points in low dimensions to still have reasonable similarity values, giving them room to spread out instead of crowding in the center.
The denominator again normalizes to make these proper probabilities that sum to 1.
Finding the right low-dimensional positions
Now we have two probability distributions: representing similarities we want to preserve from the high-dimensional space, and representing similarities in our current low-dimensional representation. We need to adjust the positions until these distributions match.
To measure how well they match, t-SNE uses the Kullback-Leibler (KL) divergence, a standard measure of how different two probability distributions are:
where:
- : Kullback-Leibler divergence (cost function to minimize)
- : target similarity between points and in high-dimensional space
- : current similarity between points and in low-dimensional space
- : natural logarithm
- The sum is over all pairs of points
The KL divergence has useful properties for this task. When is large (points should be close) but is small (they're far apart), the log ratio is large and positive, heavily penalizing the mismatch. When and are both small (points should be far apart and are), the contribution is minimal. The cost function is asymmetric: it cares more about keeping close points together than about separating distant points, which aligns with t-SNE's goal of preserving local structure.
To minimize this cost, we use gradient descent. We need the derivative of the cost with respect to each low-dimensional position :
where:
- : gradient of the cost function with respect to position
- The sum is over all other points
- : difference between target and current similarities
- : vector pointing from to in low-dimensional space
- : weighting factor from the t-distribution
- The factor of 4 comes from the derivative of the symmetrized KL divergence
This gradient has an elegant interpretation. For each pair of points:
- If (points should be closer than they are), the term is positive. The gradient pulls toward .
- If (points should be farther apart), the term is negative. The gradient pushes away from .
- The magnitude of the force depends on how different the probabilities are.
- The factor comes from the t-distribution and ensures the gradient doesn't explode for distant points.
The algorithm iteratively updates each by taking small steps in the direction opposite to this gradient, gradually moving points until the low-dimensional similarities match the high-dimensional similarities as closely as possible.
Key mathematical properties
Understanding a few mathematical properties helps explain t-SNE's behavior in practice.
Non-convexity and local minima: The cost function has multiple local minima because it's non-convex. Different random initializations can lead to different final configurations. This is why running t-SNE multiple times with different random seeds is important to ensure your visualization is stable.
Scale invariance: Multiplying all distances by a constant factor doesn't change the relative similarities. This means t-SNE results don't depend on the absolute scale of your data, only on the relative distances. However, the method is not rotation-invariant, so the orientation of your final visualization is arbitrary.
The role of perplexity: The perplexity parameter is a smoothness control. Lower values (5-15) create more localized neighborhoods. Higher values (30-50) create broader neighborhoods. The choice of perplexity significantly affects the result. A common default is 30, which typically balances local and global structure well for most datasets. The perplexity should generally be between 5 and 50, and you should try several values to see which gives the most interpretable visualization.