Sub topic 18
A reproducible workflow for real data
This chapter combines the earlier pieces into one repeatable procedure for t-SNE and UMAP. It assumes you know basic Python and NumPy, scikit-learn's fit/transform interface, and what perplexity, n_neighbors and min_dist do. The goal is a pipeline that someone else can rerun and get the same figure from, and one that tells you how far to trust that figure.
The workflow at a glance
A plot from a single run with default settings is a weak result. A defensible one comes from a fixed sequence of steps, with every choice recorded.
Step 1: Preprocess deliberately
Both methods start from distances, so whatever distorts distances distorts the map.
- Handle missing values and outliers first. Neither method accepts NaN. A few extreme points can stretch the distance scale and change the neighbour sets of other points.
- Scale features that have different units. Without scaling, a feature measured in thousands dominates the Euclidean distance. For data where every feature shares one unit, such as pixels, scaling is optional and can amplify noise in near-constant columns.
- Reduce with PCA to roughly 30 to 50 components before embedding. This removes low-variance noise directions and speeds up nearest-neighbour search. It is the usual first step for very wide data such as gene expression. For data with fewer than about 50 features, skip it.
- Choose the metric to match the data. Euclidean distance suits scaled dense features. Cosine distance often suits text vectors and learned embeddings.
Keep the preprocessing in a scikit-learn Pipeline so it can be reapplied to new data.
Step 2: Fix the seed and record the settings
t-SNE with init="pca" is mostly deterministic, but the optimiser still has random elements. UMAP's layout is stochastic. Always set random_state, and store it together with the parameters and library versions.
The script below applies the preprocessing and runs t-SNE with five seeds. It scores each run with trustworthiness, which is the fraction of each point's embedded neighbours that were also neighbours in the original space (1.0 is perfect).
import numpy as np
import sklearn
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE, trustworthiness
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_digits(return_X_y=True)
prep = make_pipeline(StandardScaler(), PCA(n_components=30, random_state=0))
X_pre = prep.fit_transform(X)
print("scikit-learn", sklearn.__version__)
scores = []
for seed in range(5):
Z = TSNE(n_components=2, perplexity=30, init="pca",
learning_rate="auto", random_state=seed).fit_transform(X_pre)
t = trustworthiness(X_pre, Z, n_neighbors=10)
scores.append(t)
print(f"seed={seed} trustworthiness={t:.3f}")
print(f"mean={np.mean(scores):.3f} std={np.std(scores):.4f}")Scores that agree to the second decimal tell you the optimiser is not producing wildly different local structure. Large spread means the result depends on the seed, so report it as such.
Step 3: Sweep one parameter at a time
Change one parameter, hold the seed fixed, and compare scores and plots side by side. Sensible ranges:
| Method | Parameter | Values to try | Main effect |
|---|---|---|---|
| t-SNE | `perplexity` | 5, 30, 100 | Effective neighbourhood size. Low values fragment clusters, high values merge them. |
| UMAP | `n_neighbors` | 5, 15, 50 | Local versus global emphasis. |
| UMAP | `min_dist` | 0.0, 0.1, 0.5 | How tightly points pack inside a cluster. |
Keep perplexity well below the number of samples. For UMAP, the plot changes visibly with min_dist, but the neighbour structure barely changes, so trustworthiness will move little. That is expected, and it means the score alone cannot pick min_dist. Choose it for readability.
The sweep below runs UMAP with several n_neighbors values and prints one score for each.
import umap
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.manifold import trustworthiness
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_digits(return_X_y=True)
X_pre = make_pipeline(StandardScaler(),
PCA(n_components=30, random_state=0)).fit_transform(X)
for nn in [5, 15, 50]:
Z = umap.UMAP(n_neighbors=nn, min_dist=0.1,
random_state=0).fit_transform(X_pre)
t = trustworthiness(X_pre, Z, n_neighbors=10)
print(f"n_neighbors={nn:>2} trustworthiness={t:.3f}")Setting random_state makes UMAP reproducible but runs it single-threaded, so it is slower on large data. For a quick exploratory pass, leave the seed unset and set it only for the final run.
Step 4: Embed new data without leaking
Scikit-learn's TSNE has no transform, so it cannot place new points into an existing map. If you must embed unseen data, refit on the combined data, or use UMAP, which provides transform. Fit the preprocessing on the training split only, then apply it to the test split.
import umap
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_digits(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, random_state=0, stratify=y)
prep = make_pipeline(StandardScaler(), PCA(n_components=30, random_state=0))
P_train = prep.fit_transform(X_train)
P_test = prep.transform(X_test)
reducer = umap.UMAP(n_neighbors=15, min_dist=0.1,
random_state=0).fit(P_train)
E_train = reducer.embedding_
E_test = reducer.transform(P_test)
print(E_train.shape, E_test.shape)Points placed by transform are approximate. They land near their training neighbours, but they do not reshape the map. Treat them as a projection onto a fixed layout.
Step 5: Check stability before you trust a feature
A structure deserves attention only if it survives changes you did not mean to make. Before interpreting any cluster, check these:
- Seeds. Does the cluster appear with three or more different
random_statevalues? - Parameters. Does it persist across a reasonable range of perplexity or
n_neighbors? - Method. Does it show up in both t-SNE and UMAP, and in PCA at least as a rough grouping?
- Labels or metadata. Colour the same plot by a variable you did not use (batch, date, source). If clusters line up with a technical variable, they may be artefacts.
Remember what is not stable by design. Cluster sizes, distances between clusters, and global orientation can all change between runs and settings. Report conclusions about which points are neighbours, not about how far apart groups are.
What to record
Write these next to every figure:
- Library versions (
scikit-learn,umap-learn, NumPy). - Preprocessing steps and the number of PCA components.
- Method, metric, and all parameters, including defaults you relied on.
- The random seed or seeds, and the trustworthiness score with
n_neighborsused. - The number of samples and any filtering applied.
Exercise
You embed 5,000 samples with UMAP, random_state=None, and send a colleague the picture. They rerun your code and get a differently arranged picture with the same clusters. List two changes that would make the result reproducible, and say what you would check to decide whether the clusters are real.
Show answer
Set random_state (for example 0) in UMAP and record the umap-learn and scikit-learn versions, the PCA settings and all parameters. Fit preprocessing inside a pipeline so it is applied identically. To decide whether the clusters are real, rerun with several seeds and a range of n_neighbors, confirm the clusters persist, compare trustworthiness across runs, and check that they do not simply line up with a technical variable such as batch.