<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/how-to-prepare-and-apply-machine-learning-to-your-dataset/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://www.r-exercises.com/2017/08/25/machine-learning-tutorial/"> 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/08/android-150996_960_720.png" target="_blank"><img sizes="(max-width: 150px) 100vw, 150px" src="https://i1.wp.com/www.r-exercises.com/wp-content/uploads/2017/08/android-150996_960_720-150x150.png?resize=150%2C150" alt="" class="wp-image-7740" data-recalc-dims="1"></a><strong>INTRODUCTION</strong></p>
<p>Dear reader,</p>
<p>If you are a newbie in the world of machine learning, then this tutorial is exactly what you need in order to introduce yourself to this exciting new part of the data science world.</p>
<p>This post includes a full machine learning project that will guide you step by step to create a “template,” which you can use later on other datasets.</p>
<p>In this step-by-step tutorial you will:</p>
<p><strong>1.</strong> Use one of the most popular machine learning packages in R.<br>
<strong>2.</strong> Explore a dataset by using statistical summaries and data visualization.<br>
<strong>3.</strong> Build 5 machine-learning models, pick the best, and build confidence that the accuracy is reliable.</p>
<p>The process of a machine learning project may not be exactly the same, but there are certain standard and necessary steps:</p>
<p><strong>1.</strong> Define Problem.<br>
<strong>2.</strong> Prepare Data.<br>
<strong>3.</strong> Evaluate Algorithms.<br>
<strong>4.</strong> Improve Results.<br>
<strong>5.</strong> Present Results.</p>
<p><strong>1. PACKAGE INSTALLATION &amp; DATA SET</strong></p>
<p>The first thing you have to do is install and load the “caret” package with:<br>
<code>install.packages(&quot;caret&quot;)<br>
library(caret)</code></p>
<p>Moreover, we need a dataset to work with. The dataset we chose in our case is “iris,” which contains 150 observations of iris flowers. There are four columns of measurements of the flowers in centimeters. The fifth column is the species of the flower observed. All observed flowers belong to one of three species. To attach it to the environment, use:<br>
<code>data(iris)</code></p>
<p><strong>1.1 Create a Validation Dataset</strong></p>
<p>First of all, we need to validate that our data set is good. Later, we will use statistical methods to estimate the accuracy of the models that we create on unseen data. To be sure about the accuracy of the best model on unseen data, we will evaluate it on actual unseen data. To do this, we will “deposit” some data that the algorithms will not find and use this data later to get a second and independent idea of how accurate the best model really is.</p>
<p>We will split the loaded dataset into two, 80% of which we will use to train our models and 20% of which we will hold back as a validation dataset. Look at the example below:<br>
#create a list of 80% of rows in the original dataset to use them for training<br>
<code>validation_index &lt;- createDataPartition(dataset$Species, p=0.80, list=FALSE)</code><br>
# select 20% of the data for validation<br>
<code>validation &lt;- dataset[-validation_index,]</code><br>
# use the remaining 80% of data to training and testing the models<br>
<code>dataset &lt;- dataset[validation_index,]</code></p>
<p>You now have training data in the dataset variable and a validation set that will be used later in the validation variable.</p>
<div>
<aside><img src="http://www.r-exercises.com/2017/08/25/machine-learning-tutorial/"></aside>
<div><strong>Learn more</strong> about machine learning in the online course <a rel="nofollow" href="http://www.r-exercises.com/product/beginner-to-advanced-guide-on-machine-learning-with-r-tool/" target="_blank">Beginner to Advanced Guide on Machine Learning with R Tool</a>. In this course you will learn how to:
<ul>
<li>Create a machine learning algorhitm from a beginner point of view</li>
<li>Quickly dive into more advanced methods in an accessible pace and with more explanations</li>
<li>And much more</li>
</ul>
<p>This course shows a complete workflow start to finish. It is a great introduction and fallback when you have some experience.
</div>
</div>
<p><strong>2. DATASET SUMMARY</strong></p>
<p>In this step, we are going to explore our data set. More specifically, we need to know certain features of our dataset, like:</p>
<p><strong>1.</strong> Dimensions of the dataset.<br>
<strong>2.</strong> Types of the attributes.<br>
<strong>3.</strong> Details of the data.<br>
<strong>4.</strong> Levels of the class attribute.<br>
<strong>5.</strong> Analysis of the instances in each class.<br>
<strong>6.</strong> Statistical summary of all attributes.</p>
<p><strong>2.1 Dimensions of Dataset</strong></p>
<p>We can see of how many instances (rows) and how many attributes (columns) the data contains with the dim function. Look at the example below:<br>
<code>dim(dataset)</code></p>
<p><strong>2.2 Types of Attributes</strong></p>
<p>Knowing the types is important as it can help you summarize the data you have and possible transformations you might need to use to prepare the data before modeilng. They could be doubles, integers, strings, factors and other types. You can find it with:<br>
<code>sapply(dataset, class)</code></p>
<p><strong>2.3 Details of the Data</strong></p>
<p>You can take a look at the first 5 rows of the data with:<br>
<code>head(dataset)</code></p>
<p><strong>2.4 Levels of the Class</strong></p>
<p>The class variable is a factor that has multiple class labels or levels. Let’s look at the levels:<br>
<code>levels(dataset$Species)</code></p>
<p>There are two types of classification problems: the multinomial like this one and the binary if there were two levels.</p>
<p><strong>2.5 Class Distribution</strong></p>
<p>Let’s now take a look at the number of instances that belong to each class. We can view this as an absolute count and as a percentage with:<br>
<code>percentage &lt;- prop.table(table(dataset$Species)) * 100<br>
cbind(freq=table(dataset$Species), percentage=percentage)</code></p>
<p><strong>2.6 Statistical Summary</strong></p>
<p>This includes the mean, the min and max values, as well as some percentiles. Look at the example below:<br>
<code>summary(dataset)</code></p>
<p><strong>3. DATASET VISUALIZATION</strong></p>
<p>We now have a basic idea about the data. We need to extend that with some visualizations, and for that reason we are going to use two types of plots:</p>
<p><strong>1.</strong> Univariate plots to understand each attribute.<br>
<strong>2.</strong> Multivariate plots to understand the relationships between attributes.</p>
<p><strong>3.1 Univariate Plots</strong></p>
<p>We can visualize just the input attributes and just the output attributes. Let’s set that up and call the input attributes x and the output attributes y.<br>
<code>x &lt;- dataset[,1:4]<br>
y &lt;- dataset[,5]</code></p>
<p>Since the input variables are numeric, we can create box and whisker plots of each one with:<br>
<code>par(mfrow=c(1,4))<br>
for(i in 1:4) {<br>
boxplot(x[,i], main=names(iris)[i])<br>
}</code></p>
<p>We can also create a barplot of the Species class variable to graphically display the class distribution.<br>
<code>plot(y)</code></p>
<p><strong>3.2 Multivariate Plots</strong></p>
<p>First, we create scatterplots of all pairs of attributes and color the points by class. Then, we can draw ellipses around them to make them more easily separated.<br>
You have to install and call the “ellipse” package to do this.<br>
<code>install.packages(&quot;ellipse&quot;)<br>
library(ellipse)<br>
featurePlot(x=x, y=y, plot=&quot;ellipse&quot;)</code></p>
<p>We can also create box and whisker plots of each input variable, but this time they are broken down into separate plots for each class.<br>
<code>featurePlot(x=x, y=y, plot=&quot;box&quot;)</code></p>
<p>Next, we can get an idea of the distribution of each attribute. We will use some probability density plots to give smooth lines for each distribution.<br>
<code>scales &lt;- list(x=list(relation=&quot;free&quot;), y=list(relation=&quot;free&quot;))<br>
featurePlot(x=x, y=y, plot=&quot;density&quot;, scales=scales)</code></p>
<p><strong>4. ALGORITHMS EVALUATION</strong></p>
<p>Now it is time to create some models of the data and estimate their accuracy on unseen data.</p>
<p><strong>1.</strong> Use the test harness to use 10-fold cross validation.<br>
<strong>2.</strong> Build 5 different models to predict species from flower measurements.<br>
<strong>3.</strong> Select the best model.</p>
<p><strong>4.1 Test Harness</strong></p>
<p>This will split our dataset into 10 parts, train in 9, test on 1, and release for all combinations of train-test splits.<br>
<code>control &lt;- trainControl(method=&quot;cv&quot;, number=10)<br>
metric &lt;- &quot;Accuracy&quot;</code></p>
<p>We are using the metric of “Accuracy” to evaluate models. This is: (number of correctly predicted instances / divided by the total number of instances in the dataset)*100 to give a percentage.</p>
<p><strong>4.2 Build Models</strong></p>
<p>We don’t know which algorithms would be good on this problem or what configurations to use. We get an idea from the plots that we created earlier.</p>
<p>Algorithms evaluation:</p>
<p><strong>1.</strong> Linear Discriminant Analysis (LDA)<br>
<strong>2.</strong> Classification and Regression Trees (CART).<br>
<strong>3.</strong> k-Nearest Neighbors (kNN).<br>
<strong>4.</strong> Support Vector Machines (SVM) with a linear kernel.<br>
<strong>5.</strong> Random Forest (RF)</p>
<p>This is a good mixture of simple linear (LDA), nonlinear (CART, kNN) and complex nonlinear methods (SVM, RF). We reset the random number seed before reach run to ensure that the evaluation of each algorithm is performed using exactly the same data splits. It ensures the results are directly comparable.</p>
<p><strong>NOTE</strong>: To proceed, first install and load the following packages: “rpart”, “kernlab”, “e1071” and “randomForest”.</p>
<p>Let’s build our five models:<br>
# a) linear algorithms<br>
<code>set.seed(7)<br>
fit.lda &lt;- train(Species~., data=dataset, method=&quot;lda&quot;, metric=metric, trControl=control)</code><br>
# b) nonlinear algorithms<br>
# CART<br>
<code>set.seed(7)<br>
fit.cart &lt;- train(Species~., data=dataset, method=&quot;rpart&quot;, metric=metric, trControl=control)</code><br>
# kNN<br>
<code>set.seed(7)<br>
fit.knn &lt;- train(Species~., data=dataset, method=&quot;knn&quot;, metric=metric, trControl=control)</code><br>
# c) advanced algorithms<br>
# SVM<br>
<code>set.seed(7)<br>
fit.svm &lt;- train(Species~., data=dataset, method=&quot;svmRadial&quot;, metric=metric, trControl=control)</code><br>
# Random Forest<br>
<code>set.seed(7)<br>
fit.rf &lt;- train(Species~., data=dataset, method=&quot;rf&quot;, metric=metric, trControl=control)</code></p>
<p><strong>4.3 Select the Best Model</strong></p>
<p>We now have 5 models and accuracy estimations for each so we have to compare them.</p>
<p>It is a good idea to create a list of the created models and use the summary function.<br>
<code>results &lt;- resamples(list(lda=fit.lda, cart=fit.cart, knn=fit.knn, svm=fit.svm, rf=fit.rf))<br>
summary(results)</code></p>
<p>Moreover, we can create a plot of the model evaluation results and compare the spread and the mean accuracy of each model. There is a population of accuracy measures for each algorithm because each algorithm was evaluated 10 times.<br>
<code>dotplot(results)</code></p>
<p>You can summarize the results for just the LDA model that seems to be the most accurate.<br>
<code>print(fit.lda)</code></p>
<p><strong>5. Make Predictions</strong></p>
<p>The LDA was the most accurate model. Now we want to get an idea of the accuracy of the model on our validation set.</p>
<p>We can run the LDA model directly on the validation set and summarize the results in a confusion matrix.<br>
<code>predictions &lt;- predict(fit.lda, validation)<br>
confusionMatrix(predictions, validation$Species)</code></p>
<div>
<h3>Related exercise sets:</h3>
<ol>
<li><a rel="nofollow" href="http://www.r-exercises.com/2015/10/09/vector-exercises/" title="Vector exercises" target="_blank">Vector exercises </a></li>
<li><a rel="nofollow" href="http://www.r-exercises.com/2017/05/31/evaluate-your-model-with-r-exercises/" title="Evaluate your model with R Exercises" target="_blank">Evaluate your model with R Exercises </a></li>
<li><a rel="nofollow" href="http://www.r-exercises.com/2017/06/15/neural-networks-exercises-part-2/" title="Neural networks Exercises (Part-2)" target="_blank">Neural networks Exercises (Part-2) </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/08/25/machine-learning-tutorial/"> 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/htc67R2mNa0" height="1"></a></div>