<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/parallel-computing-exercises-snowfall-part-1/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://www.r-exercises.com/2017/07/06/parallel-computing-exercises-snowfall-part-1/?utm_source=rss&utm_medium=rss&utm_campaign=parallel-computing-exercises-snowfall-part-1"> R-exercises</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p><a rel="nofollow" href="https://i0.wp.com/www.r-exercises.com/wp-content/uploads/2017/06/4624380615_14326f22c4_b_384.jpg" target="_blank"><img sizes="(max-width: 300px) 100vw, 300px" src="https://i2.wp.com/www.r-exercises.com/wp-content/uploads/2017/06/4624380615_14326f22c4_b_384-300x181.jpg?resize=300%2C181" alt="" class="wp-image-6824" data-recalc-dims="1"></a><br>
R has a lot of tools to speed up computations making use of multiple CPU cores either on one computer, or on multiple machines. This series of exercises aims to introduce the basic techniques for implementing parallel computations using multiple CPU cores on one machine.<br>
The initial step in preparation for parallelizing computations is to decide whether the task can and should be run in parallel. Some tasks involve sequential computation, where operations in one round depend on the results of the previous round. Such computations cannot be parallelized. The next question is whether it is worth to use parallel computations. On the one hand, running tasks in parallel may reduce computer time spent on calculations. On the other hand, it requires additional time to write the code that can be run in parallel, and check whether it yields correct results.<br>
The code that implements parallel computations basically makes three things:</p>
<ul>
<li>splits the task into pieces,</li>
<li>runs them in parallel, and</li>
<li>combines the results.</li>
</ul>
<p>This set of exercises allows to train in using the <code>snowfall</code> package to perform parallel computations. The set is based on the example of parallelizing the k-means algorithm, which splits data into clusters (i.e. splits data points into groups based on their similarity). The standard k-means algorithm is sensitive to the choice of initial points. So it is advisable to run the algorithm multiple times, with different initial points to get the best result. It is assumed that your computer has two or more CPU cores.<br>
The data for the exercises can be downloaded <a rel="nofollow" href="http://www.r-exercises.com/wp-content/uploads/2017/06/data_snowfall.csv" target="_blank">here</a>.<br>
For other parts of the series follow the tag <a rel="nofollow" href="http://www.r-exercises.com/tags/parallel-computing" target="_blank">parallel computing</a>.<br>
Answers to the exercises are available <a rel="nofollow" href="http://r-exercises.com/2017/07/06/parallel-computing-exercises-snowfall-part-1-solutions" target="_blank">here</a>.</p>
<p><strong>Exercise 1</strong><br>
Use the <code>detectCores</code> function from the <code>parallel</code> package to find the number of physical CPU cores on your computer. Then change the arguments of the function to find the number of logical CPU cores.</p>
<p><strong>Exercise 2</strong><br>
Load the data set, and assign it to the <code>df</code> variable.</p>
<p><strong>Exercise 3</strong><br>
Use the <code>system.time</code> function to measure the time spent on execution of the command <code>fit_30 &lt;- kmeans(df, centers = 3, nstart = 30)</code>, which finds three clusters in the data.<br>
Note that this command runs the kmeans function 30 times sequentially with different (randomly chosen) initial points, and then selects the ‘best’ way of clustering (the one that minimizes the squared sum of distances between each data point and its cluster center).</p>
<div>
<aside><img src="http://www.r-exercises.com/2017/07/06/parallel-computing-exercises-snowfall-part-1/?utm_source=rss&utm_medium=rss&utm_campaign=parallel-computing-exercises-snowfall-part-1"></aside>
<div><strong>Learn more</strong> about optimizing your workflow in the online course <a rel="nofollow" href="http://www.r-exercises.com/product/getting-started-with-r-for-data-science/" target="_blank">Getting Started with R for Data Science</a>. In this course you will learn how to:
<ul>
<li>efficiently organize your workflow to get the best performance of your entire project</li>
<li>get a full introduction to using R for a data science project</li>
<li>And much more</li>
</ul>
</div>
</div>
<p><strong>Exercise 4</strong><br>
Now we’ll try to paralellize the runs of kmeans. The first step is to write the code that performs a single run of the <code>kmeans</code> function. The code has to do the following:</p>
<ol>
<li>Randomly choose three rows in the data set (this can be done using the <code>sample</code> function).</li>
<li>Subset the data set keeping only the chosen rows (they will be used as initial points in the k-means algorithm).</li>
<li>Transform the obtained subset into a matrix.</li>
<li>Run the <code>kmeans</code> function using the original data set, the obtained matrix (as the <code>centers</code> argument), and without the <code>nstart</code> argument.</li>
</ol>
<p><strong>Exercise 5</strong><br>
The second step is to wrap the code written in the previous exercise into a function. It should take one argument, which is not used (see explanation on the solutions page), and should return the output of the <code>kmeans</code> function.<br>
Such functions are often labelled as <code>wrapper</code>, but they may have any possible name.</p>
<p><strong>Exercise 6</strong><br>
Let’s prepare for parallel execution of the function:</p>
<ol>
<li>Initialize a cluster for parallel computations using the <code>sfInit</code> function from the <code>snowfall</code> package. Set the <code>parallel</code> argument equal to <code>TRUE</code>. If your machine has two logical CPU’s assign two to the <code>cpus</code> argument; if the number of CPU’s exceeds two set this argument equal to the number of logical CPU’s on your machine minus one.</li>
<li>Make the data set available for parallel processes with the <code>sfExport</code> function.</li>
<li>Prepare the random number generation for parallel execution using the <code>sfClusterSetupRNG</code>. Set the <code>seed</code> argument equal to 1234.</li>
</ol>
<p>(Note that <code>kmeans</code> is a function from the base R packages. If your want to run in parallel a function from a downloaded package, you have also to make it available for parallel execution with the <code>sfLibrary</code> function).</p>
<p><strong>Exercise 7</strong><br>
Use the <code>sfLapply</code> function from the <code>snowfall</code> package to run the wrapper function (written in Exercise 5) 30 times in parallel, and store the output of <code>sfLapply</code> in the <code>result</code> variable. Apply also the <code>system.time</code> function to measure the time spent on execution of <code>sfLapply</code>.<br>
Note that <code>sfLapply</code> is a parallel version of <code>lapply</code> function. It takes two main arguments: (1) a vector or a list (in this case it should be a numeric vector of length 30), and (2) the function to be applied to each element of the vector or list.</p>
<p><strong>Exercise 8</strong><br>
Stop the cluster for parallel execution with the <code>sfStop</code> function from the <code>snowfall</code> package.</p>
<p><strong>Exercise 9</strong><br>
Explore the output of <code>sfLapply</code> (the <code>result</code> object):</p>
<ol>
<li>Find out to what class it belongs.</li>
<li>Print its length.</li>
<li>Print the structure of its first element.</li>
<li>Find the value of the <code>tot.withinss</code> sub-element in the first element (it represents the total squared sum of distances between data points and their cluster centers in a given solution to the clustering problem). Print that value.</li>
</ol>
<p><strong>Exercise 10</strong><br>
Find an element of the <code>result</code> object with the lowest <code>tot.withinss</code> value (there may be multiple such elements), and assign it to the <code>best_result</code> variable.<br>
Compare the <code>tot.withinss</code> value of that variable with the corresponding value of the <code>fit_30</code> variable, which was obtained in Exercise 3.</p>
<div>
<h3>Related exercise sets:</h3>
<ol>
<li><a rel="nofollow" href="http://www.r-exercises.com/2017/05/07/shiny-application-layouts-exercises-part-5/" title="Shiny Application Layouts Exercises (Part-5)" target="_blank">Shiny Application Layouts Exercises (Part-5) </a></li>
<li><a rel="nofollow" href="http://www.r-exercises.com/2017/01/10/getting-started-with-plotly-basic-plots/" title="Getting started with Plotly: basic Plots" target="_blank">Getting started with Plotly: basic Plots </a></li>
<li><a rel="nofollow" href="http://www.r-exercises.com/2017/06/10/density-based-clustering-exercises/" title="Density-Based Clustering Exercises" target="_blank">Density-Based Clustering Exercises </a></li>
<li><a rel="nofollow" href="http://www.r-exercises.com/start-here-to-learn-r/" target="_blank">Explore all our (>1000) R exercises</a></li>
<li><a rel="nofollow" href="http://www.r-exercises.com/r-courses/" target="_blank">Find an R course using our R Course Finder</a> directory</li>
</ol>
</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://www.r-exercises.com/2017/07/06/parallel-computing-exercises-snowfall-part-1/?utm_source=rss&utm_medium=rss&utm_campaign=parallel-computing-exercises-snowfall-part-1"> R-exercises</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/5veoYG85JEc" height="1"></a></div>