Sub topic 11
Barnes-Hut and FFT approximations for large data
This chapter assumes you know the t-SNE objective and gradient descent from earlier chapters, can use scikit-learn's fit_transform, and know what a tree data structure is. It explains why exact t-SNE becomes slow and how two approximations make it practical for large datasets.
Why exact t-SNE does not scale
t-SNE moves each embedded point under two kinds of force:
- An attractive force pulls a point toward the points that were its neighbours in the original space.
- A repulsive force pushes every point away from every other point, which spreads the map out.
The exact gradient for point i sums over all other points j. One iteration therefore costs O(N²) time. Storing the full matrix of high-dimensional affinities costs O(N²) memory. At 10,000 points that is 100 million pairs. At 1,000,000 points it is 10¹² pairs, which is not feasible.
The two forces have different structure, and that structure is what the approximations exploit.
- Attractive forces depend on the affinities p_ij. For a point, almost all of these are close to zero, so you can keep only the nearest neighbours. Implementations typically keep about 3 × perplexity neighbours per point. The attractive term is then sparse and costs O(N).
- Repulsive forces involve every pair, so they cannot be made sparse. This term needs a real approximation.
Sparse affinities and approximate neighbours
The first saving happens before optimisation starts. Instead of computing all N² distances, you search for each point's k nearest neighbours with k ≈ 3 × perplexity. You then set every other p_ij to zero.
Exact neighbour search in high dimensions is itself slow. Large-scale tools replace it with approximate search such as Annoy or pynndescent. These return neighbours that are almost always correct, and they cost far less than a brute-force scan. The error this introduces is usually small compared with the effect of choosing the perplexity.
Barnes-Hut: summarising distant points
Barnes-Hut comes from astrophysics, where it speeds up gravitational N-body simulation. The idea is that a group of points far from point i pushes on it almost as if the group were a single point at its centre of mass.
The algorithm has two steps:
- Build a quadtree over the current 2-D embedding. Each cell is split into four children, recursively. In 3-D this becomes an octree. Each cell stores its centre of mass and its point count.
- For each point i, walk the tree. If a cell's width r divided by its distance d to i is below a threshold θ, treat the whole cell as one point with weight equal to its count. Otherwise descend into its children.
A larger θ summarises more aggressively. That makes the run faster and the force estimates less accurate. θ = 0 never summarises and reproduces the exact gradient. The tree is rebuilt every iteration because the points move. Overall cost is O(N log N).
In scikit-learn, Barnes-Hut is the default method, and θ is the angle parameter (default 0.5). The Barnes-Hut method only supports n_components below 4, because tree cost grows quickly with dimension. For 2-D or 3-D plots this does not matter.
import time
from sklearn.datasets import load_digits
from sklearn.manifold import TSNE
X, y = load_digits(return_X_y=True)
for method in ["exact", "barnes_hut"]:
start = time.perf_counter()
TSNE(method=method, init="pca", learning_rate="auto",
random_state=0).fit_transform(X)
print(f"{method:>10}: {time.perf_counter() - start:.1f} s")On the 1,797 digits the gap is modest. It widens quickly as N grows, because the exact method scales quadratically.
Checking the accuracy cost of `angle`
You can measure what a larger θ costs with the trustworthiness score from the quality-metrics chapter.
from sklearn.datasets import load_digits
from sklearn.manifold import TSNE, trustworthiness
X, y = load_digits(return_X_y=True)
for angle in [0.2, 0.5, 0.8]:
Z = TSNE(angle=angle, init="pca", learning_rate="auto",
random_state=0).fit_transform(X)
score = trustworthiness(X, Z, n_neighbors=10)
print(f"angle = {angle}: trustworthiness = {score:.3f}")Expect the scores to differ only slightly across this range. That is why 0.5 is a reasonable default and why increasing it is a cheap way to save time.
FFT-accelerated interpolation
Barnes-Hut still has a log N factor and a tree that must be rebuilt and traversed per point. FFT-accelerated interpolation t-SNE (FIt-SNE) removes both.
The repulsive force uses the Student-t kernel 1 / (1 + ‖yi − yj‖²). That kernel is smooth. FIt-SNE exploits this in three steps:
- Lay a regular grid over the embedding and interpolate each point's contribution onto nearby grid nodes.
- Compute the interactions between grid nodes. Because the grid is regular and the kernel depends only on distance, this is a convolution, and a fast Fourier transform (FFT) computes it in O(M log M) time. M is the number of grid nodes, and it does not depend on N.
- Interpolate the result from the grid back to each point.
Per-iteration cost is then linear in N. The accuracy depends on the grid resolution, not on a θ threshold. The grid is also easy to parallelise. In practice FIt-SNE handles millions of points where Barnes-Hut becomes slow.
scikit-learn does not include FFT t-SNE. The openTSNE package does, and it uses FFT by default:
# pip install openTSNE
from openTSNE import TSNE
from sklearn.datasets import load_digits
X, y = load_digits(return_X_y=True)
embedding = TSNE(
perplexity=30,
negative_gradient_method="fft", # use "bh" for Barnes-Hut
n_jobs=4,
random_state=0,
).fit(X)
print(embedding.shape)The fit method returns an embedding object that behaves like a NumPy array. It can also place new points into an existing map, which scikit-learn's TSNE cannot do.
Choosing a method
| Situation | Suggested method | Reason |
|---|---|---|
| Up to a few thousand points | Barnes-Hut (scikit-learn default) | Fast enough and simple |
| A tiny dataset where you need the true gradient | `method="exact"` | No approximation error, but O(N²) |
| Tens of thousands of points | Barnes-Hut or FFT | Both work, FFT is usually faster |
| Hundreds of thousands to millions | FFT with approximate neighbours | Linear cost per iteration |
| You need a 3-D map or higher | Barnes-Hut, which supports `n_components` below 4 | The FFT grid becomes costly in 3-D and above |
Edge cases and failure modes
- The approximation changes the result. A Barnes-Hut or FFT embedding is not the same as the exact one. Differences are usually minor next to seed-to-seed variation, but do not compare an approximate run with an exact run and read the differences as real.
- Dimensions. scikit-learn raises an error if you combine
method="barnes_hut"with four or more output dimensions. Usemethod="exact"there, and expect it to be slow. - Memory still matters. Sparse affinities save memory, but the input matrix and the neighbour search can still be large. Reduce the input with PCA to about 50 dimensions first. This speeds up neighbour search and removes some noise.
- Larger datasets need more iterations. More points means more attraction to balance, and large maps often need a higher learning rate.
learning_rate="auto"sets this from N, so prefer it. - Approximate search can miss neighbours. If a small fraction of true neighbours is missed, the affinities change slightly. This rarely matters for visual structure.
Exercise
Why can t-SNE sparsify the attractive forces but not the repulsive ones? Which approximation handles the repulsive term in O(N log N), and which in O(N)?
Show answer
The affinities p_ij are near zero for all but a point's closest neighbours, so keeping about 3 × perplexity neighbours per point loses almost nothing and makes the attractive term sparse. The repulsive term is a sum over all pairs of embedded points, and every pair contributes, so it has to be approximated. Barnes-Hut approximates it in O(N log N) by summarising distant groups of points with a quadtree. FFT-accelerated interpolation approximates it in O(N) by interpolating onto a grid and computing the kernel convolution with an FFT.
Exercise
You run scikit-learn's TSNE with n_components=4 and the default settings, and it raises an error. What is the cause and what are your options?
Show answer
The default method is Barnes-Hut, which supports fewer than 4 output dimensions because its spatial tree becomes inefficient as dimension grows. You can use method="exact", which works in any dimension but costs O(N²), or reduce n_components to 2 or 3, which is what visualisation needs anyway.