{"id":3430,"date":"2017-04-10T18:16:01","date_gmt":"2017-04-10T17:16:01","guid":{"rendered":"http:\/\/www.blopig.com\/blog\/?p=3430"},"modified":"2017-04-11T16:23:12","modified_gmt":"2017-04-11T15:23:12","slug":"a-very-basic-introduction-to-random-forests-using-r","status":"publish","type":"post","link":"https:\/\/www.blopig.com\/blog\/2017\/04\/a-very-basic-introduction-to-random-forests-using-r\/","title":{"rendered":"A very basic introduction to Random Forests using R"},"content":{"rendered":"<p>Random Forests is a powerful tool used extensively across a multitude of fields. As a matter of fact, it is hard to come upon a data scientist that never had to resort to this technique at some point. Motivated by the fact that I have been using Random Forests quite a lot recently, I decided to give a quick intro to Random Forests using R.<\/p>\n<p><strong>So what are Random Forests? \u00a0<\/strong>Well, I am probably not the most suited person to answer this question (<a href=\"https:\/\/www.google.co.uk\/#q=what+is+random+forests\">a google search will reveal much more interesting answers<\/a>) , still I shall give it a go. Random Forests is a learning method for classification (and others applications &#8212; see below). It\u00a0is based on generating a large number of decision trees, each constructed using a different subset of your training set. These subsets are usually selected by sampling at random and with replacement from the original data set. The decision trees are then used to identify a classification consensus by selecting the\u00a0most common\u00a0output (mode). While random forests can be used for other applications (i.e. regression), for the sake of keeping this post short, I shall focus solely on classification.<\/p>\n<p><strong>Why R?<\/strong> Well, the quick and easy question for this is that I do all my plotting in R (mostly because I think <a href=\"http:\/\/ggplot2.org\/\">ggplot2<\/a> looks very pretty). I decided to explore Random Forests in R and to assess what are its advantages and shortcomings. I am planning to compare Random Forests in R against the python implementation in <a href=\"http:\/\/scikit-learn.org\/stable\/\">scikit-learn<\/a>. Do expect a post about this in the near future!<\/p>\n<p><strong>The data:\u00a0<\/strong>to keep things simple, I decided to use the\u00a0Edgar Anderson&#8217;s Iris Data set. You can have a look at it by inspecting the contents of\u00a0<em>iris\u00a0<\/em>in R. This data set contains observations for four features (sepal length and width, and petal length and width &#8211; all in cm) of 150 flowers, equally split between three different iris species. This data set is fairly canon in classification and data analysis. Let us take a look at it, shall we:<\/p>\n<p style=\"text-align: center\"><a href=\"https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/04\/Blogpost1.png?ssl=1\"><img data-recalc-dims=\"1\" decoding=\"async\" loading=\"lazy\" class=\"aligncenter wp-image-3431 size-large\" src=\"https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/04\/Blogpost1.png?resize=625%2C625&#038;ssl=1\" alt=\"\" width=\"625\" height=\"625\" srcset=\"https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/04\/Blogpost1.png?resize=1024%2C1024&amp;ssl=1 1024w, https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/04\/Blogpost1.png?resize=150%2C150&amp;ssl=1 150w, https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/04\/Blogpost1.png?resize=300%2C300&amp;ssl=1 300w, https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/04\/Blogpost1.png?resize=768%2C768&amp;ssl=1 768w, https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/04\/Blogpost1.png?resize=624%2C624&amp;ssl=1 624w, https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/04\/Blogpost1.png?w=1600&amp;ssl=1 1600w, https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/04\/Blogpost1.png?w=1250&amp;ssl=1 1250w\" sizes=\"auto, (max-width: 625px) 100vw, 625px\" \/><\/a><\/p>\n<p style=\"text-align: left\">As you can observe, there seems to be some\u00a0separation in regards to the different features and our three species\u00a0of irises [note: this set is not very representative of a real world data set and results should be taken with a grain of salt].<\/p>\n<p><strong>Training and Validation sets:\u00a0<\/strong>great care needs to be taken to ensure clear separation between training and validation sets. I tend to\u00a0save the cases for which I am actually interested in performing predictions as a second validation set (Validation 2). Then I split the remaining data evenly into Training and Validation 1.<\/p>\n<p>Let us split our data set then, shall we?<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"r\"># Set random seed to make results reproducible:\r\nset.seed(17)\r\n# Calculate the size of each of the data sets:\r\ndata_set_size &lt;- floor(nrow(iris)\/2)\r\n# Generate a random sample of \"data_set_size\" indexes\r\nindexes &lt;- sample(1:nrow(iris), size = data_set_size)\r\n\r\n# Assign the data to the correct sets\r\ntraining &lt;- iris[indexes,]\r\nvalidation1 &lt;- iris[-indexes,]\r\n\r\n<\/pre>\n<p>Before we can move on, here are some things to consider:<\/p>\n<p>1- The size of your data set usually imposes a hard limit on how many features you can consider. This occurs due to the <a href=\"http:\/\/www.visiondummy.com\/2014\/04\/curse-dimensionality-affect-classification\/\">curse of dimensionality<\/a>, i.e. your data becomes sparser and sparser as you increase the number of features considered, which usually leads to overfitting. While there is no rule of thumb relating to how many features vs. \u00a0the number of observations you should use, I try to keep e^Nf &lt; No (Nf = number of features, No = number of observations) to minimise overfitting [this is not always possible and it does not ensure that we won&#8217;t overfit]. In this case, our training set has 75 observations, which suggests that using four features (e^4 ~ 54.6) is not entirely absurd. Obviously, this depends on your data, so we will cover some further overfitting checks later on.<\/p>\n<p>2- An important thing to consider when assembling training sets is the proportion of negatives vs. positives in your data. Think of an extreme scenario where you have many, many more observations for one class vs. the others. How will this affect classification? This would make it more likely for the classifier to predict the dominant class when given new values. I mentioned before that the <em>iris<\/em> set is quite nice to play with. It comes with exactly 50 observations for each species of irises. What happens if you have a data set with a much higher number of observations for a particular class? You can bypass any imbalance regarding the representation of each class by carefully constructing your training set in order not to favour any particular class. In this case, our randomly selected set has 21 observations for species <em>setosa<\/em>\u00a0and 27 observations for each of species\u00a0<em>versicolor\u00a0<\/em>and\u00a0<em>virginica<\/em>, so we are good to go.<\/p>\n<p>3- Another common occurrence that is not represented by the <em>iris<\/em> data set is missing values (NAs) for observations. There are many ways of dealing with missing values, including assigning the median or the mode for that particular feature to the missing observation or even disregarding some observations entirely, depending on how many observations you have. There are even ways to use random forests to estimate a good value to assign to the missing observations, but for the sake of brevity, this will not be covered here.<\/p>\n<p>Right, data sets prepared and no missing values, it is time to fire our random forests algorithm. I am using the \u00a0<a href=\"https:\/\/cran.r-project.org\/web\/packages\/randomForest\/randomForest.pdf\"><em>randomForest\u00a0<\/em>package<\/a>. You can click the link for additional documentation. Here is the\u00a0example usage code:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"r\">#import the package\r\nlibrary(randomForest)\r\n# Perform training:\r\nrf_classifier = randomForest(Species ~ ., data=training, ntree=100, mtry=2, importance=TRUE)\r\n<\/pre>\n<p>Note some important parameters:<\/p>\n<p>-The first parameter specifies our formula: Species ~ . (we want to predict Species using each of the remaining columns of data).<br \/>\n&#8211;<em>ntree<\/em> defines the number of trees to be generated. It is typical to test a range of values for this parameter (i.e. 100,200,300,400,500) and choose the one that minimises the OOB estimate of error rate.<br \/>\n&#8211;<em>mtry<\/em> is the number of features used in the construction of each tree. These features are selected at random, which is where the &#8220;random&#8221; in &#8220;random forests&#8221; comes from. The default value for this parameter, when performing classification, is sqrt(number of features).<br \/>\n&#8211;<em>importance<\/em>\u00a0enables the algorithm to calculate variable importance.<\/p>\n<p>We can quickly look at the results of our classifier for our training set by printing the contents of <em>rf_classifier<\/em>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"r\">&gt; rf_classifier\r\n\r\nCall:\r\n randomForest(formula = Species ~ ., data = training,ntree=100,mtry=2, importance = TRUE) \r\n               Type of random forest: classification\r\n                     Number of trees: 100\r\nNo. of variables tried at each split: 2\r\n\r\n        OOB estimate of  error rate: 5.33%\r\nConfusion matrix:\r\n           setosa versicolor virginica class.error\r\nsetosa         21          0         0  0.00000000\r\nversicolor      0         25         2  0.07407407\r\nvirginica       0          2        25  0.07407407\r\n\r\n\r\n<\/pre>\n<p>As you can see, it lists the call used to build the classifier, the number of trees (100), the variables at each split (2), and it outputs a very useful confusion matrix and OOB estimate of error rate. This estimate is calculated by counting however many points in the training set were misclassified (2 versicolor and 2 virginica observations = 4) and dividing this number by the total number of observations (4\/75 ~= 5.33%).<\/p>\n<p>The OOB estimate of error rate is a useful measure to discriminate between different random forest classifiers. We could, for instance, vary the number of trees or the number of variables to be considered, and select the combination that produces the smallest value for this error rate. For more complicated data sets, i.e. when a higher number of features is present, a good idea is to use cross-validation to perform feature selection using the OOB error rate (see rfcv from randomForest for more details).<\/p>\n<p>Remember the\u00a0<em>importance<\/em> parameter? Let us take a look at the importance that our classifier has assigned to each variable:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"r\">varImpPlot(rf_classifier)\r\n<\/pre>\n<p style=\"text-align: center\"><a href=\"https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/04\/Blogpost2.png?ssl=1\"><img data-recalc-dims=\"1\" decoding=\"async\" loading=\"lazy\" class=\"aligncenter wp-image-3440 size-large\" src=\"https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/04\/Blogpost2.png?resize=625%2C313&#038;ssl=1\" alt=\"\" width=\"625\" height=\"313\" srcset=\"https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/04\/Blogpost2.png?resize=1024%2C512&amp;ssl=1 1024w, https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/04\/Blogpost2.png?resize=300%2C150&amp;ssl=1 300w, https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/04\/Blogpost2.png?resize=768%2C384&amp;ssl=1 768w, https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/04\/Blogpost2.png?resize=624%2C312&amp;ssl=1 624w, https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/04\/Blogpost2.png?w=2000&amp;ssl=1 2000w, https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/04\/Blogpost2.png?w=1250&amp;ssl=1 1250w, https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/04\/Blogpost2.png?w=1875&amp;ssl=1 1875w\" sizes=\"auto, (max-width: 625px) 100vw, 625px\" \/><\/a><\/p>\n<p style=\"text-align: left\">Each features&#8217;s importance is assessed based on two criteria:<\/p>\n<p style=\"text-align: left\">-MeanDecreaseAccuracy:\u00a0gives a rough estimate of the loss in prediction performance when that particular variable is omitted from the training set. Caveat: if two variables are somewhat redundant, then omitting one of them may not lead to massive gains in prediction performance, but would make\u00a0the second variable more important.<\/p>\n<p style=\"text-align: left\">-MeanDecreaseGini: GINI is\u00a0a measure of node impurity. Think of it like this, if you use this feature\u00a0to split the data, how pure will the nodes be? Highest purity means that each node contains only elements of a single class. Assessing the decrease in GINI when that feature\u00a0is omitted leads to an understanding of how important that feature is to split the data correctly.<\/p>\n<p style=\"text-align: left\">Do note that these measures are used to rank variables in terms of importance and, thus, their absolute values could be disregarded.<\/p>\n<p style=\"text-align: left\">Ok, great. Looks like we have a classifier that was properly trained and is producing somewhat good predictions for our training set. Shall we evaluate what happens when we try to use this classifier to predict classes for our \u00a0validation1 set?<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"r\"># Validation set assessment #1: looking at confusion matrix\r\nprediction_for_table &lt;- predict(rf_classifier,validation1[,-5])\r\ntable(observed=validation1[,5],predicted=prediction_for_table)\r\n\r\n            predicted\r\nobserved     setosa versicolor virginica\r\n  setosa         29          0         0\r\n  versicolor      0         20         3\r\n  virginica       0          1        22\r\n<\/pre>\n<p>The confusion matrix is a good way of looking at how good our classifier is performing when presented with new data.<\/p>\n<p>Another way of assessing the performance of our classifier is to generate a ROC curve and compute the area under the curve:<\/p>\n<p>&nbsp;<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"r\"># Validation set assessment #2: ROC curves and AUC\r\n\r\n# Needs to import ROCR package for ROC curve plotting:\r\nlibrary(ROCR)\r\n\r\n# Calculate the probability of new observations belonging to each class\r\n# prediction_for_roc_curve will be a matrix with dimensions data_set_size x number_of_classes\r\nprediction_for_roc_curve &lt;- predict(rf_classifier,validation1[,-5],type=\"prob\")\r\n\r\n# Use pretty colours:\r\npretty_colours &lt;- c(\"#F8766D\",\"#00BA38\",\"#619CFF\")\r\n# Specify the different classes \r\nclasses &lt;- levels(validation1$Species)\r\n# For each class\r\nfor (i in 1:3)\r\n{\r\n # Define which observations belong to class[i]\r\n true_values &lt;- ifelse(validation1[,5]==classes[i],1,0)\r\n # Assess the performance of classifier for class[i]\r\n pred &lt;- prediction(prediction_for_roc_curve[,i],true_values)\r\n perf &lt;- performance(pred, \"tpr\", \"fpr\")\r\n if (i==1)\r\n {\r\n     plot(perf,main=\"ROC Curve\",col=pretty_colours[i]) \r\n }\r\n else\r\n {\r\n     plot(perf,main=\"ROC Curve\",col=pretty_colours[i],add=TRUE) \r\n }\r\n # Calculate the AUC and print it to screen\r\n auc.perf &lt;- performance(pred, measure = \"auc\")\r\n print(auc.perf@y.values)\r\n}\r\n\r\n<\/pre>\n<p>Here is the final product (ROC curve):<\/p>\n<p style=\"text-align: center\"><a href=\"https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/04\/Blogpost3.png?ssl=1\"><img data-recalc-dims=\"1\" decoding=\"async\" loading=\"lazy\" class=\"alignnone size-large wp-image-3442\" src=\"https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/04\/Blogpost3.png?resize=625%2C625&#038;ssl=1\" alt=\"\" width=\"625\" height=\"625\" srcset=\"https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/04\/Blogpost3.png?resize=1024%2C1024&amp;ssl=1 1024w, https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/04\/Blogpost3.png?resize=150%2C150&amp;ssl=1 150w, https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/04\/Blogpost3.png?resize=300%2C300&amp;ssl=1 300w, https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/04\/Blogpost3.png?resize=768%2C768&amp;ssl=1 768w, https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/04\/Blogpost3.png?resize=624%2C624&amp;ssl=1 624w, https:\/\/i0.wp.com\/www.blopig.com\/blog\/wp-content\/uploads\/2017\/04\/Blogpost3.png?w=1200&amp;ssl=1 1200w\" sizes=\"auto, (max-width: 625px) 100vw, 625px\" \/><\/a><\/p>\n<p>And here are the values for our AUCs:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"r\">Setosa\r\nAUC = 1\r\n\r\nVersicolor\r\nAUC = 0.98\r\n\r\nVirginica\r\nAUC = 0.98\r\n<\/pre>\n<p>Voila! I hope this was somewhat useful!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Random Forests is a powerful tool used extensively across a multitude of fields. As a matter of fact, it is hard to come upon a data scientist that never had to resort to this technique at some point. Motivated by the fact that I have been using Random Forests quite a lot recently, I decided [&hellip;]<\/p>\n","protected":false},"author":11,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"nf_dc_page":"","wikipediapreview_detectlinks":true,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"ngg_post_thumbnail":0,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[29,14,15],"tags":[],"ppma_author":[505],"class_list":["post-3430","post","type-post","status-publish","format-standard","hentry","category-code","category-howto","category-technical"],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"authors":[{"term_id":505,"user_id":11,"is_guest":0,"slug":"saulo","display_name":"Saulo Pires de Oliveira","avatar_url":"https:\/\/secure.gravatar.com\/avatar\/5f63aaf111511b89e2975aad0ccbd7c0160152b90b2df36425f2db14218cdd13?s=96&d=mm&r=g","0":null,"1":"","2":"","3":"","4":"","5":"","6":"","7":"","8":""}],"_links":{"self":[{"href":"https:\/\/www.blopig.com\/blog\/wp-json\/wp\/v2\/posts\/3430","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.blopig.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.blopig.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.blopig.com\/blog\/wp-json\/wp\/v2\/users\/11"}],"replies":[{"embeddable":true,"href":"https:\/\/www.blopig.com\/blog\/wp-json\/wp\/v2\/comments?post=3430"}],"version-history":[{"count":11,"href":"https:\/\/www.blopig.com\/blog\/wp-json\/wp\/v2\/posts\/3430\/revisions"}],"predecessor-version":[{"id":3444,"href":"https:\/\/www.blopig.com\/blog\/wp-json\/wp\/v2\/posts\/3430\/revisions\/3444"}],"wp:attachment":[{"href":"https:\/\/www.blopig.com\/blog\/wp-json\/wp\/v2\/media?parent=3430"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.blopig.com\/blog\/wp-json\/wp\/v2\/categories?post=3430"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.blopig.com\/blog\/wp-json\/wp\/v2\/tags?post=3430"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.blopig.com\/blog\/wp-json\/wp\/v2\/ppma_author?post=3430"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}