<div><div><div><div data-width="55" data-show-faces="false" data-send="true" data-layout="box_count" data-height="62" data-href="http://www.r-bloggers.com/what-are-the-best-machine-learning-packages-in-r/"></div></div><div><a data-url="http://www.r-bloggers.com/what-are-the-best-machine-learning-packages-in-r/" data-counturl="http://www.r-bloggers.com/what-are-the-best-machine-learning-packages-in-r/" data-count="vertical" data-text="What are the Best Machine Learning Packages in R?" target="_blank" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<p><em>Guest post by <strong><span>Khushbu Shah</span> </strong></em></p>
<p>The most common question asked by prospective data scientists is – “What is the best programming language for Machine Learning?” The answer to this question always results in a debate whether to choose R, Python or MATLAB for Machine Learning. Nobody can, in reality, answer the question as to whether Python or R is best language for Machine Learning. However, the programming language one should choose for machine learning directly depends on the requirements of a given data problem, the likes and preferences of the data scientist and the context of machine learning activities they want to perform. According to a survey on Kaggler’s Favourite Tools, the open source R programming language turned out to be the favourite among 543 Kagglers of the 1714 Kaggler’s listing their data science tools.</p>
<p>R is the preeminent choice among data professionals who want to understand and explore data, using statistical methods and graphs. It has several machine learning packages and advanced implementations for the top machine learning algorithms – which every data scientist must be familiar with, to explore, model and prototype the given data. R is an open source language to which people have contributed, from around the world. Starting from data collection and cleaning to reproducible research – you will find a Black Box written by someone else, which you can directly use in your program. This Black Box is known as Package in R. A Package in R is nothing but collection of pre-written codes which can be reused.</p>
<p>As per CRAN there are around 8,341 packages that are currently available.  Apart from CRAN, there are other repositories which contribute multiple packages. The simple straightforward syntax to install any of these machine learning packages is: <code>install.packages (“Name_Of_R_Package”)</code>.</p>
<p>Few basic packages without which your life as a data scientist, will be tough include <code>dplyr</code>, <code>ggplot2</code>, <code>reshape2</code> etc. In this article we will be more focused on packages used in the field of Machine Learning.</p>
<h3>Enrol now for a hands-on project based <a target="_blank" href="https://www.dezyre.com/data-science-in-R-programming-online-training/37?couponCode=114098108111103103101114">Data Science in R Programming Course</a></h3>
<ol>
<li>
<h3><strong><code>MICE</code> Package – Takes care of your Missing Values</strong></h3>
<p>If missing values are something which haunts you then <code>MICE</code> package is the real friend of yours.</p>
<p>When we face an issue of missing values we generally go ahead with basic imputations such as replacing with 0, replacing with mean, replacing with mode etc. but each of these methods are not versatile and could result into a possible data discrepancy.</p>
<p><code>MICE</code> package helps you to impute missing values by using multiple techniques, depending on the kind of data you are working with.</p>
<p>Let’s take an example on using <code>MICE</code> Package.</p>
<pre>    dataset &lt;- data.frame(var1=rnorm(20,0,1), var2=rnorm(20,5,1))
    dataset &lt;- NA
    dataset &lt;- NA
    summary(dataset)</pre>
<p><a target="_blank" href="http://i2.wp.com/www.r-bloggers.com/wp-content/uploads/2016/06/Image-1.jpg"><img alt="Image 1" class="wp-image-122928" src="http://i2.wp.com/www.r-bloggers.com/wp-content/uploads/2016/06/Image-1.jpg?resize=450%2C128" data-recalc-dims="1"></a></p>
<p>Till now we have created a random dataframe and introduced few missing values in the data intentionally. Now it’s time to see <code>MICE</code> at work and forget the worry</p>
<pre>    install.pckages(“mice”)
    require(mice)
    dataset2 &lt;- mice(dataset)
    dataset2&lt;-complete(dataset2)
    summary(dataset2)</pre>
<p><a target="_blank" href="http://i0.wp.com/www.r-bloggers.com/wp-content/uploads/2016/06/Image-3.jpg"><img alt="Image 3" class="wp-image-122930" src="http://i0.wp.com/www.r-bloggers.com/wp-content/uploads/2016/06/Image-3.jpg?resize=450%2C82" data-recalc-dims="1"></a></p>
<p>We have used the default parameters of <code>MICE</code> package for the example, but you can read and change the parameters as per your requirements.
<li>
<h3><strong><code>rpart</code> package: Lets partition your data</strong></h3>
<p>(<code>rpart</code>) package in R language, is used to build classification or regression models using a two stage procedure and the resultant models is represented in the form of binary trees. The basic way to plot any regression or classification tree using the <code>rpart</code> package is to call the <code>plot()</code> function. The results might not be pretty by just using the basic <code>plot()</code> function, so there is an alternative i.e. the <code>prp()</code> function which is powerful and flexible. <code>prp()</code> function in <code>rpart.plot</code> package is often referred to as the authentic Swiss army knife for plotting regression trees.</p>
<p><code>rpart()</code> function helps establish a relationship between a dependant and independent variables so that a business can understand the variance in the dependant variables based on the independent variables. For instance, if an eLearning company has to find out how their sales (dependant variables) have been impacted due to promotions on Social Media, WOM, Newspapers, Referral Sites, etc. then <code>rpart</code> package has several functions that can help with this analysis phenomenon.</p>
<p>rpart stands for Recursive Partitioning and Regression Trees. Using rpart you can run Regression as well as classification. If we talk about syntax, it is pretty simple-</p>
<p><var>rpart(formula, data=, method=,control=)</var></p>
<ul>
<li>where formula contains the combination of dependent &amp; independent variables; data is the name of your dataset, method depends on the objective i.e. for classification tree, it will be<strong>class</strong>; and control is specific to your requirement for example, we want a minimum number variable to split a node etc.</li>
</ul>
<p>Let’s consider <code>iris</code> dataset, which looks like –</p>
<p><a target="_blank" href="http://i1.wp.com/www.r-bloggers.com/wp-content/uploads/2016/06/Image-4.jpg"><img alt="Image 4" class="wp-image-122931" src="http://i1.wp.com/www.r-bloggers.com/wp-content/uploads/2016/06/Image-4.jpg?resize=450%2C295" data-recalc-dims="1"></a></p>
<p>Assuming our objective is to predict Species using a decision tree, it can be achieved by a simple line of code</p>
<pre>    rpart_tree &lt;- rpart(formula = Species~., data=iris, method = ‘class’)
    summary(rpart_tree)
    plot(rpart_tree)
</pre>
<p>Let see how does our built tree look like:</p>
<pre><a target="_blank" href="http://i2.wp.com/www.r-bloggers.com/wp-content/uploads/2016/06/Image-6.jpg"><img alt="Image 6" class="wp-image-122933" src="http://i2.wp.com/www.r-bloggers.com/wp-content/uploads/2016/06/Image-6.jpg?resize=450%2C116" data-recalc-dims="1"></a>



</pre>
<p>Here you can see the splits of different nodes and predicted class.</p>
<p>To predict for a new dataset, you have simple function <var>predict(tree_name,new_data)</var> which will give you the predicted classes.
<li>
<h3><strong><code>PARTY</code>: Let’s again partition your data</strong></h3>
<p>PARTY package in R is used for recursive partitioning and this package reflects the continuous development of ensemble methods.</p>
<p><code>PARTY</code> is yet another package to build decision trees based on Conditional Inference algorithm. <code>ctree()</code> is the main function of <code>PARTY</code> package which is used extensively, which reduces the training time and bias.</p>
<p>Similar to other predictive analytics functions in R, <code>PARTY</code> also has similar syntax i.e.</p>
<dl>
<dt><var>ctree(formula,data)</var></dt>
<dd>which will build your decision tree, taking the default values of various arguments into consideration which can be tweaked based on requirements.</dd>
</dl>
<p>Let’s build a tree using the same example discussed above.</p>
<pre>    party_tree &lt;- ctree(formula=Species~. , data = iris)
    plot(party_tree)
</pre>
<p>Let see how does the built tree looks like –</p>
<p><a target="_blank" href="http://i1.wp.com/www.r-bloggers.com/wp-content/uploads/2016/06/Image-8.jpg"><img alt="Image 8" class="wp-image-122935" src="http://i1.wp.com/www.r-bloggers.com/wp-content/uploads/2016/06/Image-8.jpg?resize=450%2C249" data-recalc-dims="1"></a></p>
<p>In this package also you have a predict function which will be used to predict classes for the new data coming in.
<li>
<h3><strong><code>CARET</code>: Classification And REgression Training</strong></h3>
<p>Classification and REgression Training (<code>CARET</code>) package is developed with the intent to combine model training and prediction. Data scientists can run several different algorithms for a given business problem using the <code>CARET</code> package. Data scientists might not be aware as to which is the best algorithm for a given problem. <code>CARET</code> package helps investigate the optimal parameters for an algorithm with controlled experiments. The grid search method of the <code>caret</code> R package searches parameters by combining various methods to estimate the performance of a given model. After looking at all the trial combinations, the grid search method finds the combination that gives best results.</p>
<p>Data scientists can streamline the prices of building predictive models with the help of specialized inbuilt functions for data splitting, feature selection, data pre-processing, variable importance estimation, model tuning through resampling and model visualizations.</p>
<p><code>CARET</code> package is one of the best packages in R. The developers of this package understood that it is hard to know about the best suited algorithm for the given problem case. There can be situations where you are using a particular model and doubting your data but the problem lies in the algorithm you have chosen.</p>
<p>After installing <code>CARET</code> package, you can run <var>names(getModelInfo())</var> and see that there are 217 possible methods which can be run through a single package.</p>
<p>To build any predictive model, <code>CARET</code> uses <strong><code>train()</code></strong> function; The syntax of train function looks like –</p>
<p><var>train(formula, data, method)</var></p>
<p>Where method is the predictive model you are trying to build. Let’s use the iris dataset and fit a linear regression model to predict <code>Sepal.Length</code></p>
<pre>    Lm_model &lt;- train(Sepal.Length~Sepal.Width + Petal.Length + Petal.Width, data=iris, method = “lm”)
    summary(lm_model)
</pre>
<p><code><a target="_blank" href="http://i1.wp.com/www.r-bloggers.com/wp-content/uploads/2016/06/Image-10.jpg"><img alt="Image 10" class="wp-image-122937" src="http://i1.wp.com/www.r-bloggers.com/wp-content/uploads/2016/06/Image-10.jpg?resize=450%2C242" data-recalc-dims="1"></a>
<p>CARET package is just not for building models but it also takes care of splitting your data into test and train, do transformation etc.</p>
<p>In short, this is the GoTo package in R – for your all Predictive Modeling related needs.
<li>
<h3><strong><code>randomForest</code>: Let’s combine multiple trees to build our own forest</strong></h3>
<p>Random Forest algorithm is one of the most widely used algorithms when it comes to Machine Learning. R package randomForest is used to create large number of decision trees and then each observation is inputted into the decision tree. The common output obtained for maximum of the observations is considered as the final output. When using randomForest algorithm, data scientists/analysts have to ensure that the variables must be numeric or factors. Factors cannot have more than 32 levels when implementing randomForest.</p>
<p>As you must be aware that Random Forest takes random samples of variables as well as observations and build multiple trees. These multiple trees are then combined at the end &amp; votes are taken to finally predict the class of the response variable.</p>
<p>Let’s use the iris data example to build a Random Forest using randomForest package.</p>
<p><var>Rf_fit&lt;-randomForest(formula=Species~., data=iris)</var></p>
<p>You run a line similar to other packages and your Random Forest is ready to be used. Let see how does this built Forest performs.</p>
<pre>    print(Rf_fit)
    importance(Rf_fit)
</pre>
<p><a target="_blank" href="http://i0.wp.com/www.r-bloggers.com/wp-content/uploads/2016/06/Image-11.jpg"><img alt="Image 11" class="wp-image-122938" src="http://i0.wp.com/www.r-bloggers.com/wp-content/uploads/2016/06/Image-11.jpg?resize=450%2C225" data-recalc-dims="1"></a></p>
<p>You might need to play with different control parameters in randomForest e.g., Number of variables in each tree, No. of trees you want to build etc. Generally, data scientists run multiple iterations and select the best combination.
<li>
<h3><strong><code>nnet</code>: It’s all about hidden layers</strong></h3>
<p>This is the most widely used and easy to understand neural network package, but it is limited to a single layer of nodes. However, several studies have shown that more nodes are not required as they do not contribute in enhancing the performance of the model but rather increase the calculation time and complexity of the model.</p>
<p>This package does not provide any specific set of methods for finding the number of nodes in the hidden layer. So, when big data professionals implement nnet it is always suggested that they set it to a value that lies between the number of input and output nodes. nnet packages provides implementation for Artificial Neural Networks algorithm which works – based on the understanding of how a human brain functions, given the input and output signals. ANNs find great applications in forecasting for airlines. In fact, neural network structures provide better forecasts using the nnet functions than the traditional forecasting methods like exponential smoothing, regression, etc.</p>
<p>R has multiple packages for building neural networks e.g, <code>nnet</code>, <code>neuralnet</code>, <code>RSNNS</code>. Let’s use our <code>iris</code> data example again (I know you are bored of <code>iris</code>). Let’s try to predict Species using the <code>nnet</code> now and see how does it look –</p>
<p><var>nnet_model &lt;- nnet(Species~., data=iris, size = 10)</var></p>
<p><a target="_blank" href="http://i0.wp.com/www.r-bloggers.com/wp-content/uploads/2016/06/Image-12.jpg"><img alt="Image 12" class="wp-image-122939" src="http://i0.wp.com/www.r-bloggers.com/wp-content/uploads/2016/06/Image-12.jpg?resize=450%2C249" data-recalc-dims="1"></a></p>
<p>You can observe 10 hidden layers in the Neural Network output – this is because we gave <var>size=10</var> while building the Neural Net.</p>
<p>Unfortunately, there is no direct way to plot the built neural networks but there are plenty of custom functions contributed on GitHub which you can use.</p>
<p>To build the above shown network we have used – <a target="_blank" href="https://gist.githubusercontent.com/fawda123/7471137/raw/466c1474d0a505ff044412703516c34f1a4684a5/nnet_plot_update.r">https://gist.githubusercontent.com/fawda123/7471137/raw/466c1474d0a505ff044412703516c34f1a4684a5/nnet_plot_update.r</a>
<li>
<h3><strong><code>e1071</code>: Let the vectors support your model</strong></h3>
<p>Wondering if this of junk value? Not at all! This is a very vital package in R language that has specialized functions for implementing Naïve Bayes (conditional probability), SVM, Fourier Transforms, Bagged Clustering, Fuzzy Clustering, etc. In fact, the first R interface for SVM implementation was in <code>e1071</code> R package – for instance, if a data scientist is trying to find out what is the probability that a person who buys an iPhone 6S also buys an iPhone 6S Case.</p>
<p>This kind of analysis is based on conditional probability, so data scientists can make use of <code>e1071</code> R package which has specialized functions for implementing Naive Bayes Classifier.</p>
<p>Support Vector Machines are there to rescue you when you have a dataset which is not separable in the given dimensions and you need to promote your data to higher dimensions in order to classify or regress it.</p>
<p>Support Vector Machine a.k.a SVM uses Kernel Functions (To optimize mathematical operations) and maximize the margin between two classes.</p>
<p>Similar to other functions discussed above, syntax for SVM is also similar:</p>
<p><var>svm_model &lt;- svm(Species ~Sepal.Length + Sepal.Width, data=iris)</var></p>
<p>In order to visualize the classified SVM, we need to use <code>plot()</code> function with the data also</p>
<p><var>plot(svm_model, data = iris[,c(1,2,5)])</var></p>
<p><a target="_blank" href="http://i1.wp.com/www.r-bloggers.com/wp-content/uploads/2016/06/Image-13.jpg"><img alt="Image 13" class="wp-image-122940" src="http://i1.wp.com/www.r-bloggers.com/wp-content/uploads/2016/06/Image-13.jpg?resize=450%2C249" data-recalc-dims="1"></a></p>
<p>In the plot shown above, we can clearly see the decision boundaries which were received after applying SVM on iris data.</p>
<p>There are multiple parameters which you would have to change in order to get the best accuracy e.g, kernel, cost, gamma, coefficients etc.</p>
<p>To get a bet classifier using SVM you will have to experiment with many of these factors, for example kernel can take multiple values like – linear, Gaussian, Cosine etc.
<li>
<h3><strong><code>kernLab</code>: kernel trick packaged well</strong></h3>
<p><code>Kernlab</code> takes advantage of the S4 object model in R language, so that data scientists can use kernel based machine learning algorithms. <code>Kernlab</code> has implementations for SVM, kernel feature analysis, dot product primitives, ranking algorithm, Gaussian processes and a spectral clustering algorithm. Kernel based machine learning methods are used when it is challenging to solve clustering, classification and regression problems – in the space in which the observations are made.</p>
<p><code>Kernlab</code> package is widely used in the implementation of SVM which eases pattern recognition to a great extent. It has various kernel functions like – tanhdot (hyperbolic tangent kernel Function), polydot (polynomial kernel function), laplacedot (laplacian kernel function) and many more to perform pattern recognition.</p>
<p>Till now you might have understood the power of Kernel functions used in SVM. If Kernel functions are not there, then SVM is not possible altogether.</p>
<p>SVM is not the only technique which uses Kernel Trick but there are plenty of other kernel based algorithms which are quite popular and useful, e.g., RVM, Kernel based PCA, Dimensionality reduction etc.</p>
<p><code>kernLab</code> package is a house to ~20 of such algorithms which work on the power of Kernels.</p>
<p><code>kernLab</code> has its own predefined kernels but user has flexibility to build and use their own kernel functions.</p>
<p>Let’s initialize our own Radial Basis Function with a sigma value of 0.01</p>
<pre>    Myrbf &lt;- rbfdot(sigma = 0.01)
    Myrbf   
</pre>
<p>If you want to see the class of <strong><code>Myrbf</code></strong>, you can do it by simply running <code>class()</code> function over the created object</p>
<pre><a target="_blank" href="http://i0.wp.com/www.r-bloggers.com/wp-content/uploads/2016/06/Image-14.jpg"><img alt="Image 14" class="wp-image-122941" src="http://i0.wp.com/www.r-bloggers.com/wp-content/uploads/2016/06/Image-14.jpg?resize=450%2C58" data-recalc-dims="1"></a>


<a target="_blank" href="http://i1.wp.com/www.r-bloggers.com/wp-content/uploads/2016/06/Image-15.jpg"><img alt="Image 15" class="wp-image-122942" src="http://i1.wp.com/www.r-bloggers.com/wp-content/uploads/2016/06/Image-15.jpg?resize=450%2C43" data-recalc-dims="1"></a>
</pre>
<p>Every kernel object accepts two vectors and returns dot product of them. Let’s create two vectors and see their dot products –</p>
<pre>    x&lt;-rnorm(10)
    y&lt;-rnorm(10)
    Myrbf(x,y)

<img alt="Image 16" class="wp-image-122943" src="http://i2.wp.com/www.r-bloggers.com/wp-content/uploads/2016/06/Image-16.jpg?resize=450%2C56" data-recalc-dims="1">
</pre>
<p>Here we created two random normal variables x &amp; y with 10 values each and computed their dot product using <strong><code>Myrbf kernel</code></strong>.</p>
<p>Let’s see an example of SVM using <strong><code>Myrbf kernel</code></strong></p>
<p>We’ll be using iris data again to understand the working of SVM using <code>kernLab</code> –</p>
<pre>    Kernlab_svm &lt;- ksvm(Species ~ Sepal.Length + Sepal.Width, data = iris, kernel = Myrbf, C=4)
    Kernlab_svm    
</pre>
<p><a target="_blank" href="http://i0.wp.com/www.r-bloggers.com/wp-content/uploads/2016/06/Image-17.jpg"><img alt="Image 17" class="wp-image-122944" src="http://i0.wp.com/www.r-bloggers.com/wp-content/uploads/2016/06/Image-17.jpg?resize=450%2C154" data-recalc-dims="1"></a></p>
<p>Let’s use the built Support Vector Machine and see how did it predicted:</p>
<pre>    predited&lt;-predict(Kernlab_svm,iris)
    table(predicted = predicted, true = iris$Species)
<a target="_blank" href="http://i1.wp.com/www.r-bloggers.com/wp-content/uploads/2016/06/Image-18.jpg"><img alt="Image 18" class="wp-image-122945" src="http://i1.wp.com/www.r-bloggers.com/wp-content/uploads/2016/06/Image-18.jpg?resize=450%2C77" data-recalc-dims="1"></a>


</pre>
</li>

<h3>Closing Note:</h3>
<p>Every package or function in R has some default values associated with it, before applying any algorithm you must know about the various options available. Passing default values will throw you some result but you can’t be sure that the output is the most optimized or accurate one.</p>
<p>There are many other machine learning packages available in the CRAN repository like <code>igraph, glmnet</code>, <code>gbm</code>, <code>tree</code>, <code>CORElearn</code>, <code>mboost</code>, etc. which are used in different industries to build performance efficient models. We have observed the scenarios where changing just one parameter can modify the output completely. So, don’t rely on default values of parameters – Understand your data and requirements before applying any algorithm.</p>
<h3>Enrol now for a hands-on project based <a target="_blank" href="https://www.dezyre.com/data-science-in-R-programming-online-training/37?couponCode=114098108111103103101114">Data Science in R Programming Course
<p></a>
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/cLjpBA_f7BU"></h3></code></ol>