<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/multi-dimensional-reduction-and-visualisation-with-t-sne/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://datascienceplus.com/multi-dimensional-reduction-and-visualisation-with-t-sne/"> R Programming – DataScience+</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p><b>t-SNE</b> is a very powerful technique that can be used for visualising (looking for patterns) in multi-dimensional data. Great things have been said about this technique. In this blog post I did a few experiments with t-SNE in R to learn about this technique and its uses.</p>
<p>Its power to visualise complex multi-dimensional data is apparent, as well as its ability to cluster data in an unsupervised way.</p>
<p>What’s more, it is also quite clear that t-SNE can aid machine learning algorithms when it comes to prediction and classification. But the inclusion of t-SNE in machine learning algorithms and ensembles has to be ‘crafted’ carefully, since t-SNE was not originally intended for this purpose.</p>
<p>All in all, t-SNE is a powerful technique that merits due attention.</p>
<h2>t-SNE</h2>
<p>Let’s start with a brief description. <b>t-SNE</b> stands for <b>t-Distributed Stochastic Neighbor Embedding</b> and its main aim is that of <b>dimensionality reduction</b>, i.e., given some complex dataset with many many dimensions, t-SNE projects this data into a 2D (or 3D) representation while preserving the ‘structure’ (patterns) in the original dataset. Visualising high-dimensional data in this way allows us to look for patterns in the dataset.</p>
<p>t-SNE has become so popular because:</p>
<ul>
<li>it was demonstrated to be useful in many situations,</li>
<li>it’s incredibly flexible, and</li>
<li>can often find structure where other dimensionality-reduction algorithms cannot.</li>
</ul>
<p>A good introduction on t-SNE can be found <a rel="nofollow" href="https://www.oreilly.com/learning/an-illustrated-introduction-to-the-t-sne-algorithm" target="_blank">here</a>. The original paper on t-SNE and some visualisations can be found at <a rel="nofollow" href="http://lvdmaaten.github.io/tsne/" target="_blank">this site</a>. In particular, I like <a rel="nofollow" href="http://cs.stanford.edu/people/karpathy/cnnembed/" target="_blank">this site</a> which shows how t-SNE is used for unsupervised image clustering.</p>
<p>While t-SNE itself is computationally heavy, a faster version exists that uses what is known as the Barnes-Hut approximation. This faster version allows t-SNE to be applied on large real-world datasets.</p>
<h2>t-SNE for Exploratory Data Analysis</h2>
<p>Because t-SNE is able to provide a 2D or 3D visual representation of high-dimensional data that preserves the original structure, we can use it during initial data exploration. We can use it to check for the presence of clusters in the data and as a visual check to see if there is some ‘order’ or some ‘pattern’ in the dataset. It can aid our intuition about what we think we know about the domain we are working in.</p>
<p>Apart from the initial exploratory stage, visualising information via t-SNE (or any other algorithm) is vital throughout the entire analysis process – from those first investigations of the raw data, during data preparation, as well as when interpreting the outputs of machine learning algorithms and presenting insights to others. We will see further on that we can use t-SNE even during the predcition/classification stage itself.</p>
<h2>Experiments on the Optdigits dataset</h2>
<p>In this post, I will apply t-SNE to a well-known dataset, called optdigits, for visualisation purposes.</p>
<p>The optdigits dataset has 64 dimensions. Can t-SNE reduce these 64 dimensions to just 2 dimension while preserving structure in the process? And will this structure (if present) allow handwritten digits to be correctly clustered together? Let’s find out.</p>
<h2>tsne package</h2>
<p>We will use the <a rel="nofollow" href="https://cran.r-project.org/web/packages/tsne/index.html" target="_blank">tsne package</a> that provides an exact implementation of t-SNE (not the Barnes-Hut approximation). And we will use this method to reduce dimensionality of the optdigits data to 2 dimensions. Thus, the final output of t-SNE will essentially be an array of 2D coordinates, one per row (image). And we can then plot these coordinates to get the final 2D map (visualisation). The algorithm runs in iterations (called epochs), until the system converges. Every<br>
\(K\) number of iterations and upon convergence, t-SNE can call a user-supplied callback function, and passes the list of 2D coordinates to it. In our callback function, we plot the 2D points (one per image) and the corresponding class labels, and colour-code everything by the class labels.</p>
<pre>
traindata &lt;- read.table(&quot;optdigits.tra&quot;, sep=&quot;,&quot;)
trn &lt;- data.matrix(traindata)

require(tsne)

cols &lt;- rainbow(10)

# this is the epoch callback function used by tsne. 
# x is an NxK table where N is the number of data rows passed to tsne, and K is the dimension of the map. 
# Here, K is 2, since we use tsne to map the rows to a 2D representation (map).
ecb = function(x, y){ plot(x, t='n'); text(x, labels=trn[,65], col=cols[trn[,65] +1]); }

tsne_res = tsne(trn[,1:64], epoch_callback = ecb, perplexity=50, epoch=50)

</pre>
<p>The images below show how the clustering improves as more epochs pass.<br>
<a rel="nofollow" href="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/09/tsne1.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/09/tsne1-490x338.png?w=450&ssl=1" alt="" class="wp-image-8606" data-recalc-dims="1"></a></p>
<p><a rel="nofollow" href="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2017/09/tsne3.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/09/tsne3-490x341.png?w=450&ssl=1" alt="" class="wp-image-8608" data-recalc-dims="1"></a></p>
<p><a rel="nofollow" href="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/09/tsne2.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2017/09/tsne2-490x341.png?w=450&ssl=1" alt="" class="wp-image-8607" data-recalc-dims="1"></a></p>
<p><a rel="nofollow" href="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/09/tsne4.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/09/tsne4-490x340.png?w=450&ssl=1" alt="" class="wp-image-8609" data-recalc-dims="1"></a></p>
<p>As one can see from the above diagrams (especially the last one, for epoch 1000), t-SNE does a very good job in clustering the handwritten digits correctly.</p>
<p>But the algorithm takes some time to run. Let’s try out the more efficient Barnes-Hut version of t-SNE, and see if we get equally good results.</p>
<h2>Rtsne package</h2>
<p>The <a rel="nofollow" href="https://cran.r-project.org/web/packages/Rtsne/index.html" target="_blank">Rtsne package</a> can be used as shown below. The perplexity parameter is crucial for t-SNE to work correctly – this parameter determines how the local and global aspects of the data are balanced. A more detailed explanation on this parameter and other aspects of t-SNE can be found in <a rel="nofollow" href="http://distill.pub/2016/misread-tsne/" target="_blank">this article</a>, but a perplexity value between 30 and 50 is recommended.</p>
<pre>
traindata &lt;- read.table(&quot;optdigits.tra&quot;, sep=&quot;,&quot;)
trn &lt;- data.matrix(traindata)

require(Rtsne)

# perform dimensionality redcution from 64D to 2D
tsne &lt;- Rtsne(as.matrix(trn[,1:64]), check_duplicates = FALSE, pca = FALSE, perplexity=30, theta=0.5, dims=2)

# display the results of t-SNE
cols &lt;- rainbow(10)
plot(tsne$Y, t='n')
text(tsne$Y, labels=trn[,65], col=cols[trn[,65] +1])

</pre>
<p>Gives this plot:<br>
<a rel="nofollow" href="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/09/tsne5.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/09/tsne5-490x340.png?w=450&ssl=1" alt="" class="wp-image-8605" data-recalc-dims="1"></a></p>
<p>Note how clearly-defined and distinctly separable the clusters of handwritten digits are. We have only a minimal amount of incorrect entries in the 2D map.</p>
<h2>Of Manifolds and the Manifold Assumption</h2>
<p>How can t-SNE achieve such a good result? How can it ‘drop’ 64-dimensional data into just 2 dimensions and still preserve enough (or all) structure to allow the classes to be separated?</p>
<p>The reason has to do with the mathematical concept of manifolds. A Manifold is a \(d\)-dimensional surface that lives in an \(D\)-dimensional space, where \(d &lt; D\). For the 3D case, imagine a 2D piece of paper that is embedded within 3D space. Even if the piece of paper is crumpled up extensively, it can still be ‘unwrapped’ (uncrumpled) into the 2D plane that it is. This 2D piece of paper is a manifold in 3D space. Or think of an entangled string in 3D space – this is a 1D manifold in 3D space.</p>
<p>Now there’s what is known as the <b>Manifold Hypothesis</b>, or the ><b>Manifold Assumption</b>, that states that natural data (like images, etc.) forms lower dimensional manifolds in their embedding space. If this assumption holds (there are theoretical and experimental evidence for this hypothesis), then t-SNE should be able to find this lower-dimensional manifold, ‘unwrap it’, and present it to us as a lower-dimensional map of the original data.</p>
<p><a rel="nofollow" href="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2017/09/manifold.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/09/manifold-490x257.png?w=450&ssl=1" alt="" class="wp-image-8604" data-recalc-dims="1"></a></p>
<h2>t-SNE vs. SOM</h2>
<p>t-SNE is actually a tool that does something similar to <b>Self-Organising Maps (SOMs)</b>, though the underlying process is quite different. We have used a SOM on the optdigits dataset in a <a rel="nofollow" href="https://mark-borg.github.io/blog/2016/optdigits-classification/#self-organising-map-som" target="_blank">previous blog</a> and obtained the following unsupervised clustering shown below.</p>
<p><a rel="nofollow" href="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/09/som-map-clusters-small2.png?ssl=1" target="_blank"><img sizes="(max-width: 487px) 100vw, 487px" src="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/09/som-map-clusters-small2-487x490.png?w=450&ssl=1" alt="" class="wp-image-8603" data-recalc-dims="1"></a></p>
<p>The t-SNE map is more clear than that obtained via a SOM and the clusters are separated much better.</p>
<h2>t-SNE for Shelter Animals dataset</h2>
<p>In a <a rel="nofollow" href="https://mark-borg.github.io/blog/2016/shelter-animal-competition/" target="_blank">previous blog</a>, I applied machine learning algorithms for predicting the outcome of shelter animals. Let’s now apply t-SNE to the dataset – I am using the cleaned and modified data as described in <a rel="nofollow" href="https://mark-borg.github.io/blog/2016/shelter-animal-competition/" target="_blank">this blog entry</a>.</p>
<pre>
trn &lt;- read.csv('train.modified.csv.zip')
trn &lt;- data.matrix(trn)

require(Rtsne)

# scale the data first prior to running t-SNE
trn[,-1]  &lt;- scale(trn[,-1])

tsne &lt;- Rtsne(trn[,-1], check_duplicates = FALSE, pca = FALSE, perplexity=50, theta=0.5, dims=2)

# display the results of t-SNE
cols &lt;- rainbow(5)
plot(tsne$Y, t='n')
text(tsne$Y, labels=as.numeric(trn[,1]), col=cols[trn[,1]])

</pre>
<p>Gives this plot:<br>
<a rel="nofollow" href="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2017/09/tsne6.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2017/09/tsne6-490x342.png?w=450&ssl=1" alt="" class="wp-image-8600" data-recalc-dims="1"></a></p>
<p>Here, while it is evident that there is some structure and patterns to the data, clustering by OutcomeType has not happened.</p>
<p>Let’s now use t-SNE to perform dimensionality reduction to 3D on the same dataset. We just need to set the dims parameter to 3 instead of 2. And we will use package rgl for plotting the 3D map produced by t-SNE.</p>
<pre>
tsne &lt;- Rtsne(trn[,-1], check_duplicates = FALSE, pca = FALSE, perplexity=50, theta=0.5, dims=2)

#display results of t-SNE
require(rgl)
plot3d(tsne$Y, col=cols[trn[,1]])
legend3d(&quot;topright&quot;, legend = '0':'5', pch = 16, col = rainbow(5))

</pre>
<p>Gives this plot:<br>
<a rel="nofollow" href="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2017/09/tsne7.png?ssl=1" target="_blank"><img sizes="(max-width: 490px) 100vw, 490px" src="https://i1.wp.com/datascienceplus.com/wp-content/uploads/2017/09/tsne7-490x448.png?w=450&ssl=1" alt="" class="wp-image-8602" data-recalc-dims="1"></a></p>
<p>This 3D map has a richer structure than the 2D version, but again the resulting clustering is not done by OutcomeType.</p>
<p>One possible reason could be that the Manifold Assumption is failing for this dataset when trying to reduce to 2D and 3D. Please note that the Manifold Assumption cannot be always true for a simple reason. If it were, we could take an arbitrary set of \(N\)-dimensional points and conclude that they lie on some \(M\)-dimensional manifold (where \(M &lt; N\)). We could then take those \(M\)-dimensional points and conclude that they lie on some other lower-dimensional manifold (with, say, \(K\) dimensions, where \(K &lt; M\)). We could repeat this process indefinitely and eventually conclude that our arbitrary \(N\)-dimensional dataset lies on a 1D manifold. Because this cannot be true for all datasets, the manifold assumption cannot always be true. In general, if you have \(N\)-dimensional points being generated by a process with <b>\(N\) degrees of freedom</b>, your data will not lie on a lower-dimensional manifold. So probably the Animal Shelter dataset has degrees of freedom higher than 3.</p>
<p>So we can conclude that t-SNE did not aid much the initial exploratory analysis for this dataset.</p>
<h2>t-SNE and machine learning?</h2>
<p>One disadvantage of t-SNE is that there is currently no incremental version of this algorithm. In other words, it is not possible to run t-SNE on a dataset, then gather a few more samples (rows), and “update” the t-SNE output with the new samples. You would need to re-run t-SNE from scratch on the full dataset (previous dataset + new samples). Thus t-SNE works only in batch mode.</p>
<p>This disadvantage appears to makes it difficult for t-SNE to be used in a machine learning system. But as we will see in a future post, it is still possible to use t-SNE (with care) in a machine learning solution. And the use of t-SNE can improve classification results, sometimes markedly. The limitation is the extra non-realtime processing brought about by t-SNE’s batch mode nature.</p>
<p>Stay tuned.</p>
<ul></ul>
<p><strong>
<p>Related Post</p>
<p>
<ol>
<li><a rel="nofollow" href="https://datascienceplus.com/comparing-trump-and-clintons-facebook-pages-during-the-us-presidential-election-2016/" title="Permanent Link toComparing Trump and Clinton’s Facebook pages during the US presidential election, 2016" target="_blank">Comparing Trump and Clinton’s Facebook pages during the US presidential election, 2016</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/analyzing-obesity-across-usa/" title="Permanent Link toAnalyzing Obesity across USA" target="_blank">Analyzing Obesity across USA</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/can-we-predict-flu-deaths-with-machine-learning-and-r/" title="Permanent Link toCan we predict flu deaths with Machine Learning and R?" target="_blank">Can we predict flu deaths with Machine Learning and R?</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/graphical-presentation-of-missing-data-vim-package/" title="Permanent Link toGraphical Presentation of Missing Data; VIM Package" target="_blank">Graphical Presentation of Missing Data; VIM Package</a></li>
<li><a rel="nofollow" href="https://datascienceplus.com/creating-graphs-with-python-and-goopycharts/" title="Permanent Link toCreating Graphs with Python and GooPyCharts" target="_blank">Creating Graphs with Python and GooPyCharts</a></li>
</ol></strong>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://datascienceplus.com/multi-dimensional-reduction-and-visualisation-with-t-sne/"> R Programming – DataScience+</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/RymdyC5Thig" height="1"></a></div>