<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/clustering-using-the-clusterr-package/"></div></div><div><a data-url="https://www.r-bloggers.com/clustering-using-the-clusterr-package/" data-counturl="https://www.r-bloggers.com/clustering-using-the-clusterr-package/" data-count="horizontal" data-text="Clustering using the ClusterR package" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://mlampros.github.io/mlampros.github.io/2016/09/12/clusterR_package/"> mlampros</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>This blog post is about clustering and specifically about my recently released package on CRAN, <strong>ClusterR</strong>. The following notes and examples are based mainly on the package Vignette.</p>
<p><a target="_blank" href="https://en.wikipedia.org/wiki/Cluster_analysis">Cluster analysis</a> or clustering is the task of grouping a set of objects in such a way that objects in the same group (called a cluster) are more similar (in some sense or another) to each other than to those in other groups (clusters). It is the main task of exploratory data mining, and a common technique for statistical data analysis, used in many fields, including machine learning, pattern recognition, image analysis, information retrieval, bioinformatics, data compression, and computer graphics.</p>
<p>The most prominent examples of clustering algorithms are <em>Connectivity-based clustering</em> (hierarchical clustering), <em>Centroid-based clustering</em> (k-means, k-medoids,…), <em>Distribution-based clustering</em> (Gaussian mixture models) and <em>Density-based clustering</em> (DBSCAN, OPTICS,…). </p>
<p>The <strong>ClusterR</strong> package consists of centroid-based (k-means, mini-batch-kmeans, k-medoids) and distribution-based (GMM) clustering algorithms. Furthermore, the package offers functions to</p>
<ul>
<li>validate the output using the true labels,</li>
<li>plot the results using either a silhouette or a 2-dimensional plot,</li>
<li>predict new observations,</li>
<li>estimate the optimal number of clusters for each algorithm separately.<br>
</li>
</ul>
<h4><strong>Gaussian Mixture Models (GMM)</strong></h4>
<p></p>
<p><a target="_blank" href="https://brilliant.org/wiki/gaussian-mixture-model/">Gaussian Mixture Models</a> are a probabilistic model for representing normally distributed subpopulations within an overall population. A Gaussian mixture model is parameterized by two types of values, the mixture <em>component weights</em> and the <em>component means</em> and <em>covariances</em> (for the <em>multivariate</em> case). If the number of components is known, expectation maximization is the technique most commonly used to estimate the mixture model’s parameters.</p>
<p>The <strong>GMM</strong> function in the <em>ClusterR</em> package is an R implementation of the <a target="_blank" href="http://arma.sourceforge.net/docs.html#gmm_diag">Armadillo library</a> class for modeling data as a Gaussian Mixture Model (GMM), under the assumption of <em>diagonal</em> covariance matrices. A number of function parameters can be tuned, among others the <em>gaussian_comps</em>, the <em>dist_mode</em> (eucl_dist, maha_dist), the <em>seed_mode</em> (static_subset, random_subset, static_spread, random_spread), the <em>km_iter</em> and the <em>em_iter</em> (more information about the parameters can be found in the package documentation). I’ll illustrate the <em>GMM</em> function using the synthetic data <em>dietary_survey_IBS</em>,</p>
<div>
<pre><code><span>
</span><span>library</span><span>(</span><span>ClusterR</span><span>)</span><span>
</span><span>data</span><span>(</span><span>dietary_survey_IBS</span><span>)</span><span>
</span><span>dim</span><span>(</span><span>dietary_survey_IBS</span><span>)</span><span>
</span><span>## [1] 400 43
</span><span>
</span><span>X</span><span> </span><span>=</span><span> </span><span>dietary_survey_IBS</span><span>[,</span><span> </span><span>-</span><span>ncol</span><span>(</span><span>dietary_survey_IBS</span><span>)]</span><span> </span><span># data (excluding the response variable)
</span><span>
</span><span>y</span><span> </span><span>=</span><span> </span><span>dietary_survey_IBS</span><span>[,</span><span> </span><span>ncol</span><span>(</span><span>dietary_survey_IBS</span><span>)]</span><span> </span><span># the response variable
</span><span>
</span><span>dat</span><span> </span><span>=</span><span> </span><span>center_scale</span><span>(</span><span>X</span><span>,</span><span> </span><span>mean_center</span><span> </span><span>=</span><span> </span><span>T</span><span>,</span><span> </span><span>sd_scale</span><span> </span><span>=</span><span> </span><span>T</span><span>)</span><span> </span><span># centering and scaling the data
</span><span>
</span><span>gmm</span><span> </span><span>=</span><span> </span><span>GMM</span><span>(</span><span>dat</span><span>,</span><span> </span><span>2</span><span>,</span><span> </span><span>dist_mode</span><span> </span><span>=</span><span> </span><span>&quot;maha_dist&quot;</span><span>,</span><span> </span><span>seed_mode</span><span> </span><span>=</span><span> </span><span>&quot;random_subset&quot;</span><span>,</span><span> </span><span>km_iter</span><span> </span><span>=</span><span> </span><span>10</span><span>,</span><span>
</span><span>em_iter</span><span> </span><span>=</span><span> </span><span>10</span><span>,</span><span> </span><span>verbose</span><span> </span><span>=</span><span> </span><span>F</span><span>)</span><span> </span><span># predict centroids, covariance matrix and weights
</span><span>
</span><span>pr</span><span> </span><span>=</span><span> </span><span>predict_GMM</span><span>(</span><span>dat</span><span>,</span><span> </span><span>gmm</span><span>$</span><span>centroids</span><span>,</span><span> </span><span>gmm</span><span>$</span><span>covariance_matrices</span><span>,</span><span> </span><span>gmm</span><span>$</span><span>weights</span><span>)</span><span> </span></code></pre>
</div>
<p></p>
<p>The <em>GMM</em> function, initially, returns the <em>centroids</em>, the <em>covariance matrix</em> ( where each row of the matrix represents a diagonal covariance matrix), the <em>weights</em> and the <em>log-likelihoods</em> for each gaussian component. Then, the <em>predict_GMM</em> function takes the output of the <em>GMM</em> model and returns the probable clusters.</p>
<p>In addition to the previous mentioned functions, the <strong>Optimal_Clusters_GMM</strong> can be utilized to estimate the number of clusters of the data using either the <em>AIC</em> (Akaike information) or the <em>BIC</em> (Bayesian information) criterion,</p>
<p></p>
<div>
<pre><code><span>
</span><span>opt_gmm</span><span> </span><span>=</span><span> </span><span>Optimal_Clusters_GMM</span><span>(</span><span>dat</span><span>,</span><span> </span><span>max_clusters</span><span> </span><span>=</span><span> </span><span>10</span><span>,</span><span> </span><span>criterion</span><span> </span><span>=</span><span> </span><span>&quot;BIC&quot;</span><span>,</span><span> </span><span>dist_mode</span><span> </span><span>=</span><span> </span><span>&quot;maha_dist&quot;</span><span>,</span><span> </span><span>seed_mode</span><span> </span><span>=</span><span> </span><span>&quot;random_subset&quot;</span><span>,</span><span>
</span><span>km_iter</span><span> </span><span>=</span><span> </span><span>10</span><span>,</span><span> </span><span>em_iter</span><span> </span><span>=</span><span> </span><span>10</span><span>,</span><span> </span><span>var_floor</span><span> </span><span>=</span><span> </span><span>1e-10</span><span>,</span><span> </span><span>plot_data</span><span> </span><span>=</span><span> </span><span>T</span><span>)</span><span>
</span></code></pre>
</div>
<p><img alt="Alt text" src="https://i0.wp.com/mlampros.github.io/images/Rplot1.png?w=456" data-recalc-dims="1"></p>
<p></p>
<p>In case of model selection, among a specific number of models, the model with the lowest <a target="_blank" href="https://en.wikipedia.org/wiki/Bayesian_information_criterion">BIC</a> should be preferred, which is true here for a number of clusters equal to 2.</p>
<p>Assuming that true labels are available, then one could use the <strong>external_validation</strong> methods (<em>rand_index</em>, <em>adjusted_rand_index</em>, <em>jaccard_index</em>, <em>fowlkes_Mallows_index</em>, <em>mirkin_metric</em>, <em>purity</em>, <em>entropy</em>, <em>nmi</em> (normalized mutual information) and <em>var_info</em> (variation of information) to validate the output clusters,</p>
<p></p>
<div>
<pre><code><span>
</span><span>res</span><span> </span><span>=</span><span> </span><span>external_validation</span><span>(</span><span>dietary_survey_IBS</span><span>$</span><span>class</span><span>,</span><span> </span><span>pr</span><span>$</span><span>cluster_labels</span><span>,</span><span> </span><span>method</span><span> </span><span>=</span><span> </span><span>&quot;adjusted_rand_index&quot;</span><span>,</span><span> </span><span>summary_stats</span><span> </span><span>=</span><span> </span><span>T</span><span>)</span><span>
</span><span>res</span><span>
</span><span>## ## ---------------------------------------- ## purity : 1 ## entropy : 0 ## normalized mutual information : 1 ## variation of information : 0 ## ---------------------------------------- ## specificity : 1 ## sensitivity : 1 ## precision : 1 ## recall : 1 ## F-measure : 1 ## ---------------------------------------- ## accuracy OR rand-index : 1 ## adjusted-rand-index : 1 ## jaccard-index : 1 ## fowlkes-mallows-index : 1 ## mirkin-metric : 0 ## ----------------------------------------
</span><span>
</span></code></pre>
</div>
<p>and if the <em>summary_stats</em> parameter is set to TRUE then it also returns the <em>specificity</em>, <em>sensitivity</em>, <em>precision</em>, <em>recall</em> and <em>F-measure</em> metrics.</p>

<h4><strong>k-means</strong></h4>
<p><a target="_blank" href="https://en.wikipedia.org/wiki/K-means_clustering">k-means</a> clustering is a method of vector quantization, originally from signal processing, that is popular for cluster analysis in data mining. k-means clustering aims to partition <em>n</em> observations into <em>k</em> clusters in which each observation belongs to the cluster with the nearest mean, serving as a prototype of the cluster. This results in a partitioning of the data space into <a target="_blank" href="https://en.wikipedia.org/wiki/Voronoi_diagram">Voronoi</a> cells. The most common algorithm uses an iterative refinement technique. Due to its ubiquity, it is often called the k-means algorithm; it is also referred to as <a target="_blank" href="https://en.wikipedia.org/wiki/Lloyd%27s_algorithm">Lloyd’s algorithm</a>, particularly in the computer science community.<br>
</p>
<p>The ClusterR package provides two different k-means functions, the <em>KMeans_arma</em>, which is an R implementation of the k-means armadillo library and the <em>KMeans_rcpp</em> which uses the RcppArmadillo package. Both functions come to the same output results, however, they return different features which I’ll explain in the next code chunks.</p>
<p><strong>KMeans_arma</strong><br>
</p>
<p>The <em>KMeans_arma</em> is faster than the KMeans_rcpp function, however, it initially outputs only the centroids for a specific number of clusters. Furthermore, the number of columns of the data should be larger than the number of clusters, otherwise, it raises an error. The clustering will run faster on multi-core machines when OpenMP is enabled (eg. -fopenmp in GCC). The algorithm is initialized once and 10 iterations are typically sufficient for convergence. The initial centroids are seeded using one of <em>keep_existing</em>, <em>static_subset</em>, <em>random_subset</em>, <em>static_spread</em> and <em>random_spread</em>. If the seed_mode equals to keep_existing then the user should supply a matrix of centroids. </p>
<p>I’ll reduce the dimensions of the dietary_survey_IBS data using PCA and particularly the <em>princomp</em> function of the <em>stats</em> package, so that a 2-dimensional plot of the resulted clusters is possible,</p>
<div>
<pre><code><span>
</span><span>pca_dat</span><span> </span><span>=</span><span> </span><span>stats</span><span>::</span><span>princomp</span><span>(</span><span>dat</span><span>)</span><span>$</span><span>scores</span><span>[,</span><span> </span><span>1</span><span>:</span><span>2</span><span>]</span><span>
</span><span>km</span><span> </span><span>=</span><span> </span><span>KMeans_arma</span><span>(</span><span>pca_dat</span><span>,</span><span> </span><span>clusters</span><span> </span><span>=</span><span> </span><span>2</span><span>,</span><span> </span><span>n_iter</span><span> </span><span>=</span><span> </span><span>10</span><span>,</span><span> </span><span>seed_mode</span><span> </span><span>=</span><span> </span><span>&quot;random_subset&quot;</span><span>,</span><span> </span><span>verbose</span><span> </span><span>=</span><span> </span><span>T</span><span>,</span><span> </span><span>CENTROIDS</span><span> </span><span>=</span><span> </span><span>NULL</span><span>)</span><span>
</span><span>pr</span><span> </span><span>=</span><span> </span><span>predict_KMeans</span><span>(</span><span>pca_dat</span><span>,</span><span> </span><span>km</span><span>)</span><span>
</span><span>table</span><span>(</span><span>dietary_survey_IBS</span><span>$</span><span>class</span><span>,</span><span> </span><span>pr</span><span>)</span><span>
</span><span>class</span><span>(</span><span>km</span><span>)</span><span> </span><span>=</span><span> </span><span>'matrix'</span><span>
</span><span>plot_2d</span><span>(</span><span>data</span><span> </span><span>=</span><span> </span><span>pca_dat</span><span>,</span><span> </span><span>clusters</span><span> </span><span>=</span><span> </span><span>as.vector</span><span>(</span><span>pr</span><span>),</span><span> </span><span>centroids_medoids</span><span> </span><span>=</span><span> </span><span>as.matrix</span><span>(</span><span>km</span><span>))</span><span>
</span></code></pre>
</div>
<p></p>
<p><img alt="Alt text" src="https://i1.wp.com/mlampros.github.io/images/Rplot_2d.png?w=456" data-recalc-dims="1"></p>
<p><strong>KMeans_rcpp</strong><br>
</p>
<p>As stated before the <em>KMeans_rcpp</em> function offers some additional features in comparison to the <em>KMeans_arma</em> function,</p>
<ul>
<li>It allows for multiple initializations (which can be parallelized if Openmp is available)</li>
<li>Besides <em>optimal_init</em>, <em>quantile_init</em>, <em>random</em> and <em>kmeans++</em> initilizations one can specify the centroids using the CENTROIDS parameter</li>
<li>The running time and convergence of the algorithm can be adjusted using the <em>num_init</em>, <em>max_iters</em> and <em>tol</em> parameters</li>
<li>If num_init > 1 then KMeans_rcpp returns the attributes of the best initialization using as criterion the within-cluster-sum-of-squared-error</li>
<li>The algorithm returns the following attributes: <em>clusters</em>, <em>fuzzy_clusters</em> (if fuzzy = TRUE), <em>centroids</em>, <em>total_SSE</em>, <em>best_initialization</em>, <em>WCSS_per_cluster</em>, <em>obs_per_cluster</em>, <em>between.SS_DIV_total.SS</em></li>
</ul>
<p>
More details about KMeans_rcpp can be found in the package documentation. I’ll explain the various parameters of the <em>KMeans_rcpp</em> using a <a target="_blank" href="https://en.wikipedia.org/wiki/Vector_quantization">vector quantization</a> example and the OpenImageR package,<br>
</p>
<div>
<pre><code><span>
</span><span>library</span><span>(</span><span>OpenImageR</span><span>)</span><span>
</span><span>path</span><span> </span><span>=</span><span> </span><span>'elephant.jpg'</span><span>
</span><span>im</span><span> </span><span>=</span><span> </span><span>readImage</span><span>(</span><span>path</span><span>)</span><span>
</span><span># first resize the image to reduce the dimensions
</span><span>im</span><span> </span><span>=</span><span> </span><span>resizeImage</span><span>(</span><span>im</span><span>,</span><span> </span><span>75</span><span>,</span><span> </span><span>75</span><span>,</span><span> </span><span>method</span><span> </span><span>=</span><span> </span><span>'bilinear'</span><span>)</span><span> </span><span>imageShow</span><span>(</span><span>im</span><span>)</span><span> </span><span># plot the original image
</span><span>
</span><span>im2</span><span> </span><span>=</span><span> </span><span>apply</span><span>(</span><span>im</span><span>,</span><span> </span><span>3</span><span>,</span><span> </span><span>as.vector</span><span>)</span><span> </span><span># vectorize RGB
</span></code></pre>
</div>
<p><img alt="Alt text" src="https://i0.wp.com/mlampros.github.io/images/Rplot_eleph.png?w=456" data-recalc-dims="1"></p>
<p></p>
<div>
<pre><code><span>
</span><span># perform KMeans_rcpp clustering
</span><span>
</span><span>km_rc</span><span> </span><span>=</span><span> </span><span>KMeans_rcpp</span><span>(</span><span>im2</span><span>,</span><span> </span><span>clusters</span><span> </span><span>=</span><span> </span><span>5</span><span>,</span><span> </span><span>num_init</span><span> </span><span>=</span><span> </span><span>5</span><span>,</span><span> </span><span>max_iters</span><span> </span><span>=</span><span> </span><span>100</span><span>,</span><span> </span><span>initializer</span><span> </span><span>=</span><span> </span><span>'optimal_init'</span><span>,</span><span> </span><span>threads</span><span> </span><span>=</span><span> </span><span>1</span><span>,</span><span> </span><span>verbose</span><span> </span><span>=</span><span> </span><span>F</span><span>)</span><span>
</span><span>km_rc</span><span>$</span><span>between.SS_DIV_total.SS</span><span>
</span><span>## [1] 0.9873009
</span></code></pre>
</div>
<p></p>
<p>The attribute <em>between.SS_DIV_total.SS</em> is equal to <em>(total_SSE – sum(WCSS_per_cluster)) / total_SSE</em>. If there is no pattern of clustering then the between sum of squares will be a very small fraction of the total sum of squares, whereas if the <em>between.SS_DIV_total.SS</em> attribute is close to 1.0 then the observations cluster pretty well.</p>
<p></p>
<div>
<pre><code><span>getcent</span><span> </span><span>=</span><span> </span><span>km_rc</span><span>$</span><span>centroids</span><span>
</span><span>getclust</span><span> </span><span>=</span><span> </span><span>km_rc</span><span>$</span><span>clusters</span><span>
</span><span>new_im</span><span> </span><span>=</span><span> </span><span>getcent</span><span>[</span><span>getclust</span><span>,</span><span> </span><span>]</span><span> </span><span># each observation is associated with the nearby centroid
</span><span>
</span><span>dim</span><span>(</span><span>new_im</span><span>)</span><span> </span><span>=</span><span> </span><span>c</span><span>(</span><span>nrow</span><span>(</span><span>im</span><span>),</span><span> </span><span>ncol</span><span>(</span><span>im</span><span>),</span><span> </span><span>3</span><span>)</span><span> </span><span># back-convertion to a 3-dimensional image
</span><span>
</span><span>imageShow</span><span>(</span><span>new_im</span><span>)</span><span>
</span></code></pre>
</div>
<p><img alt="Alt text" src="https://i0.wp.com/mlampros.github.io/images/Rplot_km.png?w=456" data-recalc-dims="1"></p>
<p></p>
<p>As a follow-up one can take advantage of the <strong>Optimal_Clusters_KMeans</strong> function (which indirectly uses KMeans_rcpp) to estimate the optimal number of clusters. The available criteria are <em>variance_explained</em>, <em>WCSSE</em> (within-cluster-sum-of-squared-error), <em>dissimilarity</em>, <em>silhouette</em>, <em>distortion_fK</em>, <em>AIC</em>, <em>BIC</em> and <em>Adjusted_Rsquared</em>. More information on each criterion can be found in the package documentation.<br>
</p>
<p>In the next code chunk I’ll use the <em>distortion_fK</em> criterion, which is fully described in the “Selection of K in K-means clustering, Pham., Dimov., Nguyen., (2004)” paper,<br>
</p>
<div>
<pre><code><span>
</span><span>opt</span><span> </span><span>=</span><span> </span><span>Optimal_Clusters_KMeans</span><span>(</span><span>im2</span><span>,</span><span> </span><span>max_clusters</span><span> </span><span>=</span><span> </span><span>10</span><span>,</span><span> </span><span>plot_clusters</span><span> </span><span>=</span><span> </span><span>T</span><span>,</span><span> </span><span>verbose</span><span> </span><span>=</span><span> </span><span>F</span><span>,</span><span> </span><span>criterion</span><span> </span><span>=</span><span> </span><span>'distortion_fK'</span><span>,</span><span> </span><span>fK_threshold</span><span> </span><span>=</span><span> </span><span>0.85</span><span>)</span><span>
</span></code></pre>
</div>
<p><img alt="Alt text" src="https://i0.wp.com/mlampros.github.io/images/Rplot_distortion.png?w=456" data-recalc-dims="1"></p>
<p></p>
<p>Values below the fixed threshold (here fK_threshold = 0.85) could be recommended for clustering, however there are multiple optimal clusterings and this highlights the fact that f(K) should only be used to suggest a guide value for the number of clusters and the final decision as to which value to adopt has to be left at the discretion of the user.</p>
<h4><strong>Mini-batch-kmeans</strong></h4>
<p></p>
<p><a target="_blank" href="http://www.eecs.tufts.edu/~dsculley/papers/fastkmeans.pdf">Mini-batch-kmeans</a> is a variation of the classical k-means algorithm. It is particularly useful for big data sets because rather than using the whole data (as k-means does) it uses mini-batches from random data samples to optimize the objective function.<br>
</p>
<p>The parameters of the <strong>MiniBatchKmeans</strong> algorithm are almost the same as for the KMeans_rcpp function in the ClusterR package. The most important differences are the <em>batch_size</em> (the size of the mini batches) and the <em>init_fraction</em> (the percentage of data to use for the initialized centroids, which applies if the initializer equals to ‘kmeans++’ or ‘quantile_init’).<br>
</p>
<p>I’ll take advantage of the <em>vector quantization</em> example to show the differences in computation time and output quality between the KMeans_rcpp and MiniBatchKmeans functions,<br>
</p>
<div>
<pre><code><span>
</span><span>path_d</span><span> </span><span>=</span><span> </span><span>'dog.jpg'</span><span>
</span><span>im_d</span><span> </span><span>=</span><span> </span><span>readImage</span><span>(</span><span>path_d</span><span>)</span><span>
</span><span># first resize the image to reduce the dimensions
</span><span>im_d</span><span> </span><span>=</span><span> </span><span>resizeImage</span><span>(</span><span>im_d</span><span>,</span><span> </span><span>350</span><span>,</span><span> </span><span>350</span><span>,</span><span> </span><span>method</span><span> </span><span>=</span><span> </span><span>'bilinear'</span><span>)</span><span> </span><span>imageShow</span><span>(</span><span>im_d</span><span>)</span><span> </span><span># plot the original image
</span></code></pre>
</div>
<p></p>
<p><img alt="Alt text" src="https://i1.wp.com/mlampros.github.io/images/Rplot_dog.png?w=456" data-recalc-dims="1"></p>
<p></p>
<div>
<pre><code><span>im3</span><span> </span><span>=</span><span> </span><span>apply</span><span>(</span><span>im_d</span><span>,</span><span> </span><span>3</span><span>,</span><span> </span><span>as.vector</span><span>)</span><span> </span><span># vectorize RGB
</span><span>
</span><span>dim</span><span>(</span><span>im3</span><span>)</span><span> </span><span># initial dimensions of the data
</span><span>
</span><span># 122500 3
</span></code></pre>
</div>
<p></p>
<p>First, we perform a <em>k-means</em> clustering,<br>
</p>
<div>
<pre><code><span>
</span><span>start</span><span> </span><span>=</span><span> </span><span>Sys.time</span><span>()</span><span>
</span><span>km_init</span><span> </span><span>=</span><span> </span><span>KMeans_rcpp</span><span>(</span><span>im3</span><span>,</span><span> </span><span>clusters</span><span> </span><span>=</span><span> </span><span>5</span><span>,</span><span> </span><span>num_init</span><span> </span><span>=</span><span> </span><span>5</span><span>,</span><span> </span><span>max_iters</span><span> </span><span>=</span><span> </span><span>100</span><span>,</span><span> </span><span>initializer</span><span> </span><span>=</span><span> </span><span>'kmeans++'</span><span>,</span><span> </span><span>threads</span><span> </span><span>=</span><span> </span><span>1</span><span>,</span><span> </span><span>verbose</span><span> </span><span>=</span><span> </span><span>F</span><span>)</span><span>
</span><span>end</span><span> </span><span>=</span><span> </span><span>Sys.time</span><span>()</span><span>
</span><span>t</span><span> </span><span>=</span><span> </span><span>end</span><span> </span><span>-</span><span> </span><span>start</span><span>
</span><span>cat</span><span>(</span><span>'time to complete :'</span><span>,</span><span> </span><span>t</span><span>,</span><span> </span><span>attributes</span><span>(</span><span>t</span><span>)</span><span>$</span><span>units</span><span>,</span><span> </span><span>'\n'</span><span>)</span><span>
</span><span># time to complete : 2.44029 secs
</span><span>
</span><span>getcent_init</span><span> </span><span>=</span><span> </span><span>km_init</span><span>$</span><span>centroids</span><span>
</span><span>getclust_init</span><span> </span><span>=</span><span> </span><span>km_init</span><span>$</span><span>clusters</span><span>
</span><span>new_im_init</span><span> </span><span>=</span><span> </span><span>getcent_init</span><span>[</span><span>getclust_init</span><span>,</span><span> </span><span>]</span><span> </span><span># each observation is associated with the nearby centroid
</span><span>
</span><span>dim</span><span>(</span><span>new_im_init</span><span>)</span><span> </span><span>=</span><span> </span><span>c</span><span>(</span><span>nrow</span><span>(</span><span>im_d</span><span>),</span><span> </span><span>ncol</span><span>(</span><span>im_d</span><span>),</span><span> </span><span>3</span><span>)</span><span> </span><span># back-convertion to a 3-dimensional image
</span><span>
</span><span>imageShow</span><span>(</span><span>new_im_init</span><span>)</span><span>
</span></code></pre>
</div>
<p></p>
<p><img alt="Alt text" src="https://i1.wp.com/mlampros.github.io/images/Rplot_dog_km.png?w=456" data-recalc-dims="1"></p>
<p></p>
<p>and then a <em>mini-batch-kmeans</em> clustering,<br>
</p>
<div>
<pre><code><span>
</span><span>start</span><span> </span><span>=</span><span> </span><span>Sys.time</span><span>()</span><span>
</span><span>km_mb</span><span> </span><span>=</span><span> </span><span>MiniBatchKmeans</span><span>(</span><span>im3</span><span>,</span><span> </span><span>clusters</span><span> </span><span>=</span><span> </span><span>5</span><span>,</span><span> </span><span>batch_size</span><span> </span><span>=</span><span> </span><span>20</span><span>,</span><span> </span><span>num_init</span><span> </span><span>=</span><span> </span><span>5</span><span>,</span><span> </span><span>max_iters</span><span> </span><span>=</span><span> </span><span>100</span><span>,</span><span> </span><span>init_fraction</span><span> </span><span>=</span><span> </span><span>0.2</span><span>,</span><span> </span><span>initializer</span><span> </span><span>=</span><span> </span><span>'kmeans++'</span><span>,</span><span> </span><span>early_stop_iter</span><span> </span><span>=</span><span> </span><span>10</span><span>,</span><span>
</span><span>verbose</span><span> </span><span>=</span><span> </span><span>F</span><span>)</span><span>
</span><span>pr_mb</span><span> </span><span>=</span><span> </span><span>predict_MBatchKMeans</span><span>(</span><span>im3</span><span>,</span><span> </span><span>km_mb</span><span>$</span><span>centroids</span><span>)</span><span>
</span><span>end</span><span> </span><span>=</span><span> </span><span>Sys.time</span><span>()</span><span>
</span><span>t</span><span> </span><span>=</span><span> </span><span>end</span><span> </span><span>-</span><span> </span><span>start</span><span>
</span><span>cat</span><span>(</span><span>'time to complete :'</span><span>,</span><span> </span><span>t</span><span>,</span><span> </span><span>attributes</span><span>(</span><span>t</span><span>)</span><span>$</span><span>units</span><span>,</span><span> </span><span>'\n'</span><span>)</span><span>
</span><span># time to complete : 0.8346727 secs </span><span>
</span><span>getcent_mb</span><span> </span><span>=</span><span> </span><span>km_mb</span><span>$</span><span>centroids</span><span>
</span><span>new_im_mb</span><span> </span><span>=</span><span> </span><span>getcent_mb</span><span>[</span><span>pr_mb</span><span>,</span><span> </span><span>]</span><span> </span><span># each observation is associated with the nearby centroid
</span><span>
</span><span>dim</span><span>(</span><span>new_im_mb</span><span>)</span><span> </span><span>=</span><span> </span><span>c</span><span>(</span><span>nrow</span><span>(</span><span>im_d</span><span>),</span><span> </span><span>ncol</span><span>(</span><span>im_d</span><span>),</span><span> </span><span>3</span><span>)</span><span> </span><span># back-convertion to a 3-dimensional image
</span><span>
</span><span>imageShow</span><span>(</span><span>new_im_mb</span><span>)</span><span>
</span></code></pre>
</div>
<p></p>
<p><img alt="Alt text" src="https://i0.wp.com/mlampros.github.io/images/Rplot_minibkm.png?w=456" data-recalc-dims="1"></p>
<p></p>
<p>For a slight difference in the output quality, the mini-batch-kmeans returns the output in average more than twice as fast as the classical k-means for this data set.</p>
<p></p>
<p>In order to implement the mini-batch-kmeans I consulted the following web-resources:</p>
<ul>
<li>
<p><a target="_blank" href="http://www.eecs.tufts.edu/~dsculley/papers/fastkmeans.pdf">http://www.eecs.tufts.edu/~dsculley/papers/fastkmeans.pdf</a></p>
</li>
<li>
<p><a target="_blank" href="https://github.com/siddharth-agrawal/Mini-Batch-K-Means">https://github.com/siddharth-agrawal/Mini-Batch-K-Means</a></p>
</li>
<li>
<p><a target="_blank" href="https://github.com/scikit-learn/scikit-learn/blob/51a765a/sklearn/cluster/k_means_.py#L1113">https://github.com/scikit-learn/scikit-learn/blob/51a765a/sklearn/cluster/k_means_.py#L1113</a></p>
</li>
</ul>
<h4><strong>K-Medoids</strong></h4>
<p></p>
<p>The <a target="_blank" href="https://en.wikipedia.org/wiki/K-medoids">k-medoids</a> algorithm (Kaufman, L., Rousseeuw, P., 1987) is a clustering algorithm related to the k-means algorithm and the medoid shift algorithm. Both the k-means and k-medoids algorithms are partitional and both attempt to minimize the distance between points labeled to be in a cluster and a point designated as the center of that cluster. In contrast to the k-means algorithm, k-medoids chooses <em>data points as centers</em> (medoids or exemplars) and works with an <em>arbitrary metrics of distances</em> between data points. A useful tool for determining k is the silhouette width. K-medoids is more robust to noise and outliers in comparison to k-means, because it minimizes a sum of pairwise dissimilarities instead of the sum of squared Euclidean distances. A medoid can be defined as the object of a cluster whose average dissimilarity to all the objects in the cluster is minimal, i.e. it is a most centrally located point in the cluster.</p>
<p>The most common realization of the k-medoid clustering is the Partitioning Around Medoids (PAM) algorithm. PAM proceeds in two phases: BUILD and SWAP. In the BUILD phase, the algorithm searches for a good set of initial medoids and in the SWAP phase all possible swaps between the BUILD-medoids and the observations take place so that there is no further decrease of the objective (Clustering in an Object-Oriented Environment, A.Struyf, M. Hubert, P. Rousseeuw., 1997).</p>
<p>In the ClusterR package, the <strong>Cluster_Medoids</strong> and <strong>Clara_Medoids</strong> functions correspond to PAM (partitioning around medoids) and CLARA (clustering large applications) algorithms. </p>
<p>In the following code chunk, I’ll make use of the <em>mushroom</em> data to illustrate how k-medoids work with a distance metric other than the euclidean. The mushroom data consist of 23 categorical attributes (including the class) and 8124 instances. More information about the data can be found in the package documentation.</p>
<p><strong>Cluster_Medoids</strong></p>
<p>The <em>Cluster_Medoids</em> function can also take – besides a matrix or data frame – a dissimilarity matrix as input. In the case of the mushroom data, where all the features are categorical (with two or more unique values) it would be meaningful to use the <em>gower</em> distance. The <em>gower</em> distance applies a different function to each predictor depending on its type (numeric, ordered, factor). This dissimilarity measure is implemented in many R packages, among others in the cluster package (<em>daisy</em> function) and in the FD package (<em>gowdis</em> function). I’ll take advantage of the <em>gowdis</em> function of the FD package as it also allows user-defined weights for each separate predictor,</p>
<div>
<pre><code><span>
</span><span>data</span><span>(</span><span>mushroom</span><span>)</span><span>
</span><span>X</span><span> </span><span>=</span><span> </span><span>mushroom</span><span>[,</span><span> </span><span>-1</span><span>]</span><span>
</span><span>y</span><span> </span><span>=</span><span> </span><span>as.numeric</span><span>(</span><span>mushroom</span><span>[,</span><span> </span><span>1</span><span>])</span><span> </span><span># convert the labels to numeric
</span><span>
</span><span>gwd</span><span> </span><span>=</span><span> </span><span>FD</span><span>::</span><span>gowdis</span><span>(</span><span>X</span><span>)</span><span> </span><span># calculate the 'gower' distance for the factor variables
</span><span>
</span><span>gwd_mat</span><span> </span><span>=</span><span> </span><span>as.matrix</span><span>(</span><span>gwd</span><span>)</span><span> </span><span># convert the distances to a matrix
</span><span>
</span><span>cm</span><span> </span><span>=</span><span> </span><span>Cluster_Medoids</span><span>(</span><span>gwd_mat</span><span>,</span><span> </span><span>clusters</span><span> </span><span>=</span><span> </span><span>2</span><span>,</span><span> </span><span>swap_phase</span><span> </span><span>=</span><span> </span><span>TRUE</span><span>,</span><span> </span><span>verbose</span><span> </span><span>=</span><span> </span><span>F</span><span>)</span><span>
</span></code></pre>
</div>
<p></p>
<table>
<thead>
<tr>
<th>adusted_rand_index</th>
<th>avg_silhouette_width</th>
</tr>
</thead>
<tbody>
<tr>
<td>0.5733587</td>
<td>0.2545221</td>
</tr>
</tbody>
</table>
<p>As mentioned before the <em>gowdis</em> function of the FD package allows the user to give different weights to each separate variable. The weights parameter can be tuned, for example by using <a target="_blank" href="http://www.math.vu.nl/~sbhulai/papers/paper-vandenhoven.pdf#page=23">random search</a>, in order to achieve better clustering results. For instance, by using the following weights for each separate variable one can improve both the <em>adjusted-rand-index</em> (external validation) and the <em>average silhouette width</em> (internal validation),<br>
</p>
<table>
<thead>
<tr>
<th>predictors</th>
<th>weights</th>
</tr>
</thead>
<tbody>
<tr>
<td>cap_shape</td>
<td>4.626</td>
</tr>
<tr>
<td>cap_surface</td>
<td>38.323</td>
</tr>
<tr>
<td>cap_color</td>
<td>55.899</td>
</tr>
<tr>
<td>bruises</td>
<td>34.028</td>
</tr>
<tr>
<td>odor</td>
<td>169.608</td>
</tr>
<tr>
<td>gill_attachment</td>
<td>6.643</td>
</tr>
<tr>
<td>gill_spacing</td>
<td>42.08</td>
</tr>
<tr>
<td>gill_size</td>
<td>57.366</td>
</tr>
<tr>
<td>gill_color</td>
<td>37.938</td>
</tr>
<tr>
<td>stalk_shape</td>
<td>33.081</td>
</tr>
<tr>
<td>stalk_root</td>
<td>65.105</td>
</tr>
<tr>
<td>stalk_surface_above_ring</td>
<td>18.718</td>
</tr>
<tr>
<td>stalk_surface_below_ring</td>
<td>76.165</td>
</tr>
<tr>
<td>stalk_color_above_ring</td>
<td>27.596</td>
</tr>
<tr>
<td>stalk_color_below_ring</td>
<td>26.238</td>
</tr>
<tr>
<td>veil_type</td>
<td>0.0</td>
</tr>
<tr>
<td>veil_color</td>
<td>1.507</td>
</tr>
<tr>
<td>ring_number</td>
<td>37.314</td>
</tr>
<tr>
<td>ring_type</td>
<td>32.685</td>
</tr>
<tr>
<td>spore_print_color</td>
<td>127.87</td>
</tr>
<tr>
<td>population</td>
<td>64.019</td>
</tr>
<tr>
<td>habitat</td>
<td>44.519</td>
</tr>
</tbody>
</table>
<div>
<pre><code><span>
</span><span>weights</span><span> </span><span>=</span><span> </span><span>c</span><span>(</span><span>4.626</span><span>,</span><span> </span><span>38.323</span><span>,</span><span> </span><span>55.899</span><span>,</span><span> </span><span>34.028</span><span>,</span><span> </span><span>169.608</span><span>,</span><span> </span><span>6.643</span><span>,</span><span> </span><span>42.08</span><span>,</span><span> </span><span>57.366</span><span>,</span><span> </span><span>37.938</span><span>,</span><span> </span><span>33.081</span><span>,</span><span> </span><span>65.105</span><span>,</span><span> </span><span>18.718</span><span>,</span><span> </span><span>76.165</span><span>,</span><span> </span><span>27.596</span><span>,</span><span> </span><span>26.238</span><span>,</span><span> </span><span>0.0</span><span>,</span><span> </span><span>1.507</span><span>,</span><span> </span><span>37.314</span><span>,</span><span> </span><span>32.685</span><span>,</span><span> </span><span>127.87</span><span>,</span><span> </span><span>64.019</span><span>,</span><span> </span><span>44.519</span><span>)</span><span>
</span><span>gwd_w</span><span> </span><span>=</span><span> </span><span>FD</span><span>::</span><span>gowdis</span><span>(</span><span>X</span><span>,</span><span> </span><span>w</span><span> </span><span>=</span><span> </span><span>weights</span><span>)</span><span> </span><span># 'gower' distance using weights
</span><span>
</span><span>gwd_mat_w</span><span> </span><span>=</span><span> </span><span>as.matrix</span><span>(</span><span>gwd_w</span><span>)</span><span> </span><span># convert the distances to a matrix
</span><span>
</span><span>cm_w</span><span> </span><span>=</span><span> </span><span>Cluster_Medoids</span><span>(</span><span>gwd_mat_w</span><span>,</span><span> </span><span>clusters</span><span> </span><span>=</span><span> </span><span>2</span><span>,</span><span> </span><span>swap_phase</span><span> </span><span>=</span><span> </span><span>TRUE</span><span>,</span><span> </span><span>verbose</span><span> </span><span>=</span><span> </span><span>F</span><span>)</span><span>
</span></code></pre>
</div>
<p></p>
<table>
<thead>
<tr>
<th>adusted_rand_index</th>
<th>avg_silhouette_width</th>
</tr>
</thead>
<tbody>
<tr>
<td>0.6197672</td>
<td>0.3000048</td>
</tr>
</tbody>
</table>
<p></p>
<p><strong>Clara_Medoids</strong><br>
</p>
<p><a target="_blank" href="https://en.wikibooks.org/wiki/Data_Mining_Algorithms_In_R/Clustering/CLARA">CLARA</a> (CLustering LARge Applications) is an obvious way to cluster larger datasets. Instead of finding medoids for the entire data set – it would be also infeasible to calculate the dissimilarity matrix – CLARA draws a small sample from the data and applies the PAM algorithm to generate an optimal set of medoids for the sample. The quality of the resulting medoids is measured by the average dissimilarity between every object in the entire data set and the medoid of its cluster.</p>
<p>The <em>Clara_Medoids</em> function in the ClusterR package follows the same logic by applying the <em>Cluster_Medoids</em> function to each selected sample. The <em>Clara_Medoids</em> takes two additional parameters, the <em>samples</em>, and the <em>sample_size</em>. The first one indicates the number of samples to draw from the data set, while the second one the fraction of the data to draw in each sample iteration (a float number between 0.0 and 1.0). I have to point out that the <em>Clara_Medoids</em> function does not take a dissimilarity matrix as input, as the <em>Cluster_Medoids</em> function does.</p>
<p>I’ll apply the <em>Clara_Medoids</em> function to the previously used <em>mushroom</em> data set by using the <em>hamming distance</em> as a dissimilarity metric and I’ll compare the computation time and output with the results of the <em>Cluster_Medoids</em> function. The <em>hamming distance</em> is appropriate for the <em>mushroom</em> data as it’s applicable to discrete variables and it’s defined as the number of attributes that take different values for two compared instances (<em>Data Mining Algorithms: Explained using R, Pawel Cichosz, 2015, page 318</em>).</p>
<div>
<pre><code><span>
</span><span>cl_X</span><span> </span><span>=</span><span> </span><span>X</span><span> </span><span># copy initial data </span><span>
</span><span># the Clara_Medoids function allows only numeric attributes
# so first convert to numeric
</span><span>
</span><span>for</span><span> </span><span>(</span><span>i</span><span> </span><span>in</span><span> </span><span>1</span><span>:</span><span>ncol</span><span>(</span><span>cl_X</span><span>))</span><span> </span><span>{</span><span> </span><span>cl_X</span><span>[,</span><span> </span><span>i</span><span>]</span><span> </span><span>=</span><span> </span><span>as.numeric</span><span>(</span><span>cl_X</span><span>[,</span><span> </span><span>i</span><span>])</span><span> </span><span>}</span><span>
</span><span>start</span><span> </span><span>=</span><span> </span><span>Sys.time</span><span>()</span><span>
</span><span>cl_f</span><span> </span><span>=</span><span> </span><span>Clara_Medoids</span><span>(</span><span>cl_X</span><span>,</span><span> </span><span>clusters</span><span> </span><span>=</span><span> </span><span>2</span><span>,</span><span> </span><span>distance_metric</span><span> </span><span>=</span><span> </span><span>'hamming'</span><span>,</span><span> </span><span>samples</span><span> </span><span>=</span><span> </span><span>5</span><span>,</span><span> </span><span>sample_size</span><span> </span><span>=</span><span> </span><span>0.2</span><span>,</span><span> </span><span>swap_phase</span><span> </span><span>=</span><span> </span><span>TRUE</span><span>,</span><span> </span><span>verbose</span><span> </span><span>=</span><span> </span><span>F</span><span>,</span><span> </span><span>threads</span><span> </span><span>=</span><span> </span><span>1</span><span>)</span><span>
</span><span>end</span><span> </span><span>=</span><span> </span><span>Sys.time</span><span>()</span><span>
</span><span>t</span><span> </span><span>=</span><span> </span><span>end</span><span> </span><span>-</span><span> </span><span>start</span><span>
</span><span>cat</span><span>(</span><span>'time to complete :'</span><span>,</span><span> </span><span>t</span><span>,</span><span> </span><span>attributes</span><span>(</span><span>t</span><span>)</span><span>$</span><span>units</span><span>,</span><span> </span><span>'\n'</span><span>)</span><span>
</span><span># time to complete : 3.104652 secs </span><span>
</span></code></pre>
</div>
<p></p>
<table>
<thead>
<tr>
<th>adusted_rand_index</th>
<th>avg_silhouette_width</th>
</tr>
</thead>
<tbody>
<tr>
<td>0.5944456</td>
<td>0.2678507</td>
</tr>
</tbody>
</table>
<p></p>
<div>
<pre><code><span>
</span><span>start</span><span> </span><span>=</span><span> </span><span>Sys.time</span><span>()</span><span>
</span><span>cl_e</span><span> </span><span>=</span><span> </span><span>Cluster_Medoids</span><span>(</span><span>cl_X</span><span>,</span><span> </span><span>clusters</span><span> </span><span>=</span><span> </span><span>2</span><span>,</span><span> </span><span>distance_metric</span><span> </span><span>=</span><span> </span><span>'hamming'</span><span>,</span><span> </span><span>swap_phase</span><span> </span><span>=</span><span> </span><span>TRUE</span><span>,</span><span> </span><span>verbose</span><span> </span><span>=</span><span> </span><span>F</span><span>,</span><span> </span><span>threads</span><span> </span><span>=</span><span> </span><span>1</span><span>)</span><span>
</span><span>end</span><span> </span><span>=</span><span> </span><span>Sys.time</span><span>()</span><span>
</span><span>t</span><span> </span><span>=</span><span> </span><span>end</span><span> </span><span>-</span><span> </span><span>start</span><span>
</span><span>cat</span><span>(</span><span>'time to complete :'</span><span>,</span><span> </span><span>t</span><span>,</span><span> </span><span>attributes</span><span>(</span><span>t</span><span>)</span><span>$</span><span>units</span><span>,</span><span> </span><span>'\n'</span><span>)</span><span>
</span><span># time to complete : 14.93423 secs </span></code></pre>
</div>
<p></p>
<table>
<thead>
<tr>
<th>adusted_rand_index</th>
<th>avg_silhouette_width</th>
</tr>
</thead>
<tbody>
<tr>
<td>0.5733587</td>
<td>0.2545221</td>
</tr>
</tbody>
</table>
<p>Using the <em>hamming</em> distance, both the <em>Clara_Medoids</em> and the <em>Cluster_Medoids</em> functions return approximately the same result (comparable also with the <em>gower</em> distance results), only that the <em>Clara_Medoids</em> function outputs more than four times faster than the <em>Cluster_Medoids</em> for this data set.</p>
<p>By using the object results of the last two code chunks one can also plot the silhouette widths using the <strong>Silhouette_Dissimilarity_Plot</strong> function. Worth mentioning here is that the dissimilarities and silhouette widths of the <em>Clara_Medoids</em> function are based on the best-selected sample and not on the entire data set, as is the case for the <em>Cluster_Medoids</em> function. </p>
<div>
<pre><code><span>
</span><span># Silhouette Plot for the &quot;Clara_Medoids&quot; object
</span><span>
</span><span>Silhouette_Dissimilarity_Plot</span><span>(</span><span>cl_f</span><span>,</span><span> </span><span>silhouette</span><span> </span><span>=</span><span> </span><span>TRUE</span><span>)</span><span>
</span></code></pre>
</div>
<p></p>
<p><img alt="Alt text" src="https://i0.wp.com/mlampros.github.io/images/Rplot_clara.png?w=456" data-recalc-dims="1"></p>
<div>
<pre><code><span>
</span><span># Silhouette Plot for the &quot;Cluster_Medoids&quot; object
</span><span>
</span><span>Silhouette_Dissimilarity_Plot</span><span>(</span><span>cl_e</span><span>,</span><span> </span><span>silhouette</span><span> </span><span>=</span><span> </span><span>TRUE</span><span>)</span><span>
</span></code></pre>
</div>
<p></p>
<p><img alt="Alt text" src="https://i2.wp.com/mlampros.github.io/images/Rplot_cluster.png?w=456" data-recalc-dims="1"></p>

<p><strong>References for the K-Medoids functions</strong></p>
<p>It took me a while to figure out how to implement the K-medoids (<em>Cluster_Medoids</em> and <em>Clara_Medoids</em>) functions, as I initially thought that the start medoids are initiallized in the same way the centroids are initiallized in the k-means algorithm. Due to the fact that I didn’t have access to the book of Kaufman and Rousseeuw (but only to the article: <em>Anja Struyf, Mia Hubert, Peter J. Rousseeuw, (Feb. 1997), Clustering in an Object-Oriented Environment, Journal of Statistical Software, Vol 1, Issue 4</em>) the <strong>cluster</strong> package was a big help as it has a very detailed package documentation. It includes both the partioning around medoids (pam) and the Clustering LARge Applications (clara) algorithms and in that way one can compare the output results.</p>
<p>In the following code chunk I’ll benchmark the <em>pam</em> function of the <em>cluster</em> package and the <em>Cluster_Medoids</em> function of the <em>ClusterR</em> package, based on the previously used vector quantization example, and I’ll compare the output medoids,</p>
<div>
<pre><code><span>
</span><span>#====================================
# pam function of the cluster package
#====================================
</span><span>
</span><span>start_pm</span><span> </span><span>=</span><span> </span><span>Sys.time</span><span>()</span><span>
</span><span>set.seed</span><span>(</span><span>1</span><span>)</span><span>
</span><span>pm_vq</span><span> </span><span>=</span><span> </span><span>cluster</span><span>::</span><span>pam</span><span>(</span><span>im2</span><span>,</span><span> </span><span>k</span><span> </span><span>=</span><span> </span><span>5</span><span>,</span><span> </span><span>metric</span><span> </span><span>=</span><span> </span><span>'euclidean'</span><span>,</span><span> </span><span>do.swap</span><span> </span><span>=</span><span> </span><span>TRUE</span><span>)</span><span>
</span><span>end_pm</span><span> </span><span>=</span><span> </span><span>Sys.time</span><span>()</span><span>
</span><span>t_pm</span><span> </span><span>=</span><span> </span><span>end_pm</span><span> </span><span>-</span><span> </span><span>start_pm</span><span>
</span><span>cat</span><span>(</span><span>'time to complete :'</span><span>,</span><span> </span><span>t_pm</span><span>,</span><span> </span><span>attributes</span><span>(</span><span>t_pm</span><span>)</span><span>$</span><span>units</span><span>,</span><span> </span><span>'\n'</span><span>)</span><span>
</span><span># time to complete : 12.05006 secs </span><span>
</span><span>pm_vq</span><span>$</span><span>medoids</span><span>
</span><span># [,1] [,2] [,3]
# [1,] 1.0000000 1.0000000 1.0000000
# [2,] 0.6325856 0.6210824 0.5758536
# [3,] 0.4480000 0.4467451 0.4191373
# [4,] 0.2884769 0.2884769 0.2806337
# [5,] 0.1058824 0.1058824 0.1058824
</span><span>
</span><span>#===========================================================================================================
# Cluster_Medoids function of the ClusterR package using 6 threads (parallelization if OpenMP is available)
#===========================================================================================================
</span><span>
</span><span>start_vq</span><span> </span><span>=</span><span> </span><span>Sys.time</span><span>()</span><span>
</span><span>set.seed</span><span>(</span><span>1</span><span>)</span><span>
</span><span>cl_vq</span><span> </span><span>=</span><span> </span><span>Cluster_Medoids</span><span>(</span><span>im2</span><span>,</span><span> </span><span>clusters</span><span> </span><span>=</span><span> </span><span>5</span><span>,</span><span> </span><span>distance_metric</span><span> </span><span>=</span><span> </span><span>'euclidean'</span><span>,</span><span> </span><span>swap_phase</span><span> </span><span>=</span><span> </span><span>TRUE</span><span>,</span><span> </span><span>verbose</span><span> </span><span>=</span><span> </span><span>F</span><span>,</span><span> </span><span>threads</span><span> </span><span>=</span><span> </span><span>6</span><span>)</span><span>
</span><span>end_vq</span><span> </span><span>=</span><span> </span><span>Sys.time</span><span>()</span><span>
</span><span>t_vq</span><span> </span><span>=</span><span> </span><span>end_vq</span><span> </span><span>-</span><span> </span><span>start_vq</span><span>
</span><span>cat</span><span>(</span><span>'time to complete :'</span><span>,</span><span> </span><span>t_vq</span><span>,</span><span> </span><span>attributes</span><span>(</span><span>t_vq</span><span>)</span><span>$</span><span>units</span><span>,</span><span> </span><span>'\n'</span><span>)</span><span>
</span><span># time to complete : 3.333658 secs
</span><span>
</span><span>cl_vq</span><span>$</span><span>medoids</span><span>
</span><span># [,1] [,2] [,3]
# [1,] 0.2884769 0.2884769 0.2806337
# [2,] 0.6325856 0.6210824 0.5758536
# [3,] 0.4480000 0.4467451 0.4191373
# [4,] 0.1058824 0.1058824 0.1058824
# [5,] 1.0000000 1.0000000 1.0000000
</span><span>
</span><span>#=======================================================================
# Cluster_Medoids function of the ClusterR package using a single thread
#=======================================================================
</span><span>
</span><span>start_vq_single</span><span> </span><span>=</span><span> </span><span>Sys.time</span><span>()</span><span>
</span><span>set.seed</span><span>(</span><span>1</span><span>)</span><span>
</span><span>cl_vq_single</span><span> </span><span>=</span><span> </span><span>Cluster_Medoids</span><span>(</span><span>im2</span><span>,</span><span> </span><span>clusters</span><span> </span><span>=</span><span> </span><span>5</span><span>,</span><span> </span><span>distance_metric</span><span> </span><span>=</span><span> </span><span>'euclidean'</span><span>,</span><span> </span><span>swap_phase</span><span> </span><span>=</span><span> </span><span>TRUE</span><span>,</span><span> </span><span>verbose</span><span> </span><span>=</span><span> </span><span>F</span><span>,</span><span> </span><span>threads</span><span> </span><span>=</span><span> </span><span>1</span><span>)</span><span>
</span><span>end_vq_single</span><span> </span><span>=</span><span> </span><span>Sys.time</span><span>()</span><span>
</span><span>t_vq_single</span><span> </span><span>=</span><span> </span><span>end_vq_single</span><span> </span><span>-</span><span> </span><span>start_vq_single</span><span>
</span><span>cat</span><span>(</span><span>'time to complete :'</span><span>,</span><span> </span><span>t_vq_single</span><span>,</span><span> </span><span>attributes</span><span>(</span><span>t_vq_single</span><span>)</span><span>$</span><span>units</span><span>,</span><span> </span><span>'\n'</span><span>)</span><span>
</span><span># time to complete : 8.693385 secs
</span><span>
</span><span>cl_vq_single</span><span>$</span><span>medoids</span><span>
</span><span># [,1] [,2] [,3]
# [1,] 0.2863456 0.2854044 0.2775613
# [2,] 1.0000000 1.0000000 1.0000000
# [3,] 0.6325856 0.6210824 0.5758536
# [4,] 0.4480000 0.4467451 0.4191373
# [5,] 0.1057339 0.1057339 0.1057339
</span><span>
</span></code></pre>
</div>
<p>For this data set (5625 observations and 3 columns) the <em>Clara_Medoids</em> function returns the same medoids almost four times faster as the <em>pam</em> function if OpenMp is available (6 threads).</p>
<p>An updated version of the <strong>ClusterR</strong> package can be found in my <a target="_blank" href="https://github.com/mlampros/ClusterR">Github repository</a> and to report bugs/issues please use the following link, <a target="_blank" href="https://github.com/mlampros/ClusterR/issues">https://github.com/mlampros/ClusterR/issues</a>.</p>
<p><div><div><div><div data-width="55" data-show-faces="false" data-send="true" data-layout="box_count" data-height="62" data-href="https://www.r-bloggers.com/clustering-using-the-clusterr-package/"></div></div><div><a data-url="https://www.r-bloggers.com/clustering-using-the-clusterr-package/" data-counturl="https://www.r-bloggers.com/clustering-using-the-clusterr-package/" data-count="vertical" data-text="Clustering using the ClusterR package" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://mlampros.github.io/mlampros.github.io/2016/09/12/clusterR_package/"> mlampros</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/?s=tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/?s=data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/?s=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/?s=ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/?s=map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/?s=animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/?s=sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/?s=LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/?s=SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/?s=git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/?s=hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/?s=Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/?s=PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/?s=time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/?s=trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/tYaCtibi6b8"></a></div>