Written and maintained by CASRAI Editorial Board
Published · Last updated
On this page
In scikit-learn, t-SNE is the class sklearn.manifold.TSNE: you create it with TSNE(n_components=2, perplexity=30.0, ...), call fit_transform(X) on a dense array of samples by features, and get back an array of shape (n_samples, 2) that you can draw as a scatter plot. It is a visualisation tool for high-dimensional data, not a general feature-reduction step, because the class has no transform method and cannot place new points into an existing embedding. This guide, written against the current scikit-learn documentation read on 2026-11-14, covers the parameters, a worked example, how to read the output and the errors people most often hit.
What sklearn t-SNE is used for in research
t-distributed stochastic neighbour embedding (t-SNE) maps each sample in a high-dimensional table, for example thousands of gene-expression values per cell or 64 pixel intensities per image, to a point in two or three dimensions so that samples which are close neighbours in the original space tend to stay close on the page. The method is described in van der Maaten and Hinton (2008, Journal of Machine Learning Research 9) and the scikit-learn class implements it, with the Barnes-Hut approximation from van der Maaten (2014, JMLR 15) as the default method.
Researchers use it to look at structure before or after an analysis: whether labelled groups separate, whether a batch effect is visible, whether an unexpected subgroup exists. It is an exploratory picture. The scikit-learn user guide notes that global structure is not explicitly preserved, and the Distill article “How to Use t-SNE Effectively” (Wattenberg, Viégas and Johnson, 2016) shows that cluster sizes and the distances between well-separated clusters in a t-SNE plot may mean nothing. Treat the plot as a hypothesis generator and confirm any grouping with a method that has defined statistical properties, such as the approaches in cluster analysis in Python. For the wider problem of working with many measured variables, see high-dimensional data.
sklearn t-sne versus sklearn tsne: is there a difference?
No. People type “sklearn t-sne”, “sklearn tsne” and “sklearn t sne” for the same object. In code the class name is always TSNE, imported with from sklearn.manifold import TSNE.
How to install or access it
TSNE ships inside scikit-learn, so there is nothing separate to install. The scikit-learn project installs with pip install -U scikit-learn (or from conda-forge), and the official reference page for the class is scikit-learn.org, sklearn.manifold.TSNE. Check your installed version with import sklearn; print(sklearn.__version__), because several defaults and one argument name changed between releases (see the version table below).
Step-by-step: embed a dataset with TSNE
The steps below use the bundled digits dataset, which has 64 pixel features per sample, so no download is needed. Command names and argument names are the ones in the current API reference.
- Import and load.
from sklearn.manifold import TSNE,from sklearn.datasets import load_digits,from sklearn.preprocessing import StandardScaler, thenX, y = load_digits(return_X_y=True). - Put the features on one scale. The scikit-learn manifold guide says to make sure the same scale is used over all features. For measured variables in different units, run
X = StandardScaler().fit_transform(X). (Pixel intensities in this dataset already share one scale, so this step is shown for the general case.) - Create the estimator.
tsne = TSNE(n_components=2, perplexity=30, init='pca', learning_rate='auto', random_state=0). Settingrandom_statemakes the run repeatable. - Fit and transform in one call.
embedding = tsne.fit_transform(X). The result is an array of shape (n_samples, n_components). - Plot it. With matplotlib:
import matplotlib.pyplot as plt, thenplt.scatter(embedding[:, 0], embedding[:, 1], c=y, s=8)andplt.show(). Colour by a known label only to inspect the map, never to make the algorithm separate groups: TSNE itself is unsupervised and never seesy. - Inspect the fit. Read
tsne.kl_divergence_andtsne.n_iter_(explained below).
The official reference page also gives a minimal example: X = np.array([[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 1]]), then TSNE(n_components=2, learning_rate='auto', init='random', perplexity=3).fit_transform(X), which returns an array of shape (4, 2). Note the small perplexity: it must be less than the number of samples.
A repeatability check across seeds
The scikit-learn manifold guide states that the Kullback-Leibler cost is not convex, so different random seeds can reach different embeddings, and that it is sometimes useful to try different seeds and select the embedding with the lowest KL divergence, which it describes as perfectly legitimate. A loop looks like this:
best = None
for seed in range(5):
t = TSNE(n_components=2, init='pca', learning_rate='auto', random_state=seed)
emb = t.fit_transform(X)
if best is None or best[0] > t.kl_divergence_:
best = (t.kl_divergence_, seed, emb)
Report the seeds you tried and the one you plotted in your methods text. If the story you draw from the map changes from seed to seed, the map does not support that story. For the cost function itself, see Kullback-Leibler divergence.
TSNE parameters and defaults
The data table below lists every constructor argument in the current API reference with its default and the guidance the documentation gives. The ones that most affect a research figure are discussed here.
perplexity
Perplexity is related to the number of nearest neighbours each point considers. The documentation suggests values between 5 and 50, says it must be less than the number of samples, and notes that larger and noisier datasets usually need a larger value. The Distill study shows why you should not rely on one value: at low perplexity random noise can look clustered, so run several and compare.
learning_rate, early_exaggeration and max_iter
The default learning_rate='auto' sets the rate to max(N / early_exaggeration / 4, 50), where N is the number of samples. The documentation warns that other implementations (bhtsne, FIt-SNE, openTSNE) define the learning rate four times smaller, so a value of 200 here corresponds to 800 there. Early exaggeration usually does not need tuning, and if it is too high the KL divergence can increase. max_iter (default 1000) should be at least 250.
init, method, angle and metric
The default init='pca' starts from a PCA projection, which the user guide says mitigates the loss of global structure; it cannot be used with metric='precomputed', where X is a distance matrix. The default method='barnes_hut' is O(N log N) and works only when n_components is 3 or less; method='exact' is O(N²) and is the choice when nearest-neighbour errors must be under 3%. The angle parameter (0.2 to 0.8) is documented as not very sensitive.
Which scikit-learn version changed which default?
| Release | Change in TSNE | What it means for your code |
|---|---|---|
| 0.22 | n_jobs added |
Parallel neighbour search is available. |
| 1.1 | metric_params added |
Extra keyword arguments for the distance metric. |
| 1.2 | Default learning_rate became ‘auto’ and default init became ‘pca’; learning_rate_ attribute added |
The same call can give a different map than in older tutorials. |
| 1.5 | n_iter renamed max_iter |
Code or tutorials that pass n_iter=... raise a TypeError on current versions. |
Output and how to read it
embedding_ (also the return value of fit_transform) holds the coordinates, one row per input sample in the original order. Fitted attributes in the reference include kl_divergence_ (the final Kullback-Leibler divergence), n_iter_ (iterations actually run), learning_rate_ (the rate used, added in 1.2), n_features_in_ and feature_names_in_.
A lower kl_divergence_ is better only when you compare runs of the same data with the same perplexity; it is not a score that can be compared across datasets or perplexities. The axes have no units and no meaning of their own. From the Distill article: you cannot see relative cluster sizes, distances between well-separated clusters may mean nothing, and a run stopped too early can show pinched shapes. Do not quote a distance or a cluster diameter from a t-SNE plot.
Two further limits matter for analysis plans. First, because there is no transform method, you cannot embed a held-out set or later samples into an existing map; call fit_transform on the whole dataset you want to show. Second, the Barnes-Hut method accepts only dense input, so sparse matrices need method='exact' or a low-rank projection first. The user guide says Barnes-Hut suits hundreds of thousands of points, exact suits thousands, and a million-sample dataset can take several hours where PCA takes seconds or minutes.
Troubleshooting common errors
| Symptom | Cause according to the documentation | Fix |
|---|---|---|
TypeError about an unexpected keyword n_iter |
n_iter was renamed max_iter in 1.5 |
Use max_iter, or pin an older scikit-learn. |
| ValueError that perplexity must be less than n_samples | Perplexity must be smaller than the number of samples | Lower perplexity (the official 4-sample example uses 3). |
AttributeError: no attribute transform |
TSNE has fit and fit_transform but no transform |
Embed everything in one fit_transform call, or use a method that supports new points (table below). |
Error with n_components above 3 |
Barnes-Hut works only for 3 or fewer target dimensions | Set method='exact', or reduce to 2 or 3 components. |
| Error on a sparse matrix | Barnes-Hut needs dense input | Use method='exact' or reduce with a low-rank projection first. |
Error combining init='pca' with precomputed distances |
PCA initialisation cannot be used with metric='precomputed' |
Use init='random'. |
| Map looks different from a tutorial | Defaults changed in 1.2; the cost is non-convex | Set init, learning_rate and random_state explicitly. |
Free alternatives to sklearn TSNE
When you need something TSNE does not offer, the options below are free and open source. The table states only what each project’s own documentation says; for a conceptual comparison of the two main methods, see UMAP vs t-SNE.
| Tool | What its documentation says | Install |
|---|---|---|
PCA (sklearn.decomposition.PCA) |
scikit-learn’s manifold guide contrasts PCA, which takes seconds or minutes on million-sample data, with t-SNE, which can take hours; it is also the default initialisation for TSNE. | Included with scikit-learn. |
| UMAP | The UMAP docs say it can be used for visualisation similarly to t-SNE and for general non-linear dimension reduction; its API lists a transform() method. |
pip install umap-learn |
| openTSNE | Described as a modular Python implementation of t-SNE, including the ability to add new data points to existing embeddings. | Conda or PyPI, per its installation page. |
Frequently asked questions
How do I import t-SNE in scikit-learn?
Use from sklearn.manifold import TSNE. The class is documented as sklearn.manifold.TSNE and is part of scikit-learn itself.
Can I use TSNE to transform new data?
No. The class provides fit and fit_transform but no transform, so new points cannot be added to an existing embedding. Fit on the full dataset, or choose a method whose documentation lists a way to add points.
What perplexity should I use?
The documentation suggests 5 to 50, requires a value below the number of samples, and says larger or noisier data need larger values. Try several and see whether your conclusion survives.
Why did my code fail with an n_iter error?
Release 1.5 renamed n_iter to max_iter. Change the argument name.
Does the distance between clusters in a t-SNE plot mean anything?
Not reliably. Distill’s analysis of t-SNE shows that distances between well-separated clusters and cluster sizes may mean nothing, so do not report them as measurements.
Sources
- scikit-learn documentation, sklearn.manifold.TSNE, read 2026-11-14.
- scikit-learn user guide, Manifold learning (t-SNE section), read 2026-11-14.
- Wattenberg, Viégas and Johnson (2016), How to Use t-SNE Effectively, Distill, read 2026-11-14.
- UMAP documentation, read 2026-11-14.
- openTSNE documentation, read 2026-11-14.
- van der Maaten and Hinton (2008), Visualizing Data using t-SNE, Journal of Machine Learning Research 9; van der Maaten (2014), Accelerating t-SNE using Tree-Based Algorithms, Journal of Machine Learning Research 15.
Data: scikit-learn TSNE constructor arguments, defaults and documented guidance
Parameters of sklearn.manifold.TSNE with the default value and the guidance the official scikit-learn API reference and manifold user guide give for each, compiled from the documentation read on 2026-11-14.
| Parameter | Default | Documented guidance |
|---|---|---|
| n_components | 2 | Dimension of the embedded space; Barnes-Hut requires 3 or fewer |
| perplexity | 30.0 | Consider 5-50; must be less than the number of samples; larger/noisier data need larger values |
| early_exaggeration | 12.0 | Usually need not be tuned; if too high the KL divergence can increase |
| learning_rate | auto | auto = max(N / early_exaggeration / 4, 50); other implementations define it 4x smaller |
| max_iter | 1000 | Should be at least 250; renamed from n_iter in 1.5 |
| n_iter_without_progress | 300 | Iterations without progress before optimisation stops |
| min_grad_norm | 1e-07 | Optimisation stops when the gradient norm falls below this |
| metric | euclidean | 'precomputed' means X is a distance matrix |
| init | pca | random, pca or an array; pca cannot be used with precomputed distances; default since 1.2 |
| method | barnes_hut | barnes_hut is O(N log N); exact is O(N^2) and used when nearest-neighbour errors must be under 3% |
| angle | 0.5 | Barnes-Hut trade-off; 0.2-0.8 and not very sensitive |
| random_state | None | Set an integer for a repeatable embedding |
| n_jobs | None | Parallel jobs for neighbour search; ignored for precomputed or euclidean with exact |
Sources
- scikit-learn: sklearn.manifold.TSNE (accessed 2026-11-14)
- scikit-learn user guide: Manifold learning (accessed 2026-11-14)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







