Sub topic 14
UMAP parameters: n_neighbors, min_dist and metric
This chapter assumes you can run scikit-learn estimators, know what a feature vector and Euclidean distance are, and have read the previous two chapters on how UMAP builds a weighted nearest-neighbour graph and then lays it out. Here you will learn which three parameters shape the result most, what each one changes in the graph or the layout, and which mistakes are common.
Where each parameter acts
UMAP has two stages. The three parameters act on different stages, and keeping that straight makes tuning much easier.
| Parameter | Stage | What it controls | Default |
|---|---|---|---|
| `n_neighbors` | Graph construction | How many neighbours define each point's local neighbourhood | 15 |
| `metric` | Graph construction | How distance is measured when finding neighbours | `"euclidean"` |
| `min_dist` | Layout | How tightly points may pack together in the output | 0.1 |
Two of the three change the graph itself. min_dist leaves the graph alone and changes only how the graph is drawn. This means you can change min_dist and refit without changing which points are neighbours.
n_neighbors: the scale of structure
n_neighbors is the number of nearest neighbours UMAP uses to estimate the local structure around each point. It is the closest counterpart to t-SNE's perplexity, because it sets the size of the neighbourhood the method pays attention to.
- Small values (2 to 10) make UMAP focus on very local detail. You tend to see many small clusters and fragmented structure. Real large-scale relationships can be lost, and noise can turn into apparent clusters.
- Large values (50 to 200) make UMAP take in broader structure. Clusters merge into a more connected picture, and fine detail is smoothed out.
- The default of 15 is a middle setting that works for many datasets.
Think of it as a question: "At what scale do I want to see structure?" There is no single correct answer. A value that reveals sub-types inside a class may hide how the classes relate to one another.
min_dist: how tightly points pack
min_dist is the minimum distance allowed between points in the low-dimensional layout. It is a value from 0 upwards, and the useful range is usually 0.0 to 1.0.
- Small values (0.0 to 0.1) let points clump into dense, tight blobs. This is good for emphasising clusters. It can also make a dense region look like a single point mass, which hides internal structure.
- Large values (0.5 to 0.99) spread points out so they cannot sit on top of each other. The plot then shows broad topology more than tight clusters, and it is easier to see the layout inside a cluster.
Because min_dist only affects the layout, it does not change which points are neighbours. A tight cluster at min_dist=0.0 and a loose cluster at min_dist=0.8 contain the same neighbour relationships. Only the drawing differs.
A related parameter, spread, sets the overall scale of the embedded points. min_dist must not exceed spread. Leave spread at its default of 1.0 unless you have a reason to change it.
metric: what "close" means
metric is the distance function used to find neighbours. The default is Euclidean distance, which suits many numeric features. Other choices fit other kinds of data.
| Metric | Typical use |
|---|---|
| `"euclidean"` | General numeric features of similar scale |
| `"cosine"` | Text vectors, word or image embeddings, where direction matters more than length |
| `"manhattan"` | Features where per-coordinate differences should add up linearly |
| `"correlation"` | Profiles where the shape of a pattern matters more than its level |
| `"hamming"`, `"jaccard"` | Binary or categorical features |
The metric is the most consequential choice for data that is not plain numeric measurements. If two points are "close" under the wrong metric, no setting of n_neighbors or min_dist will repair the result. Pick the metric that matches how similarity is judged in your domain. For neural-network embeddings, "cosine" is a common choice.
Metric choice interacts with preprocessing. Euclidean distance is sensitive to feature scale, so standardise features first if they use different units.
Running the parameters
The following code embeds the digits data with the defaults written out explicitly.
import umap # installed as the umap-learn package
from sklearn.datasets import load_digits
import matplotlib.pyplot as plt
X, y = load_digits(return_X_y=True)
reducer = umap.UMAP(n_neighbors=15, min_dist=0.1, metric="euclidean",
random_state=0)
Z = reducer.fit_transform(X)
plt.scatter(Z[:, 0], Z[:, 1], c=y, cmap="tab10", s=8)
plt.colorbar(label="digit")
plt.title("UMAP of the digits data")
plt.show()Setting random_state makes the run reproducible. It also turns off some parallelism, so fitting is slower on large data. If you only need a quick look, leave it unset. If you need to compare runs, set it.
A parameter sweep
To see the effect of each parameter, vary one at a time and hold the others fixed. This grid varies n_neighbors across the rows and min_dist across the columns.
import umap
from sklearn.datasets import load_digits
import matplotlib.pyplot as plt
X, y = load_digits(return_X_y=True)
n_values = [5, 15, 50]
d_values = [0.0, 0.1, 0.8]
fig, axes = plt.subplots(len(n_values), len(d_values), figsize=(12, 12))
for i, n in enumerate(n_values):
for j, d in enumerate(d_values):
Z = umap.UMAP(n_neighbors=n, min_dist=d, random_state=0).fit_transform(X)
ax = axes[i, j]
ax.scatter(Z[:, 0], Z[:, 1], c=y, cmap="tab10", s=4)
ax.set_title(f"n_neighbors={n}, min_dist={d}")
ax.set_xticks([])
ax.set_yticks([])
plt.tight_layout()
plt.show()Read the grid down a column to see the effect of n_neighbors and across a row to see the effect of min_dist. Expect the top row to show the most fragmented clusters and the left column to show the tightest blobs.
Common errors
- Treating one setting as the answer. The embedding at one parameter setting is one view of the data. Structure that appears at every reasonable setting is more trustworthy than structure that appears at only one.
- Reading
min_distas a data property. Cluster tightness is mostly a drawing choice controlled bymin_dist. Do not report "the clusters are tight" without stating the value. - Tuning
n_neighborsto get the picture you expected. Changing parameters until the classes separate cleanly is a way of fooling yourself. Choose a range ahead of time and report how results vary across it. - Using Euclidean distance on the wrong data. Text counts, binary flags and normalised embeddings usually need a different metric.
- Forgetting that
n_neighborscannot exceed the data. Setting it near or above the number of samples gives poor or failing fits. Keep it well below the sample count. - Skipping scaling. Unscaled features with large ranges dominate Euclidean distances and silently decide the neighbour graph.
Reusing a fitted model
A fitted UMAP object can place new points into the same map. The scikit-learn TSNE class does not offer this.
import umap
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
X, y = load_digits(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
reducer = umap.UMAP(random_state=0).fit(X_train)
train_embedding = reducer.embedding_
test_embedding = reducer.transform(X_test)
print(train_embedding.shape, test_embedding.shape)The parameters you chose are fixed at fit time and apply to the new points as well. New points are placed using the neighbours they have among the training data, so points unlike anything in the training set land in less meaningful positions.
Exercise
You embed a text-embedding dataset with the default settings and see many small, scattered clusters. Name one parameter change that should merge them into a broader picture, one that would only make the clusters look less tightly packed without changing which points are neighbours, and one that you should check first if the data are normalised embedding vectors.
Show answer
Increase nneighbors (for example from 15 to 50 or more) to make UMAP weigh broader structure, which merges small clusters. Increase mindist (for example to 0.5) to spread points out. This changes only the layout, not the neighbour graph. For embedding vectors, check the metric first and try "cosine" instead of the Euclidean default.
Exercise
A colleague runs UMAP with min_dist=0.0 and reports that cluster A is "much denser" than cluster B. What is wrong with that claim?
Show answer
min_dist only controls how closely points may pack in the drawing. At 0.0, points can overlap heavily in every cluster, so visual density reflects the layout setting and not the density of the original data. Density in a UMAP plot is not a reliable measure of density in the high-dimensional space.