t-Distributed Stochastic Neighbor Embedding
Visualize Fisher Iris Data
The Fisher iris data set has four-dimensional measurements of irises, and corresponding classification into species. Visualize this data by reducing the dimension using
load fisheriris rng default % for reproducibility Y = tsne(meas); gscatter(Y(:,1),Y(:,2),species)
Compare Distance Metrics
Use various distance metrics to try to obtain a better separation between species in the Fisher iris data.
load fisheriris rng('default') % for reproducibility Y = tsne(meas,'Algorithm','exact','Distance','mahalanobis'); subplot(2,2,1) gscatter(Y(:,1),Y(:,2),species) title('Mahalanobis') rng('default') % for fair comparison Y = tsne(meas,'Algorithm','exact','Distance','cosine'); subplot(2,2,2) gscatter(Y(:,1),Y(:,2),species) title('Cosine') rng('default') % for fair comparison Y = tsne(meas,'Algorithm','exact','Distance','chebychev'); subplot(2,2,3) gscatter(Y(:,1),Y(:,2),species) title('Chebychev') rng('default') % for fair comparison Y = tsne(meas,'Algorithm','exact','Distance','euclidean'); subplot(2,2,4) gscatter(Y(:,1),Y(:,2),species) title('Euclidean')
In this case, the cosine, Chebychev, and Euclidean distance metrics give reasonably good separation of clusters. But the Mahalanobis distance metric does not give a good separation.
Plot Results with
NaN Input Data
tsne removes input data rows that contain any
NaN entries. Therefore, you must remove any such rows from your classification data before plotting.
For example, change a few random entries in the Fisher iris data to
load fisheriris rng default % for reproducibility meas(rand(size(meas)) < 0.05) = NaN;
Embed the four-dimensional data into two dimensions using
Y = tsne(meas,'Algorithm','exact');
Warning: Rows with NaN missing values in X or 'InitialY' values are removed.
Determine how many rows were eliminated from the embedding.
ans = 22
Prepare to plot the result by locating the rows of
meas that have no
goodrows = not(any(isnan(meas),2));
Plot the results using only the rows of
species that correspond to rows of
meas with no
Compare t-SNE Loss
Find both 2-D and 3-D embeddings of the Fisher iris data, and compare the loss for each embedding. It is likely that the loss is lower for a 3-D embedding, because this embedding has more freedom to match the original data.
load fisheriris rng default % for reproducibility [Y,loss] = tsne(meas,'Algorithm','exact'); rng default % for fair comparison [Y2,loss2] = tsne(meas,'Algorithm','exact','NumDimensions',3); fprintf('2-D embedding has loss %g, and 3-D embedding has loss %g.\n',loss,loss2)
2-D embedding has loss 0.12929, and 3-D embedding has loss 0.0992412.
As expected, the 3-D embedding has lower loss.
View the embeddings. Use RGB colors
[1 0 0],
[0 1 0], and
[0 0 1].
For the 3-D plot, convert the species to numeric values using the
categorical command, then convert the numeric values to RGB colors using the
sparse function as follows. If
v is a vector of positive integers 1, 2, or 3, corresponding to the species data, then the command
is a sparse matrix whose rows are the RGB colors of the species.
gscatter(Y(:,1),Y(:,2),species,eye(3)) title('2-D Embedding')
figure v = double(categorical(species)); c = full(sparse(1:numel(v),v,ones(size(v)),numel(v),3)); scatter3(Y2(:,1),Y2(:,2),Y2(:,3),15,c,'filled') title('3-D Embedding') view(-50,8)
X — Data points
Data points, specified as an
where each row is one
tsne removes rows of
NaN values before creating an embedding.
See Plot Results with NaN Input Data.
Specify optional pairs of arguments as
the argument name and
Value is the corresponding value.
Name-value arguments must appear after other arguments, but the order of the
pairs does not matter.
Before R2021a, use commas to separate each name and value, and enclose
Name in quotes.
'barneshut' (default) |
tsne algorithm, specified as
'exact' algorithm optimizes the Kullback-Leibler
divergence of distributions between the original space and the embedded
'barneshut' algorithm performs an approximate
optimization that is faster and uses less memory when the number of
data rows is large.
knnsearch to find the nearest neighbors.
CacheSize — Size of Gram matrix in megabytes
1e3 (default) | positive scalar |
Size of the Gram matrix in megabytes, specified as a positive scalar or
tsne function can use
CacheSize only when the
argument begins with
If you set
tsne tries to allocate enough memory for an entire
intermediate matrix whose size is
M is the number of rows of the input data
The cache size does not have to be large enough for an entire intermediate matrix, but
must be at least large enough to hold an
M-by-1 vector. Otherwise,
tsne uses the standard algorithm for computing Euclidean
If the value of the
Distance argument begins with
fast, and the value of
CacheSize is too large
tsne might try to allocate
a Gram matrix that exceeds the available memory. In this case, MATLAB® issues an error.
Distance — Distance metric
'euclidean' (default) |
'jaccard' | function handle
Distance metric, specified as one of the following:
'euclidean'— Euclidean distance.
'seuclidean'— Standardized Euclidean distance. Each coordinate difference between the rows in
Xand the query matrix is scaled by dividing by the corresponding element of the standard deviation computed from
S = std(X,'omitnan').
'fasteuclidean'— Euclidean distance computed by using an alternative algorithm that saves time when the number of predictors is at least 10. In some cases, this faster algorithm can reduce accuracy. Algorithms starting with
'fast'do not support sparse data. For details, see Algorithms.
'fastseuclidean'— Standardized Euclidean distance computed by using an alternative algorithm that saves time when the number of predictors is at least 10. In some cases, this faster algorithm can reduce accuracy. Algorithms starting with
'fast'do not support sparse data. For details, see Algorithms.
'cityblock'— City block distance.
'chebychev'— Chebychev distance, which is the maximum coordinate difference.
'minkowski'— Minkowski distance with exponent 2. This distance is the same as the Euclidean distance.
'mahalanobis'— Mahalanobis distance, computed using the positive definite covariance matrix
'cosine'— One minus the cosine of the included angle between observations (treated as vectors).
'correlation'— One minus the sample linear correlation between observations (treated as sequences of values).
'spearman'— One minus the sample Spearman's rank correlation between observations (treated as sequences of values).
'hamming'— Hamming distance, which is the percentage of coordinates that differ.
'jaccard'— One minus the Jaccard coefficient, which is the percentage of nonzero coordinates that differ.
Custom distance function — A distance function specified using
@distfun). For details, see More About.
In all cases,
tsne uses squared pairwise
distances to calculate the Gaussian kernel in the joint distribution
Exaggeration — Size of natural clusters in data
4 (default) | scalar value
1 or greater
Size of natural clusters in data, specified as a scalar value
A large exaggeration makes
tsne learn larger
joint probabilities of
Y and creates relatively
more space between clusters in
exaggeration in the first 99 optimization iterations.
If the value of Kullback-Leibler divergence increases in the early stage of the optimization, try reducing the exaggeration. See tsne Settings.
NumDimensions — Dimension of the output
2 (default) | positive integer
Dimension of the output
Y, specified as
a positive integer. Generally, set
NumPCAComponents — PCA dimension reduction
0 (default) | nonnegative integer
PCA dimension reduction, specified as a nonnegative integer.
tsne embeds the high-dimensional data,
it first reduces the dimensionality of the data to
pca function. When
not use PCA.
Perplexity — Effective number of local neighbors of each point
30 (default) | positive scalar
Effective number of local neighbors of each point, specified as a positive scalar. See t-SNE Algorithm.
Larger perplexity causes
tsne to use more
points as nearest neighbors. Use a larger value of
a large dataset. Typical
Perplexity values are
50. In the Barnes-Hut
the number of nearest neighbors. See tsne Settings.
Standardize — Flag to normalize input data
false (default) |
Flag to normalize input data, specified as
true. When the value is
centers and scales each column of
X by first subtracting its
mean, and then dividing by its standard
When features in
on different scales, set
true. The learning process is
based on nearest neighbors, so features with large
scales can override the contribution of features
with small scales.
InitialY — Initial embedded points
1e-4*randn(N,NumDimensions) (default) |
LearnRate — Learning rate for optimization process
500 (default) | positive scalar
Learning rate for optimization process, specified as a positive
scalar. Typically, set values from
LearnRate is too small,
converge to a poor local minimum. When
too large, the optimization can initially have the Kullback-Leibler
divergence increase rather than decrease. See tsne Settings.
NumPrint — Iterative display frequency
20 (default) | positive integer
Iterative display frequency, specified as a positive integer.
Verbose name-value pair is not
iterative display after every
Options name-value pair contains a nonempty
then output functions run after every
Options — Optimization options
structure containing the fields
'MaxIter'— Positive integer specifying the maximum number of optimization iterations. Default:
'OutputFcn'— Function handle or cell array of function handles specifying one or more functions to call after every
NumPrintoptimization iterations. For syntax details, see t-SNE Output Function. Default:
'TolFun'— Stopping criterion for the optimization. The optimization exits when the norm of the gradient of the Kullback-Leibler divergence is less than
options = statset('MaxIter',500)
Theta — Barnes-Hut tradeoff parameter
0.5 (default) | scalar from 0 through 1
Barnes-Hut tradeoff parameter, specified as a scalar from 0
through 1. Higher values give a faster but less accurate optimization.
Applies only when
Verbose — Iterative display
0 (default) |
Iterative display, specified as
Verbose is not
a summary table of the Kullback-Leibler divergence and the norm of
its gradient every
prints the variances of Gaussian kernels.
these kernels in its computation of the joint probability of
If you see a large difference in the scales of the minimum and maximum
variances, you can sometimes get more suitable results by rescaling
loss — Kullback-Leibler divergence
Kullback-Leibler divergence between modeled input and output distributions, returned as a nonnegative scalar. For details, see t-SNE Algorithm.
Custom Distance Function
The syntax of a custom distance function is as follows.
function D2 = distfun(ZI,ZJ)
your function, and your function computes the distance.
ZIis a 1-by-n vector containing a single row from
ZJis an m-by-n matrix containing multiple rows of
Your function returns
D2, which is an m-by-1
vector of distances. The jth element of
the distance between the observations
If your data are not sparse, then usually the built-in distance functions are faster than a function handle.
tsne constructs a set of embedded points
in a low-dimensional space whose relative similarities mimic those
of the original high-dimensional points. The embedded points show
the clustering in the original data.
Roughly, the algorithm models the original points as coming from a Gaussian distribution, and the embedded points as coming from a Student’s t distribution. The algorithm tries to minimize the Kullback-Leibler divergence between these two distributions by moving the embedded points.
For details, see t-SNE.
Fast Euclidean Distance Algorithm
The values of the
Distance argument that begin
calculate Euclidean distances using an algorithm that uses extra memory to save
computational time. This algorithm is named "Euclidean Distance Matrix Trick" in Albanie
 and elsewhere. Internal
testing shows that this algorithm saves time when the number of predictors is at least 10.
Algorithms starting with
'fast' do not support sparse data.
To find the matrix D of distances between all the points xi and xj, where each xi has n variables, the algorithm computes distance using the final line in the following equations:
The matrix in the last line of the equations is called the Gram matrix. Computing the set of squared distances is faster, but slightly less numerically stable, when you compute and use the Gram matrix instead of computing the squared distances by squaring and summing. For a discussion, see Albanie .
To store the Gram matrix, the software uses a cache with the default size of
1e3 megabytes. You can set the cache size using the
CacheSize name-value argument. If the value of
CacheSize is too large or
tsne might try to allocate a Gram matrix that exceeds the
available memory. In this case, MATLAB issues an error.
 Albanie, Samuel. Euclidean Distance Matrix Trick. June, 2019. Available at https://www.robots.ox.ac.uk/%7Ealbanie/notes/Euclidean_distance_trick.pdf.