<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/playing-with-dimensions-from-clustering-pca-t-sne-to-carl-sagan/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://blog.datascienceheroes.com/playing-with-dimensions-from-clustering-pca-t-sne-to-carl-sagan/"> R - Data Science Heroes Blog</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<h3>Playing with dimensions</h3>
<p><img alt="Playing with dimensions: from Clustering, PCA, t-SNE... to Carl Sagan!" src="https://i1.wp.com/blog.datascienceheroes.com/content/images/2017/02/cluster_analysis.png?w=456" data-recalc-dims="1">
<p>Hi there! This post is an experiment combining the result of <strong>t-SNE</strong> with two well known clustering techniques: <strong>k-means</strong> and <strong>hierarchical</strong>. This will be the practical section, in <strong>R</strong>.</p>
<p><img alt="Playing with dimensions: from Clustering, PCA, t-SNE... to Carl Sagan!" src="https://i2.wp.com/datascienceheroes.com/img/blog/cluster_analysis.png?w=285" data-recalc-dims="1"></p>
<p>But also, this post will explore the intersection point of concepts like dimension reduction, clustering analysis, data preparation, PCA, HDBSCAN, k-NN, SOM, deep learning…and Carl Sagan!</p>
<p><em>First published at: <a target="_blank" rel="nofollow" href="http://blog.datascienceheroes.com/playing-with-dimensions-from-clustering-pca-t-sne-to-carl-sagan">http://blog.datascienceheroes.com/playing-with-dimensions-from-clustering-pca-t-sne-to-carl-sagan</a></em> </p>
<h3>PCA and t-SNE</h3>
<p>For those who don’t know <strong>t-SNE</strong> technique (<a target="_blank" rel="nofollow" href="https://lvdmaaten.github.io/tsne/">official site</a>), it’s a projection technique -or dimension reduction- similar in some aspects to Principal Component Analysis (PCA), used to visualize N variables into 2 (for example).</p>
<p>When the t-SNE output is poor Laurens van der Maaten (t-SNE’s author) says: </p>
<blockquote>
<p>As a sanity check, try running PCA on your data to reduce it to two dimensions. If this also gives bad results, then maybe there is not very much nice structure in your data in the first place. If PCA works well but t-SNE doesn’t, I am fairly sure you did something wrong. </p>
</blockquote>
<p>In my experience, doing PCA with dozens of variables with:</p>
<ul>
<li>some extreme values </li>
<li>skewed distributions</li>
<li>several dummy variables, </li>
</ul>
<p>Doesn’t lead to good visualizations.</p>
<p>Check out this example comparing the two methods:</p>
<p><img alt="Playing with dimensions: from Clustering, PCA, t-SNE... to Carl Sagan!" src="https://i1.wp.com/datascienceheroes.com/img/blog/pca_tsne.png?w=400" data-recalc-dims="1"></p>
<p>Source: <a target="_blank" rel="nofollow" href="https://www.kaggle.com/puyokw/digit-recognizer/clustering-in-2-dimension-using-tsne/code">Clustering in 2-dimension using tsne</a></p>
<p>Makes sense, doesn’t it?</p>
<p></p>
<h3>Surfing higher dimensions <img alt="🏄" class="wp-smiley" src="https://s.w.org/images/core/emoji/2/72x72/1f3c4.png"></h3>
<p>Since one of the <strong>t-SNE</strong> results is a matrix of two dimensions, where each dot reprents an input case, we can apply a clustering and then group the cases according to their distance in this <strong>2-dimension map</strong>. Like a geography map does with mapping 3-dimension (our world), into two (paper).</p>
<p><strong>t-SNE</strong> puts similar cases together, handling non-linearities of data very well. After using the algorithm on several data sets, I believe that in some cases it creates something like <em>circular shapes</em> like islands, where these cases are similar.</p>
<p>However I didn’t see this effect on the live demonstration from the Google Brain team: <a target="_blank" rel="nofollow" href="http://distill.pub/2016/misread-tsne/">How to Use t-SNE Effectively</a>. Perhaps because of the nature of input data, 2 variables as input. </p>
<p> </p>
<h4>The swiss roll data</h4>
<p>t-SNE according to its FAQ doesn’t work very well with the <em>swiss roll</em> -toy- data. However it’s a stunning example of how a 3-Dimension surface (or <strong>manifold</strong>) with a concrete spiral shape <em>*is unfols</em> like paper thanks to a reducing dimension technique. </p>
<p>The image is taken from <a target="_blank" rel="nofollow" href="http://axon.cs.byu.edu/papers/gashler2011smc.pdf">this paper</a> where they used the <a target="_blank" rel="nofollow" href="https://en.wikipedia.org/wiki/Nonlinear_dimensionality_reduction#Manifold_sculpting">manifold sculpting</a> technique. </p>
<p><img alt="Playing with dimensions: from Clustering, PCA, t-SNE... to Carl Sagan!" src="https://i1.wp.com/datascienceheroes.com/img/blog/swiss_roll_manifold_sculpting.png?w=400" data-recalc-dims="1"></p>
<p></p>
<h3>Now the practice in R!</h3>
<p><strong>t-SNE</strong> helps make the cluster more accurate because it converts data into a 2-dimension space where dots are in a circular shape (which pleases to k-means and it’s one of its weak points when creating segments. More on this: <a target="_blank" rel="nofollow" href="http://varianceexplained.org/r/kmeans-free-lunch/">K-means clustering is not a free lunch</a>). </p>
<p>Sort of <strong>data preparation</strong> to apply the clustering models.</p>
<pre><code>library(caret)  
library(Rtsne)

######################################################################
## The WHOLE post is in: https://github.com/pablo14/post_cluster_tsne
######################################################################

## Download data from: https://github.com/pablo14/post_cluster_tsne/blob/master/data_1.txt (url path inside the gitrepo.)
data_tsne=read.delim(&quot;data_1.txt&quot;, header = T, stringsAsFactors = F, sep = &quot;\t&quot;)

## Rtsne function may take some minutes to complete...
set.seed(9)  
tsne_model_1 = Rtsne(as.matrix(data_tsne), check_duplicates=FALSE, pca=TRUE, perplexity=30, theta=0.5, dims=2)

## getting the two dimension matrix
d_tsne_1 = as.data.frame(tsne_model_1$Y)  
</code></pre>
<p>Different runs of <code>Rtsne</code> lead to different results. So more than likely you will not see exactly the same model as the one present here.</p>
<p>According to the official documentation, <code>perplexity</code> is related to the importance of neighbors: </p>
<ul>
<li><em>“It is comparable with the number of nearest neighbors k that is employed in many manifold learners.”</em></li>
<li><em>“Typical values for the perplexity range between 5 and 50”</em> </li>
</ul>
<p>Object <code>tsne_model_1$Y</code> contains the X-Y coordinates (<code>V1</code> and <code>V2</code> variables) for each input case.</p>
<p> </p>
<p>Plotting the t-SNE result:</p>
<pre><code>## plotting the results without clustering
ggplot(d_tsne_1, aes(x=V1, y=V2)) +  
  geom_point(size=0.25) +
  guides(colour=guide_legend(override.aes=list(size=6))) +
  xlab(&quot;&quot;) + ylab(&quot;&quot;) +
  ggtitle(&quot;t-SNE&quot;) +
  theme_light(base_size=20) +
  theme(axis.text.x=element_blank(),
        axis.text.y=element_blank()) +
  scale_colour_brewer(palette = &quot;Set2&quot;)
</code></pre>
<p><img alt="Playing with dimensions: from Clustering, PCA, t-SNE... to Carl Sagan!" src="https://i0.wp.com/datascienceheroes.com/img/blog/tsne_output.png?w=400" data-recalc-dims="1"></p>
<p></p>
<p>And there are the famous “islands” <img alt="🏝" class="wp-smiley" src="https://s.w.org/images/core/emoji/2/72x72/1f3dd.png">️. At this point, we can do some clustering by looking at it… But let’s try k-Means and hierarchical clustering instead <img alt="😄" class="wp-smiley" src="https://s.w.org/images/core/emoji/2/72x72/1f604.png">. t-SNE’s FAQ page suggest to decrease perplexity parameter to avoid this, nonetheless I didn’t find a problem with this result.</p>
<p></p>
<h4>Creating the cluster models</h4>
<p>Next piece of code will create the <strong>k-means</strong> and <strong>hierarchical</strong> cluster models. To then assign the cluster number (1, 2 or 3) to which each input case belongs.</p>
<pre><code>## keeping original data
d_tsne_1_original=d_tsne_1

## Creating k-means clustering model, and assigning the result to the data used to create the tsne
fit_cluster_kmeans=kmeans(scale(d_tsne_1), 3)  
d_tsne_1_original$cl_kmeans = factor(fit_cluster_kmeans$cluster)

## Creating hierarchical cluster model, and assigning the result to the data used to create the tsne
fit_cluster_hierarchical=hclust(dist(scale(d_tsne_1)))

## setting 3 clusters as output
d_tsne_1_original$cl_hierarchical = factor(cutree(fit_cluster_hierarchical, k=3))  
</code></pre>
<p></p>
<h4>Plotting the cluster models onto t-SNE output</h4>
<p>Now time to plot the result of each cluster model, based on the t-SNE map.</p>
<pre><code>plot_cluster=function(data, var_cluster, palette)  
{
  ggplot(data, aes_string(x=&quot;V1&quot;, y=&quot;V2&quot;, color=var_cluster)) +
  geom_point(size=0.25) +
  guides(colour=guide_legend(override.aes=list(size=6))) +
  xlab(&quot;&quot;) + ylab(&quot;&quot;) +
  ggtitle(&quot;&quot;) +
  theme_light(base_size=20) +
  theme(axis.text.x=element_blank(),
        axis.text.y=element_blank(),
        legend.direction = &quot;horizontal&quot;, 
        legend.position = &quot;bottom&quot;,
        legend.box = &quot;horizontal&quot;) + 
    scale_colour_brewer(palette = palette) 
}


plot_k=plot_cluster(d_tsne_1_original, &quot;cl_kmeans&quot;, &quot;Accent&quot;)  
plot_h=plot_cluster(d_tsne_1_original, &quot;cl_hierarchical&quot;, &quot;Set1&quot;)

## and finally: putting the plots side by side with gridExtra lib...
library(gridExtra)  
grid.arrange(plot_k, plot_h,  ncol=2)  
</code></pre>
<p><img alt="Playing with dimensions: from Clustering, PCA, t-SNE... to Carl Sagan!" src="https://i1.wp.com/datascienceheroes.com/img/blog/tsne_cluster_kmeans_hierarchical.png?w=456" data-recalc-dims="1"></p>
<p></p>
<h3>Visual analysis</h3>
<p>In this case, and based only on visual analysis, hierarchical seems to have more <em>common sense</em> than k-means. Take a look at following image:</p>
<p><img alt="Playing with dimensions: from Clustering, PCA, t-SNE... to Carl Sagan!" src="https://i2.wp.com/datascienceheroes.com/img/blog/cluster_analysis.png?w=456" data-recalc-dims="1"></p>
<p><em>Note: dashed lines separating the clusters were drawn by hand</em></p>
<p></p>
<p>In k-means, the distance in the points at the bottom left corner are quite close in comparison to the distance of other points inside the same cluster. But they belong to different clusters. Illustrating it:</p>
<p><img alt="Playing with dimensions: from Clustering, PCA, t-SNE... to Carl Sagan!" src="https://i1.wp.com/datascienceheroes.com/img/blog/kmeans_cluster.png?w=300" data-recalc-dims="1"></p>
<p>So we’ve got: red arrow is shorter than blue arrow…</p>
<p><em>Note: Different runs may lead to different groupings, if you don’t see this effect in that part of the map, search it in other.</em></p>
<p>This effect doesn’t happen in the hierarchical clustering. Clusters with this model seems more even. But what do you think?</p>
<p></p>
<h4>Biasing the analysis (cheating)</h4>
<p>It’s not fair to k-means to be compared like that. Last analysis based on the idea of <strong>density clustering</strong>. This technique is really cool to overcome the pitfalls of simpler methods.</p>
<p><strong>HDBSCAN</strong> algorithm bases its process in densities. </p>
<p>Find the essence of each one by looking at this picture: </p>
<p><img alt="Playing with dimensions: from Clustering, PCA, t-SNE... to Carl Sagan!" src="https://i1.wp.com/datascienceheroes.com/img/blog/hdbscan_vs_kmeans.png?w=456" data-recalc-dims="1"></p>
<p>Surely you understood the difference between them…</p>
<p>Last picture comes from <a target="_blank" rel="nofollow" href="http://nbviewer.jupyter.org/github/lmcinnes/hdbscan/blob/master/notebooks/Comparing%20Clustering%20Algorithms.ipynb">Comparing Python Clustering Algorithms</a>. Yes, Python, but it’s the same for R. The package is <a target="_blank" rel="nofollow" href="https://cran.r-project.org/web/packages/largeVis/vignettes/largeVis.html">largeVis</a>. <em>(Note: Install it by doing: <code>install_github(&quot;elbamos/largeVis&quot;, ref = &quot;release/0.2&quot;)</code></em>.</p>
<p></p>
<h3>Deep learning and t-SNE</h3>
<p>Quoting Luke Metz from a great post (<a target="_blank" rel="nofollow" href="https://indico.io/blog/visualizing-with-t-sne/">Visualizing with t-SNE</a>):</p>
<p><i>Recently there has been a lot of hype around the term “deep learning“. In most applications, these “deep” models can be boiled down to the composition of simple functions that embed from one high dimensional space to another. At first glance, these spaces might seem to large to think about or visualize, but techniques such as t-SNE allow us to start to understand what’s going on inside the black box. Now, instead of treating these models as black boxes, we can start to visualize and understand them.</i> </p>
<p>A deep comment <img alt="👏" class="wp-smiley" src="https://s.w.org/images/core/emoji/2/72x72/1f44f.png">.</p>
<p></p>
<h3>Final toughts <img alt="🚀" class="wp-smiley" src="https://s.w.org/images/core/emoji/2/72x72/1f680.png"></h3>
<p>Beyond this post, <strong>t-SNE</strong> has proven to be a really <strong>great</strong> general purpose tool to reduce dimensionality. It can be use to explore the relationships inside the data by building clusters, or to <a target="_blank" rel="nofollow" href="https://auth0.com/blog/machine-learning-for-everyone-part-2-abnormal-behavior">analyze anomaly cases</a> by inspecting the isolated points in the map. </p>
<p>Playing with dimensions is a key concept in data science and machine learning. Perplexity parameter is really similar to the <em>k</em> in nearest neighbors algorithm (<a target="_blank" rel="nofollow" href="https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm">k-NN</a>). Mapping data into 2-dimension and then do clustering? Hmmm not new buddy: <a target="_blank" rel="nofollow" href="http://www.shanelynn.ie/self-organising-maps-for-customer-segmentation-using-r/">Self-Organising Maps for Customer Segmentation</a>.</p>
<p>When we select the best features to build a model, we’re reducing the data’s dimension. When we build a model, we are creating a function that describes the relationships in data… and so on…</p>
<p>Did you know the general concepts about k-NN and PCA? Well this is one more step, just plug the cables in the brain and that’s it. Learning general concepts gives us the opportunity to do this kind of associations between all of these techniques. Despite comparing programming languages, the power -in my opinion- is to have the focus on how data behaves, and how these techniques are and can ultimately be- connected.</p>
<p></p>
<p>Explore the imagination with this <strong>Carl Sagan</strong>‘s video: Flatland and the 4th Dimension. A tale about the interaction of 3D objects into 2D plane…</p>
<p><iframe height="315" width="560" allowfullscreen src="https://www.youtube.com/embed/N0WjV6MmCyM"></iframe></p>
<p></p>
<hr>
<div>
<p><a target="_blank" rel="nofollow" href="http://livebook.datascienceheroes.com/"><br>
<img alt="Playing with dimensions: from Clustering, PCA, t-SNE... to Carl Sagan!" src="https://i2.wp.com/datascienceheroes.com/img/blog/book_gray.png?w=456" data-recalc-dims="1"> Data Science Live Book<br>
</a> (open source).</p>
</div>
<p></p>
<div>
<img alt="Playing with dimensions: from Clustering, PCA, t-SNE... to Carl Sagan!" src="https://i2.wp.com/datascienceheroes.com/img/blog/twitter_logo.PNG?w=456" data-recalc-dims="1"><br>
<a target="_blank" rel="nofollow" href="https://twitter.com/DataSciHeroes">DSH Twitter</a>
</div>
<p></p>
<div>
<img alt="Playing with dimensions: from Clustering, PCA, t-SNE... to Carl Sagan!" src="https://i2.wp.com/datascienceheroes.com/img/blog/fb_logo.PNG?w=456" data-recalc-dims="1">
<p><a target="_blank" rel="nofollow" href="https://www.facebook.com/datasciheroes"><br>
DSH Facebook<br>
</a>
</div>
<p></p>
<div>
<img alt="Playing with dimensions: from Clustering, PCA, t-SNE... to Carl Sagan!" src="https://i2.wp.com/datascienceheroes.com/img/blog/logo_dsh.png?w=456" data-recalc-dims="1"><br>
<a target="_blank" rel="nofollow" href="http://blog.datascienceheroes.com/"> More DSH posts!</a> 
</div>
<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://blog.datascienceheroes.com/playing-with-dimensions-from-clustering-pca-t-sne-to-carl-sagan/"> R - Data Science Heroes Blog</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 title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/search/data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/search/map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/search/animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/search/sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/search/SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/search/git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/search/hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/search/PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/search/time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/search/trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/htStO0cDIHI"></a></div>